openMSX
imgui.cc
Go to the documentation of this file.
1// dear imgui, v1.90.5 WIP
2// (main code and documentation)
3
4// Help:
5// - See links below.
6// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
7// - Read top of imgui.cpp for more details, links and comments.
8
9// Resources:
10// - FAQ ........................ https://dearimgui.com/faq (in repository as docs/FAQ.md)
11// - Homepage ................... https://github.com/ocornut/imgui
12// - Releases & changelog ....... https://github.com/ocornut/imgui/releases
13// - Gallery .................... https://github.com/ocornut/imgui/issues/6897 (please post your screenshots/video there!)
14// - Wiki ....................... https://github.com/ocornut/imgui/wiki (lots of good stuff there)
15// - Getting Started https://github.com/ocornut/imgui/wiki/Getting-Started (how to integrate in an existing app by adding ~25 lines of code)
16// - Third-party Extensions https://github.com/ocornut/imgui/wiki/Useful-Extensions (ImPlot & many more)
17// - Bindings/Backends https://github.com/ocornut/imgui/wiki/Bindings (language bindings, backends for various tech/engines)
18// - Glossary https://github.com/ocornut/imgui/wiki/Glossary
19// - Debug Tools https://github.com/ocornut/imgui/wiki/Debug-Tools
20// - Software using Dear ImGui https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui
21// - Issues & support ........... https://github.com/ocornut/imgui/issues
22// - Test Engine & Automation ... https://github.com/ocornut/imgui_test_engine (test suite, test engine to automate your apps)
23
24// For first-time users having issues compiling/linking/running/loading fonts:
25// please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
26// Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there.
27
28// Copyright (c) 2014-2024 Omar Cornut
29// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
30// See LICENSE.txt for copyright and licensing details (standard MIT License).
31// This library is free but needs your support to sustain development and maintenance.
32// Businesses: you can support continued development via B2B invoiced technical support, maintenance and sponsoring contracts.
33// PLEASE reach out at omar AT dearimgui DOT com. See https://github.com/ocornut/imgui/wiki/Sponsors
34// Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
35
36// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
37// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
38// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
39// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
40// to a better solution or official support for them.
41
42/*
43
44Index of this file:
45
46DOCUMENTATION
47
48- MISSION STATEMENT
49- CONTROLS GUIDE
50- PROGRAMMER GUIDE
51 - READ FIRST
52 - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
53 - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
54 - HOW A SIMPLE APPLICATION MAY LOOK LIKE
55 - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
56- API BREAKING CHANGES (read me when you update!)
57- FREQUENTLY ASKED QUESTIONS (FAQ)
58 - Read all answers online: https://www.dearimgui.com/faq, or in docs/FAQ.md (with a Markdown viewer)
59
60CODE
61(search for "[SECTION]" in the code to find them)
62
63// [SECTION] INCLUDES
64// [SECTION] FORWARD DECLARATIONS
65// [SECTION] CONTEXT AND MEMORY ALLOCATORS
66// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
67// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
68// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
69// [SECTION] MISC HELPERS/UTILITIES (File functions)
70// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
71// [SECTION] MISC HELPERS/UTILITIES (Color functions)
72// [SECTION] ImGuiStorage
73// [SECTION] ImGuiTextFilter
74// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
75// [SECTION] ImGuiListClipper
76// [SECTION] STYLING
77// [SECTION] RENDER HELPERS
78// [SECTION] INITIALIZATION, SHUTDOWN
79// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
80// [SECTION] INPUTS
81// [SECTION] ERROR CHECKING
82// [SECTION] ITEM SUBMISSION
83// [SECTION] LAYOUT
84// [SECTION] SCROLLING
85// [SECTION] TOOLTIPS
86// [SECTION] POPUPS
87// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
88// [SECTION] DRAG AND DROP
89// [SECTION] LOGGING/CAPTURING
90// [SECTION] SETTINGS
91// [SECTION] LOCALIZATION
92// [SECTION] VIEWPORTS, PLATFORM WINDOWS
93// [SECTION] DOCKING
94// [SECTION] PLATFORM DEPENDENT HELPERS
95// [SECTION] METRICS/DEBUGGER WINDOW
96// [SECTION] DEBUG LOG WINDOW
97// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
98
99*/
100
101//-----------------------------------------------------------------------------
102// DOCUMENTATION
103//-----------------------------------------------------------------------------
104
105/*
106
107 MISSION STATEMENT
108 =================
109
110 - Easy to use to create code-driven and data-driven tools.
111 - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
112 - Easy to hack and improve.
113 - Minimize setup and maintenance.
114 - Minimize state storage on user side.
115 - Minimize state synchronization.
116 - Portable, minimize dependencies, run on target (consoles, phones, etc.).
117 - Efficient runtime and memory consumption.
118
119 Designed primarily for developers and content-creators, not the typical end-user!
120 Some of the current weaknesses (which we aim to address in the future) includes:
121
122 - Doesn't look fancy.
123 - Limited layout features, intricate layouts are typically crafted in code.
124
125
126 CONTROLS GUIDE
127 ==============
128
129 - MOUSE CONTROLS
130 - Mouse wheel: Scroll vertically.
131 - SHIFT+Mouse wheel: Scroll horizontally.
132 - Click [X]: Close a window, available when 'bool* p_open' is passed to ImGui::Begin().
133 - Click ^, Double-Click title: Collapse window.
134 - Drag on corner/border: Resize window (double-click to auto fit window to its contents).
135 - Drag on any empty space: Move window (unless io.ConfigWindowsMoveFromTitleBarOnly = true).
136 - Left-click outside popup: Close popup stack (right-click over underlying popup: Partially close popup stack).
137
138 - TEXT EDITOR
139 - Hold SHIFT or Drag Mouse: Select text.
140 - CTRL+Left/Right: Word jump.
141 - CTRL+Shift+Left/Right: Select words.
142 - CTRL+A or Double-Click: Select All.
143 - CTRL+X, CTRL+C, CTRL+V: Use OS clipboard.
144 - CTRL+Z, CTRL+Y: Undo, Redo.
145 - ESCAPE: Revert text to its original value.
146 - On OSX, controls are automatically adjusted to match standard OSX text editing shortcuts and behaviors.
147
148 - KEYBOARD CONTROLS
149 - Basic:
150 - Tab, SHIFT+Tab Cycle through text editable fields.
151 - CTRL+Tab, CTRL+Shift+Tab Cycle through windows.
152 - CTRL+Click Input text into a Slider or Drag widget.
153 - Extended features with `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard`:
154 - Tab, SHIFT+Tab: Cycle through every items.
155 - Arrow keys Move through items using directional navigation. Tweak value.
156 - Arrow keys + Alt, Shift Tweak slower, tweak faster (when using arrow keys).
157 - Enter Activate item (prefer text input when possible).
158 - Space Activate item (prefer tweaking with arrows when possible).
159 - Escape Deactivate item, leave child window, close popup.
160 - Page Up, Page Down Previous page, next page.
161 - Home, End Scroll to top, scroll to bottom.
162 - Alt Toggle between scrolling layer and menu layer.
163 - CTRL+Tab then Ctrl+Arrows Move window. Hold SHIFT to resize instead of moving.
164 - Output when ImGuiConfigFlags_NavEnableKeyboard set,
165 - io.WantCaptureKeyboard flag is set when keyboard is claimed.
166 - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
167 - io.NavVisible: true when the navigation cursor is visible (usually goes to back false when mouse is used).
168
169 - GAMEPAD CONTROLS
170 - Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
171 - Particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse!
172 - Download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets
173 - Backend support: backend needs to:
174 - Set 'io.BackendFlags |= ImGuiBackendFlags_HasGamepad' + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
175 - For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
176 Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
177 - BEFORE 1.87, BACKENDS USED TO WRITE TO io.NavInputs[]. This is now obsolete. Please call io functions instead!
178 - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
179 with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
180
181 - REMOTE INPUTS SHARING & MOUSE EMULATION
182 - PS4/PS5 users: Consider emulating a mouse cursor with DualShock touch pad or a spare analog stick as a mouse-emulation fallback.
183 - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + run examples/libs/synergy/uSynergy.c (on your console/tablet/phone app)
184 in order to share your PC mouse/keyboard.
185 - See https://github.com/ocornut/imgui/wiki/Useful-Extensions#remoting for other remoting solutions.
186 - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
187 Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements.
188 When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
189 When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that.
190 (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, Dear ImGui will misbehave as it will see your mouse moving back & forth!)
191 (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
192 to set a boolean to ignore your other external mouse positions until the external source is moved again.)
193
194
195 PROGRAMMER GUIDE
196 ================
197
198 READ FIRST
199 ----------
200 - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
201 - Your code creates the UI every frame of your application loop, if your code doesn't run the UI is gone!
202 The UI can be highly dynamic, there are no construction or destruction steps, less superfluous
203 data retention on your side, less state duplication, less state synchronization, fewer bugs.
204 - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
205 Or browse https://pthom.github.io/imgui_manual_online/manual/imgui_manual.html for interactive web version.
206 - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
207 - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
208 You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
209 - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
210 For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI,
211 where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
212 - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
213 - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
214 If you get an assert, read the messages and comments around the assert.
215 - This codebase aims to be highly optimized:
216 - A typical idle frame should never call malloc/free.
217 - We rely on a maximum of constant-time or O(N) algorithms. Limiting searches/scans as much as possible.
218 - We put particular energy in making sure performances are decent with typical "Debug" build settings as well.
219 Which mean we tend to avoid over-relying on "zero-cost abstraction" as they aren't zero-cost at all.
220 - This codebase aims to be both highly opinionated and highly flexible:
221 - This code works because of the things it choose to solve or not solve.
222 - C++: this is a pragmatic C-ish codebase: we don't use fancy C++ features, we don't include C++ headers,
223 and ImGui:: is a namespace. We rarely use member functions (and when we did, I am mostly regretting it now).
224 This is to increase compatibility, increase maintainability and facilitate use from other languages.
225 - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
226 See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
227 We can can optionally export math operators for ImVec2/ImVec4 using IMGUI_DEFINE_MATH_OPERATORS, which we use internally.
228 - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction
229 (so don't use ImVector in your code or at our own risk!).
230 - Building: We don't use nor mandate a build system for the main library.
231 This is in an effort to ensure that it works in the real world aka with any esoteric build setup.
232 This is also because providing a build system for the main library would be of little-value.
233 The build problems are almost never coming from the main library but from specific backends.
234
235
236 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
237 ----------------------------------------------
238 - Update submodule or copy/overwrite every file.
239 - About imconfig.h:
240 - You may modify your copy of imconfig.h, in this case don't overwrite it.
241 - or you may locally branch to modify imconfig.h and merge/rebase latest.
242 - or you may '#define IMGUI_USER_CONFIG "my_config_file.h"' globally from your build system to
243 specify a custom path for your imconfig.h file and instead not have to modify the default one.
244
245 - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
246 - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
247 - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
248 - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
249 If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
250 from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
251 likely be a comment about it. Please report any issue to the GitHub page!
252 - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
253 - Try to keep your copy of Dear ImGui reasonably up to date!
254
255
256 GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
257 ---------------------------------------------------------------
258 - See https://github.com/ocornut/imgui/wiki/Getting-Started.
259 - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
260 - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
261 - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
262 It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
263 - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
264 - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
265 - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
266 Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
267 phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
268 - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
269 - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
270
271
272 HOW A SIMPLE APPLICATION MAY LOOK LIKE
273 --------------------------------------
274 EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
275 The sub-folders in examples/ contain examples applications following this structure.
276
277 // Application init: create a dear imgui context, setup some options, load fonts
278 ImGui::CreateContext();
279 ImGuiIO& io = ImGui::GetIO();
280 // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
281 // TODO: Fill optional fields of the io structure later.
282 // TODO: Load TTF/OTF fonts if you don't want to use the default font.
283
284 // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
285 ImGui_ImplWin32_Init(hwnd);
286 ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
287
288 // Application main loop
289 while (true)
290 {
291 // Feed inputs to dear imgui, start new frame
292 ImGui_ImplDX11_NewFrame();
293 ImGui_ImplWin32_NewFrame();
294 ImGui::NewFrame();
295
296 // Any application code here
297 ImGui::Text("Hello, world!");
298
299 // Render dear imgui into screen
300 ImGui::Render();
301 ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
302 g_pSwapChain->Present(1, 0);
303 }
304
305 // Shutdown
306 ImGui_ImplDX11_Shutdown();
307 ImGui_ImplWin32_Shutdown();
308 ImGui::DestroyContext();
309
310 EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
311
312 // Application init: create a dear imgui context, setup some options, load fonts
313 ImGui::CreateContext();
314 ImGuiIO& io = ImGui::GetIO();
315 // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
316 // TODO: Fill optional fields of the io structure later.
317 // TODO: Load TTF/OTF fonts if you don't want to use the default font.
318
319 // Build and load the texture atlas into a texture
320 // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
321 int width, height;
322 unsigned char* pixels = nullptr;
323 io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
324
325 // At this point you've got the texture data and you need to upload that to your graphic system:
326 // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
327 // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
328 MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
329 io.Fonts->SetTexID((void*)texture);
330
331 // Application main loop
332 while (true)
333 {
334 // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
335 // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
336 io.DeltaTime = 1.0f/60.0f; // set the time elapsed since the previous frame (in seconds)
337 io.DisplaySize.x = 1920.0f; // set the current display width
338 io.DisplaySize.y = 1280.0f; // set the current display height here
339 io.AddMousePosEvent(mouse_x, mouse_y); // update mouse position
340 io.AddMouseButtonEvent(0, mouse_b[0]); // update mouse button states
341 io.AddMouseButtonEvent(1, mouse_b[1]); // update mouse button states
342
343 // Call NewFrame(), after this point you can use ImGui::* functions anytime
344 // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
345 ImGui::NewFrame();
346
347 // Most of your application code here
348 ImGui::Text("Hello, world!");
349 MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
350 MyGameRender(); // may use any Dear ImGui functions as well!
351
352 // Render dear imgui, swap buffers
353 // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
354 ImGui::EndFrame();
355 ImGui::Render();
356 ImDrawData* draw_data = ImGui::GetDrawData();
357 MyImGuiRenderFunction(draw_data);
358 SwapBuffers();
359 }
360
361 // Shutdown
362 ImGui::DestroyContext();
363
364 To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
365 you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
366 Please read the FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" about this.
367
368
369 HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
370 ---------------------------------------------
371 The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
372
373 void MyImGuiRenderFunction(ImDrawData* draw_data)
374 {
375 // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
376 // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering.
377 // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
378 // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
379 // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
380 ImVec2 clip_off = draw_data->DisplayPos;
381 for (int n = 0; n < draw_data->CmdListsCount; n++)
382 {
383 const ImDrawList* cmd_list = draw_data->CmdLists[n];
384 const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by Dear ImGui
385 const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by Dear ImGui
386 for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
387 {
388 const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
389 if (pcmd->UserCallback)
390 {
391 pcmd->UserCallback(cmd_list, pcmd);
392 }
393 else
394 {
395 // Project scissor/clipping rectangles into framebuffer space
396 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
397 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
398 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
399 continue;
400
401 // We are using scissoring to clip some objects. All low-level graphics API should support it.
402 // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
403 // (some elements visible outside their bounds) but you can fix that once everything else works!
404 // - Clipping coordinates are provided in imgui coordinates space:
405 // - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
406 // - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values.
407 // - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
408 // always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
409 // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
410 MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y);
411
412 // The texture for the draw call is specified by pcmd->GetTexID().
413 // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
414 MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
415
416 // Render 'pcmd->ElemCount/3' indexed triangles.
417 // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
418 MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset);
419 }
420 }
421 }
422 }
423
424
425 API BREAKING CHANGES
426 ====================
427
428 Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
429 Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
430 When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
431 You can read releases logs https://github.com/ocornut/imgui/releases for more details.
432
433(Docking/Viewport Branch)
434 - 2024/XX/XX (1.XXXX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
435 - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore.
436 you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos)
437 - likewise io.MousePos and GetMousePos() will use OS coordinates.
438 If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos.
439
440 - 2024/01/15 (1.90.2) - commented out obsolete ImGuiIO::ImeWindowHandle marked obsolete in 1.87, favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
441 - 2023/12/19 (1.90.1) - commented out obsolete ImGuiKey_KeyPadEnter redirection to ImGuiKey_KeypadEnter.
442 - 2023/11/06 (1.90.1) - removed CalcListClipping() marked obsolete in 1.86. Prefer using ImGuiListClipper which can return non-contiguous ranges.
443 - 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.
444 - 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.
445 - 2023/11/09 (1.90.0) - removed IM_OFFSETOF() macro in favor of using offsetof() available in C++11. Kept redirection define (will obsolete).
446 - 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).
447 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.
448 - 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.
449 - old: BeginChild("Name", size, true)
450 - new: BeginChild("Name", size, ImGuiChildFlags_Border)
451 - old: BeginChild("Name", size, false)
452 - new: BeginChild("Name", size) or BeginChild("Name", 0) or BeginChild("Name", size, ImGuiChildFlags_None)
453 - 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.
454 - old: BeginChild("Name", size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding);
455 - new: BeginChild("Name", size, ImGuiChildFlags_AlwaysUseWindowPadding, 0);
456 - 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).
457 - 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)
458 - 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).
459 - old: bool Combo(const char* label, int* current_item, bool (*getter)(void* user_data, int idx, const char** out_text), ...)
460 - new: bool Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
461 - old: bool ListBox(const char* label, int* current_item, bool (*getting)(void* user_data, int idx, const char** out_text), ...);
462 - new: bool ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
463 - 2023/09/08 (1.90.0) - commented out obsolete redirecting functions:
464 - GetWindowContentRegionWidth() -> use GetWindowContentRegionMax().x - GetWindowContentRegionMin().x. Consider that generally 'GetContentRegionAvail().x' is more useful.
465 - ImDrawCornerFlags_XXX -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details + grep commented names in sources.
466 - 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
467 - 2023/08/25 (1.89.9) - clipper: Renamed IncludeRangeByIndices() (also called ForceDisplayRangeByIndices() before 1.89.6) to IncludeItemsByIndex(). Kept inline redirection function. Sorry!
468 - 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)
469 - 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).
470 - 2023/06/28 (1.89.7) - overlapping items: renamed 'ImGuiTreeNodeFlags_AllowItemOverlap' to 'ImGuiTreeNodeFlags_AllowOverlap', 'ImGuiSelectableFlags_AllowItemOverlap' to 'ImGuiSelectableFlags_AllowOverlap'. Kept redirecting enums (will obsolete).
471 - 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.
472 - 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)
473 - 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.
474 - 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.
475 - 2023/05/22 (1.89.6) - listbox: commented out obsolete/redirecting functions that were marked obsolete more than two years ago:
476 - ListBoxHeader() -> use BeginListBox() (note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for reference)
477 - ListBoxFooter() -> use EndListBox()
478 - 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().
479 - 2023/05/15 (1.89.6) - clipper: renamed ImGuiListClipper::ForceDisplayRangeByIndices() to ImGuiListClipper::IncludeRangeByIndices().
480 - 2023/03/14 (1.89.4) - commented out redirecting enums/functions names that were marked obsolete two years ago:
481 - ImGuiSliderFlags_ClampOnInput -> use ImGuiSliderFlags_AlwaysClamp
482 - ImGuiInputTextFlags_AlwaysInsertMode -> use ImGuiInputTextFlags_AlwaysOverwrite
483 - ImDrawList::AddBezierCurve() -> use ImDrawList::AddBezierCubic()
484 - ImDrawList::PathBezierCurveTo() -> use ImDrawList::PathBezierCubicCurveTo()
485 - 2023/03/09 (1.89.4) - renamed PushAllowKeyboardFocus()/PopAllowKeyboardFocus() to PushTabStop()/PopTabStop(). Kept inline redirection functions (will obsolete).
486 - 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.
487 - 2023/02/15 (1.89.4) - moved the optional "courtesy maths operators" implementation from imgui_internal.h in imgui.h.
488 Even though we encourage using your own maths types and operators by setting up IM_VEC2_CLASS_EXTRA,
489 it has been frequently requested by people to use our own. We had an opt-in define which was
490 previously fulfilled in imgui_internal.h. It is now fulfilled in imgui.h. (#6164)
491 - OK: #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui.h" / #include "imgui_internal.h"
492 - Error: #include "imgui.h" / #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui_internal.h"
493 - 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.
494 - 2022/10/26 (1.89) - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
495 - 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.
496 - 2022/09/26 (1.89) - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
497 - ImGuiKey_ModCtrl and ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl
498 - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
499 - ImGuiKey_ModAlt and ImGuiModFlags_Alt -> ImGuiMod_Alt
500 - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
501 the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
502 the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
503 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.
504 - 2022/09/20 (1.89) - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers.
505 this will require uses of legacy backend-dependent indices to be casted, e.g.
506 - with imgui_impl_glfw: IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A);
507 - with imgui_impl_win32: IsKeyPressed('A') -> IsKeyPressed((ImGuiKey)'A')
508 - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now!
509 - 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);
510 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
511 - 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.
512 - 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.
513 - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
514 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
515 this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
516 - previously this would make the window content size ~200x200:
517 Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
518 - instead, please submit an item:
519 Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
520 - alternative:
521 Begin(...) + Dummy(ImVec2(200,200)) + End();
522 - content size is now only extended when submitting an item!
523 - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
524 - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
525 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
526 - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
527 - 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));
528 - 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.
529 - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
530 - 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));
531 - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
532 - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
533 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
534 - Official backends from 1.87+ -> no issue.
535 - Official backends from 1.60 to 1.86 -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
536 - Custom backends not writing to io.NavInputs[] -> no issue.
537 - Custom backends writing to io.NavInputs[] -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
538 - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
539 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
540 - 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.
541 - 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.
542 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
543 - Backend writing to io.NavInputs[] -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
544 - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputing text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
545 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
546 - Backend writing to io.MousePos -> backend should call io.AddMousePosEvent()
547 - Backend writing to io.MouseDown[] -> backend should call io.AddMouseButtonEvent()
548 - Backend writing to io.MouseWheel -> backend should call io.AddMouseWheelEvent()
549 - Backend writing to io.MouseHoveredViewport -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
550 note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
551 read https://github.com/ocornut/imgui/issues/4921 for details.
552 - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.
553 - IsKeyPressed(MY_NATIVE_KEY_XXX) -> use IsKeyPressed(ImGuiKey_XXX)
554 - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX)
555 - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes).
556 - 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.*
557 - 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.
558 - 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.
559 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
560 - 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'.
561 - 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)
562 - ImGui::SetNextTreeNodeOpen() -> use ImGui::SetNextItemOpen()
563 - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
564 - ImGui::TreeAdvanceToLabelPos() -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
565 - ImFontAtlas::CustomRect -> use ImFontAtlasCustomRect
566 - ImGuiColorEditFlags_RGB/HSV/HEX -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
567 - 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
568 - 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.
569 - 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.
570 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
571 - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
572 - ImFont::GlyphRangesBuilder -> use ImFontGlyphRangesBuilder
573 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
574 - if you are using official backends from the source tree: you have nothing to do.
575 - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
576 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
577 - ImDrawCornerFlags_TopLeft -> use ImDrawFlags_RoundCornersTopLeft
578 - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
579 - ImDrawCornerFlags_None -> use ImDrawFlags_RoundCornersNone etc.
580 flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
581 breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
582 - rounding == 0.0f + flags == 0 --> meant no rounding --> unchanged (common use)
583 - rounding > 0.0f + flags != 0 --> meant rounding --> unchanged (common use)
584 - rounding == 0.0f + flags != 0 --> meant no rounding --> unchanged (unlikely use)
585 - rounding > 0.0f + flags == 0 --> meant no rounding --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
586 this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
587 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.
588 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).
589 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
590 - ImGui::SetScrollHere() -> use ImGui::SetScrollHereY()
591 - 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.
592 - 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.
593 - 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'.
594 - 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.
595 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
596 - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
597 - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
598 - 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.
599 - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
600 - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
601 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
602 - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
603 - ImGuiCol_ModalWindowDarkening -> use ImGuiCol_ModalWindowDimBg
604 - ImGuiInputTextCallback -> use ImGuiTextEditCallback
605 - ImGuiInputTextCallbackData -> use ImGuiTextEditCallbackData
606 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
607 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
608 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
609 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
610 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
611 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
612 - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your backend
613 - ImGui::IsAnyWindowFocused() -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
614 - ImGui::IsAnyWindowHovered() -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
615 - ImGuiStyleVar_Count_ -> use ImGuiStyleVar_COUNT
616 - ImGuiMouseCursor_Count_ -> use ImGuiMouseCursor_COUNT
617 - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
618 - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
619 - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
620 - 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).
621 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
622 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
623 - 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.
624 - 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.
625 - 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!
626 - 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().
627 replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
628 worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
629 - if you omitted the 'power' parameter (likely!), you are not affected.
630 - 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.
631 - 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.
632 see https://github.com/ocornut/imgui/issues/3361 for all details.
633 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.
634 for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
635 - 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.
636 - 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.
637 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
638 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
639 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
640 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
641 - 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.
642 - 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.
643 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
644 - ShowTestWindow() -> use ShowDemoWindow()
645 - IsRootWindowFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
646 - IsRootWindowOrAnyChildFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
647 - SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
648 - GetItemsLineHeightWithSpacing() -> use GetFrameHeightWithSpacing()
649 - ImGuiCol_ChildWindowBg -> use ImGuiCol_ChildBg
650 - ImGuiStyleVar_ChildWindowRounding -> use ImGuiStyleVar_ChildRounding
651 - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
652 - IMGUI_DISABLE_TEST_WINDOWS -> use IMGUI_DISABLE_DEMO_WINDOWS
653 - 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.
654 - 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).
655 - 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.
656 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
657 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
658 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
659 - Begin() [old 5 args version] -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
660 - IsRootWindowOrAnyChildHovered() -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
661 - AlignFirstTextHeightToWidgets() -> use AlignTextToFramePadding()
662 - SetNextWindowPosCenter() -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
663 - ImFont::Glyph -> use ImFontGlyph
664 - 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.
665 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.
666 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).
667 If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
668 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
669 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
670 - 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.
671 - 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
672 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.
673 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.
674 Please reach out if you are affected.
675 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
676 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
677 - 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.
678 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
679 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
680 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
681 - 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!
682 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
683 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
684 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
685 - 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.
686 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
687 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
688 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
689 - 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.
690 If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
691 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
692 - 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.
693 NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
694 Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
695 - 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).
696 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
697 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
698 - 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.
699 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
700 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
701 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
702 - 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.).
703 old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
704 when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
705 in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
706 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
707 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
708 - 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.
709 If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
710 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.
711 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.
712 - 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",
713 consistent with other functions. Kept redirection functions (will obsolete).
714 - 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.
715 - 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).
716 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
717 - 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.
718 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
719 - 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.
720 - 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.
721 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
722 - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
723 - removed Shutdown() function, as DestroyContext() serve this purpose.
724 - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
725 - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
726 - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
727 - 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.
728 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
729 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
730 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
731 - 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.
732 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
733 - 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
734 - 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.
735 - 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.
736 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
737 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
738 - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
739 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
740 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
741 - 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.
742 - 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.
743 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.
744 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
745 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
746 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
747 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
748 - 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.
749 - 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.
750 - 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.
751 removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
752 IsItemHoveredRect() --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
753 IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
754 IsMouseHoveringWindow() --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
755 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
756 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
757 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
758 - 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).
759 - 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)".
760 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
761 - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
762 - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
763 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
764 - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
765 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
766 - 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.
767 - 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).
768 - 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).
769 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
770 - 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.
771 - 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.
772 - 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))'
773 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
774 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
775 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
776 - 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().
777 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
778 - 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.
779 - 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.
780 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
781 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.
782 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:
783 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); }
784 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.
785 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
786 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
787 - 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).
788 - 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.
789 - 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).
790 - 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)
791 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
792 - 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.
793 - 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.
794 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
795 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
796 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
797 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.
798 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!
799 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
800 - 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.
801 - 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
802 - 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.
803 you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
804 - 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.
805 this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
806 - 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.
807 - the signature of the io.RenderDrawListsFn handler has changed!
808 old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
809 new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
810 parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
811 ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
812 ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
813 - 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.
814 - 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!
815 - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
816 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
817 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
818 - 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.
819 - 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
820 - 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!
821 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
822 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
823 - 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.
824 - 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.
825 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
826 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
827 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
828 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
829 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
830 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
831 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
832 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
833 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
834 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
835 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
836 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
837 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
838 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
839 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
840 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
841 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
842 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
843 - old: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
844 - new: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
845 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.
846 - 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()
847 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
848 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
849 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
850 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
851 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
852 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
853 - 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)
854 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
855 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
856 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
857 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
858 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
859 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
860
861
862 FREQUENTLY ASKED QUESTIONS (FAQ)
863 ================================
864
865 Read all answers online:
866 https://www.dearimgui.com/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
867 Read all answers locally (with a text editor or ideally a Markdown viewer):
868 docs/FAQ.md
869 Some answers are copied down here to facilitate searching in code.
870
871 Q&A: Basics
872 ===========
873
874 Q: Where is the documentation?
875 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
876 - Run the examples/ applications and explore them.
877 - Read Getting Started (https://github.com/ocornut/imgui/wiki/Getting-Started) guide.
878 - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
879 - The demo covers most features of Dear ImGui, so you can read the code and see its output.
880 - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
881 - 20+ standalone example applications using e.g. OpenGL/DirectX are provided in the
882 examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
883 - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
884 - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
885 - Your programming IDE is your friend, find the type or function declaration to find comments
886 associated with it.
887
888 Q: What is this library called?
889 Q: Which version should I get?
890 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
891 >> See https://www.dearimgui.com/faq for details.
892
893 Q&A: Integration
894 ================
895
896 Q: How to get started?
897 A: Read https://github.com/ocornut/imgui/wiki/Getting-Started. Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
898
899 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
900 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
901 >> See https://www.dearimgui.com/faq for a fully detailed answer. You really want to read this.
902
903 Q. How can I enable keyboard or gamepad controls?
904 Q: How can I use this on a machine without mouse, keyboard or screen? (input share, remote display)
905 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
906 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
907 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
908 >> See https://www.dearimgui.com/faq
909
910 Q&A: Usage
911 ----------
912
913 Q: About the ID Stack system..
914 - Why is my widget not reacting when I click on it?
915 - How can I have widgets with an empty label?
916 - How can I have multiple widgets with the same label?
917 - How can I have multiple windows with the same label?
918 Q: How can I display an image? What is ImTextureID, how does it work?
919 Q: How can I use my own math types instead of ImVec2?
920 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
921 Q: How can I display custom shapes? (using low-level ImDrawList API)
922 >> See https://www.dearimgui.com/faq
923
924 Q&A: Fonts, Text
925 ================
926
927 Q: How should I handle DPI in my application?
928 Q: How can I load a different font than the default?
929 Q: How can I easily use icons in my application?
930 Q: How can I load multiple fonts?
931 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
932 >> See https://www.dearimgui.com/faq and https://github.com/ocornut/imgui/blob/master/docs/FONTS.md
933
934 Q&A: Concerns
935 =============
936
937 Q: Who uses Dear ImGui?
938 Q: Can you create elaborate/serious tools with Dear ImGui?
939 Q: Can you reskin the look of Dear ImGui?
940 Q: Why using C++ (as opposed to C)?
941 >> See https://www.dearimgui.com/faq
942
943 Q&A: Community
944 ==============
945
946 Q: How can I help?
947 A: - Businesses: please reach out to "omar AT dearimgui DOT com" if you work in a place using Dear ImGui!
948 We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
949 This is among the most useful thing you can do for Dear ImGui. With increased funding, we sustain and grow work on this project.
950 Also see https://github.com/ocornut/imgui/wiki/Sponsors
951 - Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
952 - 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!
953 - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
954 You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
955 But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
956 - 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).
957
958*/
959
960//-------------------------------------------------------------------------
961// [SECTION] INCLUDES
962//-------------------------------------------------------------------------
963
964#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
965#define _CRT_SECURE_NO_WARNINGS
966#endif
967
968#ifndef IMGUI_DEFINE_MATH_OPERATORS
969#define IMGUI_DEFINE_MATH_OPERATORS
970#endif
971
972#include "imgui.h"
973#ifndef IMGUI_DISABLE
974#include "imgui_internal.h"
975
976// System includes
977#include <stdio.h> // vsnprintf, sscanf, printf
978#include <stdint.h> // intptr_t
979
980// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
981#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
982#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
983#endif
984
985// [Windows] OS specific includes (optional)
986#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
987#define IMGUI_DISABLE_WIN32_FUNCTIONS
988#endif
989#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
990#ifndef WIN32_LEAN_AND_MEAN
991#define WIN32_LEAN_AND_MEAN
992#endif
993#ifndef NOMINMAX
994#define NOMINMAX
995#endif
996#ifndef __MINGW32__
997#include <Windows.h> // _wfopen, OpenClipboard
998#else
999#include <windows.h>
1000#endif
1001#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have all Win32 functions
1002#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
1003#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
1004#endif
1005#endif
1006
1007// [Apple] OS specific includes
1008#if defined(__APPLE__)
1009#include <TargetConditionals.h>
1010#endif
1011
1012// Visual Studio warnings
1013#ifdef _MSC_VER
1014#pragma warning (disable: 4127) // condition expression is constant
1015#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
1016#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later
1017#pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types
1018#endif
1019#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).
1020#pragma warning (disable: 26495) // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
1021#pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
1022#endif
1023
1024// Clang/GCC warnings with -Weverything
1025#if defined(__clang__)
1026#if __has_warning("-Wunknown-warning-option")
1027#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!
1028#endif
1029#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
1030#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
1031#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.
1032#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.
1033#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.
1034#pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is.
1035#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
1036#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.
1037#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type 'int'
1038#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
1039#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.
1040#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
1041#elif defined(__GNUC__)
1042// We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
1043#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
1044#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
1045#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
1046#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
1047#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
1048#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
1049#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
1050#pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
1051#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
1052#endif
1053
1054// Debug options
1055#define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
1056#define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window
1057
1058// 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.
1059static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in
1060static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear
1061
1062static const float NAV_ACTIVATE_HIGHLIGHT_TIMER = 0.10f; // Time to highlight an item activated by a shortcut.
1063
1064// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
1065static const float WINDOWS_HOVER_PADDING = 4.0f; // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
1066static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time.
1067static 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.
1068
1069// Tooltip offset
1070static const ImVec2 TOOLTIP_DEFAULT_OFFSET = ImVec2(16, 10); // Multiplied by g.Style.MouseCursorScale
1071
1072// Docking
1073static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA = 0.50f; // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
1074
1075//-------------------------------------------------------------------------
1076// [SECTION] FORWARD DECLARATIONS
1077//-------------------------------------------------------------------------
1078
1079static void SetCurrentWindow(ImGuiWindow* window);
1080static void FindHoveredWindow();
1081static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags);
1082static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
1083
1084static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
1085
1086// Settings
1087static void WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
1088static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
1089static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
1090static void WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
1091static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
1092
1093// Platform Dependents default implementation for IO functions
1094static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx);
1095static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text);
1096static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
1097
1098namespace ImGui
1099{
1100// Navigation
1101static void NavUpdate();
1102static void NavUpdateWindowing();
1103static void NavUpdateWindowingOverlay();
1104static void NavUpdateCancelRequest();
1105static void NavUpdateCreateMoveRequest();
1106static void NavUpdateCreateTabbingRequest();
1107static float NavUpdatePageUpPageDown();
1108static inline void NavUpdateAnyRequestFlag();
1109static void NavUpdateCreateWrappingRequest();
1110static void NavEndFrame();
1111static bool NavScoreItem(ImGuiNavItemData* result);
1112static void NavApplyItemToResult(ImGuiNavItemData* result);
1113static void NavProcessItem();
1114static void NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags);
1115static ImVec2 NavCalcPreferredRefPos();
1116static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1117static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window);
1118static void NavRestoreLayer(ImGuiNavLayer layer);
1119static int FindWindowFocusIndex(ImGuiWindow* window);
1120
1121// Error Checking and Debug Tools
1122static void ErrorCheckNewFrameSanityChecks();
1123static void ErrorCheckEndFrameSanityChecks();
1124static void UpdateDebugToolItemPicker();
1125static void UpdateDebugToolStackQueries();
1126static void UpdateDebugToolFlashStyleColor();
1127
1128// Inputs
1129static void UpdateKeyboardInputs();
1130static void UpdateMouseInputs();
1131static void UpdateMouseWheel();
1132static void UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
1133
1134// Misc
1135static void UpdateSettings();
1136static 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);
1137static void RenderWindowOuterBorders(ImGuiWindow* window);
1138static 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);
1139static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1140static void RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1141static void RenderDimmedBackgrounds();
1142
1143// Viewports
1144const 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.
1145static ImGuiViewportP* AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
1146static void DestroyViewport(ImGuiViewportP* viewport);
1147static void UpdateViewportsNewFrame();
1148static void UpdateViewportsEndFrame();
1149static void WindowSelectViewport(ImGuiWindow* window);
1150static void WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack);
1151static bool UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
1152static bool UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
1153static bool GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
1154static int FindPlatformMonitorForPos(const ImVec2& pos);
1155static int FindPlatformMonitorForRect(const ImRect& r);
1156static void UpdateViewportPlatformMonitor(ImGuiViewportP* viewport);
1157
1158}
1159
1160//-----------------------------------------------------------------------------
1161// [SECTION] CONTEXT AND MEMORY ALLOCATORS
1162//-----------------------------------------------------------------------------
1163
1164// DLL users:
1165// - Heaps and globals are not shared across DLL boundaries!
1166// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1167// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1168// - 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.
1169// - 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).
1170
1171// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1172// - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1173// Change to a different context by calling ImGui::SetCurrentContext().
1174// - Important: Dear ImGui functions are not thread-safe because of this pointer.
1175// If you want thread-safety to allow N threads to access N different contexts:
1176// - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1177// struct ImGuiContext;
1178// extern thread_local ImGuiContext* MyImGuiTLS;
1179// #define GImGui MyImGuiTLS
1180// 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.
1181// - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1182// - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1183// - DLL users: read comments above.
1184#ifndef GImGui
1185ImGuiContext* GImGui = NULL;
1186#endif
1187
1188// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1189// - 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.
1190// - DLL users: read comments above.
1191#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1192static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); return malloc(size); }
1193static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); free(ptr); }
1194#else
1195static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1196static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1197#endif
1198static ImGuiMemAllocFunc GImAllocatorAllocFunc = MallocWrapper;
1199static ImGuiMemFreeFunc GImAllocatorFreeFunc = FreeWrapper;
1200static void* GImAllocatorUserData = NULL;
1201
1202//-----------------------------------------------------------------------------
1203// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
1204//-----------------------------------------------------------------------------
1205
1206ImGuiStyle::ImGuiStyle()
1207{
1208 Alpha = 1.0f; // Global alpha applies to everything in Dear ImGui.
1209 DisabledAlpha = 0.60f; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1210 WindowPadding = ImVec2(8,8); // Padding within a window
1211 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.
1212 WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1213 WindowMinSize = ImVec2(32,32); // Minimum window size
1214 WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
1215 WindowMenuButtonPosition= ImGuiDir_Left; // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1216 ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1217 ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1218 PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1219 PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1220 FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets)
1221 FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1222 FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1223 ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
1224 ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1225 CellPadding = ImVec2(4,2); // Padding within a table cell. CellPadding.y may be altered between different rows.
1226 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!
1227 IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1228 ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1229 ScrollbarSize = 14.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
1230 ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
1231 GrabMinSize = 12.0f; // Minimum width/height of a grab box for slider/scrollbar
1232 GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1233 LogSliderDeadzone = 4.0f; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1234 TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1235 TabBorderSize = 0.0f; // Thickness of border around tabs.
1236 TabMinWidthForCloseButton = 0.0f; // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
1237 TabBarBorderSize = 1.0f; // Thickness of tab-bar separator, which takes on the tab active color to denote focus.
1238 TableAngledHeadersAngle = 35.0f * (IM_PI / 180.0f); // Angle of angled headers (supported values range from -50 degrees to +50 degrees).
1239 ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1240 ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1241 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.
1242 SeparatorTextBorderSize = 3.0f; // Thickkness of border in SeparatorText()
1243 SeparatorTextAlign = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center).
1244 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.
1245 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.
1246 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.
1247 DockingSeparatorSize = 2.0f; // Thickness of resizing border between docked windows
1248 MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1249 AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1250 AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
1251 AntiAliasedFill = true; // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1252 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.
1253 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.
1254
1255 // Behaviors
1256 HoverStationaryDelay = 0.15f; // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary.
1257 HoverDelayShort = 0.15f; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayShort). Usually used along with HoverStationaryDelay.
1258 HoverDelayNormal = 0.40f; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayNormal). "
1259 HoverFlagsForTooltipMouse = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse.
1260 HoverFlagsForTooltipNav = ImGuiHoveredFlags_NoSharedDelay | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad.
1261
1262 // Default theme
1263 ImGui::StyleColorsDark(this);
1264}
1265
1266// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
1267// 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.
1268void ImGuiStyle::ScaleAllSizes(float scale_factor)
1269{
1270 WindowPadding = ImTrunc(WindowPadding * scale_factor);
1271 WindowRounding = ImTrunc(WindowRounding * scale_factor);
1272 WindowMinSize = ImTrunc(WindowMinSize * scale_factor);
1273 ChildRounding = ImTrunc(ChildRounding * scale_factor);
1274 PopupRounding = ImTrunc(PopupRounding * scale_factor);
1275 FramePadding = ImTrunc(FramePadding * scale_factor);
1276 FrameRounding = ImTrunc(FrameRounding * scale_factor);
1277 ItemSpacing = ImTrunc(ItemSpacing * scale_factor);
1278 ItemInnerSpacing = ImTrunc(ItemInnerSpacing * scale_factor);
1279 CellPadding = ImTrunc(CellPadding * scale_factor);
1280 TouchExtraPadding = ImTrunc(TouchExtraPadding * scale_factor);
1281 IndentSpacing = ImTrunc(IndentSpacing * scale_factor);
1282 ColumnsMinSpacing = ImTrunc(ColumnsMinSpacing * scale_factor);
1283 ScrollbarSize = ImTrunc(ScrollbarSize * scale_factor);
1284 ScrollbarRounding = ImTrunc(ScrollbarRounding * scale_factor);
1285 GrabMinSize = ImTrunc(GrabMinSize * scale_factor);
1286 GrabRounding = ImTrunc(GrabRounding * scale_factor);
1287 LogSliderDeadzone = ImTrunc(LogSliderDeadzone * scale_factor);
1288 TabRounding = ImTrunc(TabRounding * scale_factor);
1289 TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImTrunc(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
1290 SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor);
1291 DockingSeparatorSize = ImTrunc(DockingSeparatorSize * scale_factor);
1292 DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor);
1293 DisplaySafeAreaPadding = ImTrunc(DisplaySafeAreaPadding * scale_factor);
1294 MouseCursorScale = ImTrunc(MouseCursorScale * scale_factor);
1295}
1296
1297ImGuiIO::ImGuiIO()
1298{
1299 // Most fields are initialized with zero
1300 memset(this, 0, sizeof(*this));
1301 IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1302
1303 // Settings
1304 ConfigFlags = ImGuiConfigFlags_None;
1305 BackendFlags = ImGuiBackendFlags_None;
1306 DisplaySize = ImVec2(-1.0f, -1.0f);
1307 DeltaTime = 1.0f / 60.0f;
1308 IniSavingRate = 5.0f;
1309 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).
1310 LogFilename = "imgui_log.txt";
1311#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1312 for (int i = 0; i < ImGuiKey_COUNT; i++)
1313 KeyMap[i] = -1;
1314#endif
1315 UserData = NULL;
1316
1317 Fonts = NULL;
1318 FontGlobalScale = 1.0f;
1319 FontDefault = NULL;
1320 FontAllowUserScaling = false;
1321 DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1322
1323 // Docking options (when ImGuiConfigFlags_DockingEnable is set)
1324 ConfigDockingNoSplit = false;
1325 ConfigDockingWithShift = false;
1326 ConfigDockingAlwaysTabBar = false;
1327 ConfigDockingTransparentPayload = false;
1328
1329 // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
1330 ConfigViewportsNoAutoMerge = false;
1331 ConfigViewportsNoTaskBarIcon = false;
1332 ConfigViewportsNoDecoration = true;
1333 ConfigViewportsNoDefaultParent = false;
1334
1335 // Miscellaneous options
1336 MouseDrawCursor = false;
1337#ifdef __APPLE__
1338 ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag
1339#else
1340 ConfigMacOSXBehaviors = false;
1341#endif
1342 ConfigInputTrickleEventQueue = true;
1343 ConfigInputTextCursorBlink = true;
1344 ConfigInputTextEnterKeepActive = false;
1345 ConfigDragClickToInputText = false;
1346 ConfigWindowsResizeFromEdges = true;
1347 ConfigWindowsMoveFromTitleBarOnly = false;
1348 ConfigMemoryCompactTimer = 60.0f;
1349 ConfigDebugBeginReturnValueOnce = false;
1350 ConfigDebugBeginReturnValueLoop = false;
1351
1352 // Inputs Behaviors
1353 MouseDoubleClickTime = 0.30f;
1354 MouseDoubleClickMaxDist = 6.0f;
1355 MouseDragThreshold = 6.0f;
1356 KeyRepeatDelay = 0.275f;
1357 KeyRepeatRate = 0.050f;
1358
1359 // Platform Functions
1360 // Note: Initialize() will setup default clipboard/ime handlers.
1361 BackendPlatformName = BackendRendererName = NULL;
1362 BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1363 PlatformLocaleDecimalPoint = '.';
1364
1365 // Input (NB: we already have memset zero the entire structure!)
1366 MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1367 MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1368 MouseSource = ImGuiMouseSource_Mouse;
1369 for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1370 for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1371 AppAcceptingEvents = true;
1372 BackendUsingLegacyKeyArrays = (ImS8)-1;
1373 BackendUsingLegacyNavInputArray = true; // assume using legacy array until proven wrong
1374}
1375
1376// Pass in translated ASCII characters for text input.
1377// - with glfw you can get those from the callback set in glfwSetCharCallback()
1378// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1379// FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1380void ImGuiIO::AddInputCharacter(unsigned int c)
1381{
1382 IM_ASSERT(Ctx != NULL);
1383 ImGuiContext& g = *Ctx;
1384 if (c == 0 || !AppAcceptingEvents)
1385 return;
1386
1387 ImGuiInputEvent e;
1388 e.Type = ImGuiInputEventType_Text;
1389 e.Source = ImGuiInputSource_Keyboard;
1390 e.EventId = g.InputEventsNextEventId++;
1391 e.Text.Char = c;
1392 g.InputEventsQueue.push_back(e);
1393}
1394
1395// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1396// we should save the high surrogate.
1397void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1398{
1399 if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1400 return;
1401
1402 if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1403 {
1404 if (InputQueueSurrogate != 0)
1405 AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1406 InputQueueSurrogate = c;
1407 return;
1408 }
1409
1410 ImWchar cp = c;
1411 if (InputQueueSurrogate != 0)
1412 {
1413 if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1414 {
1415 AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1416 }
1417 else
1418 {
1419#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1420 cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1421#else
1422 cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1423#endif
1424 }
1425
1426 InputQueueSurrogate = 0;
1427 }
1428 AddInputCharacter((unsigned)cp);
1429}
1430
1431void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1432{
1433 if (!AppAcceptingEvents)
1434 return;
1435 while (*utf8_chars != 0)
1436 {
1437 unsigned int c = 0;
1438 utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
1439 AddInputCharacter(c);
1440 }
1441}
1442
1443// Clear all incoming events.
1444void ImGuiIO::ClearEventsQueue()
1445{
1446 IM_ASSERT(Ctx != NULL);
1447 ImGuiContext& g = *Ctx;
1448 g.InputEventsQueue.clear();
1449}
1450
1451// Clear current keyboard/mouse/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons.
1452void ImGuiIO::ClearInputKeys()
1453{
1454#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1455 memset(KeysDown, 0, sizeof(KeysDown));
1456#endif
1457 for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)
1458 {
1459 KeysData[n].Down = false;
1460 KeysData[n].DownDuration = -1.0f;
1461 KeysData[n].DownDurationPrev = -1.0f;
1462 }
1463 KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1464 KeyMods = ImGuiMod_None;
1465 MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1466 for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++)
1467 {
1468 MouseDown[n] = false;
1469 MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1470 }
1471 MouseWheel = MouseWheelH = 0.0f;
1472 InputQueueCharacters.resize(0); // Behavior of old ClearInputCharacters().
1473}
1474
1475// Removed this as it is ambiguous/misleading and generally incorrect to use with the existence of a higher-level input queue.
1476// Current frame character buffer is now also cleared by ClearInputKeys().
1477#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1478void ImGuiIO::ClearInputCharacters()
1479{
1480 InputQueueCharacters.resize(0);
1481}
1482#endif
1483
1484static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1)
1485{
1486 ImGuiContext& g = *ctx;
1487 for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1488 {
1489 ImGuiInputEvent* e = &g.InputEventsQueue[n];
1490 if (e->Type != type)
1491 continue;
1492 if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1493 continue;
1494 if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1495 continue;
1496 return e;
1497 }
1498 return NULL;
1499}
1500
1501// Queue a new key down/up event.
1502// - ImGuiKey key: Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1503// - bool down: Is the key down? use false to signify a key release.
1504// - float analog_value: 0.0f..1.0f
1505// IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE.
1506// WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULLFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT.
1507void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1508{
1509 //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); }
1510 IM_ASSERT(Ctx != NULL);
1511 if (key == ImGuiKey_None || !AppAcceptingEvents)
1512 return;
1513 ImGuiContext& g = *Ctx;
1514 IM_ASSERT(ImGui::IsNamedKeyOrModKey(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API.
1515 IM_ASSERT(ImGui::IsAliasKey(key) == false); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1516 IM_ASSERT(key != ImGuiMod_Shortcut); // We could easily support the translation here but it seems saner to not accept it (TestEngine perform a translation itself)
1517
1518 // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data.
1519#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1520 IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1521 if (BackendUsingLegacyKeyArrays == -1)
1522 for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
1523 IM_ASSERT(KeyMap[n] == -1 && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1524 BackendUsingLegacyKeyArrays = 0;
1525#endif
1526 if (ImGui::IsGamepadKey(key))
1527 BackendUsingLegacyNavInputArray = false;
1528
1529 // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1530 const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key);
1531 const ImGuiKeyData* key_data = ImGui::GetKeyData(&g, key);
1532 const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1533 const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1534 if (latest_key_down == down && latest_key_analog == analog_value)
1535 return;
1536
1537 // Add event
1538 ImGuiInputEvent e;
1539 e.Type = ImGuiInputEventType_Key;
1540 e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1541 e.EventId = g.InputEventsNextEventId++;
1542 e.Key.Key = key;
1543 e.Key.Down = down;
1544 e.Key.AnalogValue = analog_value;
1545 g.InputEventsQueue.push_back(e);
1546}
1547
1548void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1549{
1550 if (!AppAcceptingEvents)
1551 return;
1552 AddKeyAnalogEvent(key, down, down ? 1.0f : 0.0f);
1553}
1554
1555// [Optional] Call after AddKeyEvent().
1556// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1557// 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.
1558void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1559{
1560 if (key == ImGuiKey_None)
1561 return;
1562 IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1563 IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1564 IM_UNUSED(native_keycode); // Yet unused
1565 IM_UNUSED(native_scancode); // Yet unused
1566
1567 // Build native->imgui map so old user code can still call key functions with native 0..511 values.
1568#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1569 const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode;
1570 if (!ImGui::IsLegacyKey((ImGuiKey)legacy_key))
1571 return;
1572 KeyMap[legacy_key] = key;
1573 KeyMap[key] = legacy_key;
1574#else
1575 IM_UNUSED(key);
1576 IM_UNUSED(native_legacy_index);
1577#endif
1578}
1579
1580// 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.
1581void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1582{
1583 AppAcceptingEvents = accepting_events;
1584}
1585
1586// Queue a mouse move event
1587void ImGuiIO::AddMousePosEvent(float x, float y)
1588{
1589 IM_ASSERT(Ctx != NULL);
1590 ImGuiContext& g = *Ctx;
1591 if (!AppAcceptingEvents)
1592 return;
1593
1594 // Apply same flooring as UpdateMouseInputs()
1595 ImVec2 pos((x > -FLT_MAX) ? ImFloor(x) : x, (y > -FLT_MAX) ? ImFloor(y) : y);
1596
1597 // Filter duplicate
1598 const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MousePos);
1599 const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1600 if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1601 return;
1602
1603 ImGuiInputEvent e;
1604 e.Type = ImGuiInputEventType_MousePos;
1605 e.Source = ImGuiInputSource_Mouse;
1606 e.EventId = g.InputEventsNextEventId++;
1607 e.MousePos.PosX = pos.x;
1608 e.MousePos.PosY = pos.y;
1609 e.MousePos.MouseSource = g.InputEventsNextMouseSource;
1610 g.InputEventsQueue.push_back(e);
1611}
1612
1613void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1614{
1615 IM_ASSERT(Ctx != NULL);
1616 ImGuiContext& g = *Ctx;
1617 IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1618 if (!AppAcceptingEvents)
1619 return;
1620
1621 // Filter duplicate
1622 const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseButton, (int)mouse_button);
1623 const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1624 if (latest_button_down == down)
1625 return;
1626
1627 ImGuiInputEvent e;
1628 e.Type = ImGuiInputEventType_MouseButton;
1629 e.Source = ImGuiInputSource_Mouse;
1630 e.EventId = g.InputEventsNextEventId++;
1631 e.MouseButton.Button = mouse_button;
1632 e.MouseButton.Down = down;
1633 e.MouseButton.MouseSource = g.InputEventsNextMouseSource;
1634 g.InputEventsQueue.push_back(e);
1635}
1636
1637// Queue a mouse wheel event (some mouse/API may only have a Y component)
1638void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
1639{
1640 IM_ASSERT(Ctx != NULL);
1641 ImGuiContext& g = *Ctx;
1642
1643 // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
1644 if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
1645 return;
1646
1647 ImGuiInputEvent e;
1648 e.Type = ImGuiInputEventType_MouseWheel;
1649 e.Source = ImGuiInputSource_Mouse;
1650 e.EventId = g.InputEventsNextEventId++;
1651 e.MouseWheel.WheelX = wheel_x;
1652 e.MouseWheel.WheelY = wheel_y;
1653 e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1654 g.InputEventsQueue.push_back(e);
1655}
1656
1657// This is not a real event, the data is latched in order to be stored in actual Mouse events.
1658// This is so that duplicate events (e.g. Windows sending extraneous WM_MOUSEMOVE) gets filtered and are not leading to actual source changes.
1659void ImGuiIO::AddMouseSourceEvent(ImGuiMouseSource source)
1660{
1661 IM_ASSERT(Ctx != NULL);
1662 ImGuiContext& g = *Ctx;
1663 g.InputEventsNextMouseSource = source;
1664}
1665
1666void ImGuiIO::AddMouseViewportEvent(ImGuiID viewport_id)
1667{
1668 IM_ASSERT(Ctx != NULL);
1669 ImGuiContext& g = *Ctx;
1670 //IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport);
1671 if (!AppAcceptingEvents)
1672 return;
1673
1674 // Filter duplicate
1675 const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseViewport);
1676 const ImGuiID latest_viewport_id = latest_event ? latest_event->MouseViewport.HoveredViewportID : g.IO.MouseHoveredViewport;
1677 if (latest_viewport_id == viewport_id)
1678 return;
1679
1680 ImGuiInputEvent e;
1681 e.Type = ImGuiInputEventType_MouseViewport;
1682 e.Source = ImGuiInputSource_Mouse;
1683 e.MouseViewport.HoveredViewportID = viewport_id;
1684 g.InputEventsQueue.push_back(e);
1685}
1686
1687void ImGuiIO::AddFocusEvent(bool focused)
1688{
1689 IM_ASSERT(Ctx != NULL);
1690 ImGuiContext& g = *Ctx;
1691
1692 // Filter duplicate
1693 const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Focus);
1694 const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
1695 if (latest_focused == focused || (ConfigDebugIgnoreFocusLoss && !focused))
1696 return;
1697
1698 ImGuiInputEvent e;
1699 e.Type = ImGuiInputEventType_Focus;
1700 e.EventId = g.InputEventsNextEventId++;
1701 e.AppFocused.Focused = focused;
1702 g.InputEventsQueue.push_back(e);
1703}
1704
1705//-----------------------------------------------------------------------------
1706// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
1707//-----------------------------------------------------------------------------
1708
1709ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
1710{
1711 IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
1712 ImVec2 p_last = p1;
1713 ImVec2 p_closest;
1714 float p_closest_dist2 = FLT_MAX;
1715 float t_step = 1.0f / (float)num_segments;
1716 for (int i_step = 1; i_step <= num_segments; i_step++)
1717 {
1718 ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
1719 ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1720 float dist2 = ImLengthSqr(p - p_line);
1721 if (dist2 < p_closest_dist2)
1722 {
1723 p_closest = p_line;
1724 p_closest_dist2 = dist2;
1725 }
1726 p_last = p_current;
1727 }
1728 return p_closest;
1729}
1730
1731// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
1732static 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)
1733{
1734 float dx = x4 - x1;
1735 float dy = y4 - y1;
1736 float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
1737 float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
1738 d2 = (d2 >= 0) ? d2 : -d2;
1739 d3 = (d3 >= 0) ? d3 : -d3;
1740 if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
1741 {
1742 ImVec2 p_current(x4, y4);
1743 ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1744 float dist2 = ImLengthSqr(p - p_line);
1745 if (dist2 < p_closest_dist2)
1746 {
1747 p_closest = p_line;
1748 p_closest_dist2 = dist2;
1749 }
1750 p_last = p_current;
1751 }
1752 else if (level < 10)
1753 {
1754 float x12 = (x1 + x2)*0.5f, y12 = (y1 + y2)*0.5f;
1755 float x23 = (x2 + x3)*0.5f, y23 = (y2 + y3)*0.5f;
1756 float x34 = (x3 + x4)*0.5f, y34 = (y3 + y4)*0.5f;
1757 float x123 = (x12 + x23)*0.5f, y123 = (y12 + y23)*0.5f;
1758 float x234 = (x23 + x34)*0.5f, y234 = (y23 + y34)*0.5f;
1759 float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
1760 ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
1761 ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
1762 }
1763}
1764
1765// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
1766// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
1767ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
1768{
1769 IM_ASSERT(tess_tol > 0.0f);
1770 ImVec2 p_last = p1;
1771 ImVec2 p_closest;
1772 float p_closest_dist2 = FLT_MAX;
1773 ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
1774 return p_closest;
1775}
1776
1777ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
1778{
1779 ImVec2 ap = p - a;
1780 ImVec2 ab_dir = b - a;
1781 float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
1782 if (dot < 0.0f)
1783 return a;
1784 float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
1785 if (dot > ab_len_sqr)
1786 return b;
1787 return a + ab_dir * dot / ab_len_sqr;
1788}
1789
1790bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1791{
1792 bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
1793 bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
1794 bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
1795 return ((b1 == b2) && (b2 == b3));
1796}
1797
1798void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
1799{
1800 ImVec2 v0 = b - a;
1801 ImVec2 v1 = c - a;
1802 ImVec2 v2 = p - a;
1803 const float denom = v0.x * v1.y - v1.x * v0.y;
1804 out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
1805 out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
1806 out_u = 1.0f - out_v - out_w;
1807}
1808
1809ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1810{
1811 ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
1812 ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
1813 ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
1814 float dist2_ab = ImLengthSqr(p - proj_ab);
1815 float dist2_bc = ImLengthSqr(p - proj_bc);
1816 float dist2_ca = ImLengthSqr(p - proj_ca);
1817 float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
1818 if (m == dist2_ab)
1819 return proj_ab;
1820 if (m == dist2_bc)
1821 return proj_bc;
1822 return proj_ca;
1823}
1824
1825//-----------------------------------------------------------------------------
1826// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
1827//-----------------------------------------------------------------------------
1828
1829// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
1830int ImStricmp(const char* str1, const char* str2)
1831{
1832 int d;
1833 while ((d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; }
1834 return d;
1835}
1836
1837int ImStrnicmp(const char* str1, const char* str2, size_t count)
1838{
1839 int d = 0;
1840 while (count > 0 && (d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
1841 return d;
1842}
1843
1844void ImStrncpy(char* dst, const char* src, size_t count)
1845{
1846 if (count < 1)
1847 return;
1848 if (count > 1)
1849 strncpy(dst, src, count - 1);
1850 dst[count - 1] = 0;
1851}
1852
1853char* ImStrdup(const char* str)
1854{
1855 size_t len = strlen(str);
1856 void* buf = IM_ALLOC(len + 1);
1857 return (char*)memcpy(buf, (const void*)str, len + 1);
1858}
1859
1860char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
1861{
1862 size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
1863 size_t src_size = strlen(src) + 1;
1864 if (dst_buf_size < src_size)
1865 {
1866 IM_FREE(dst);
1867 dst = (char*)IM_ALLOC(src_size);
1868 if (p_dst_size)
1869 *p_dst_size = src_size;
1870 }
1871 return (char*)memcpy(dst, (const void*)src, src_size);
1872}
1873
1874const char* ImStrchrRange(const char* str, const char* str_end, char c)
1875{
1876 const char* p = (const char*)memchr(str, (int)c, str_end - str);
1877 return p;
1878}
1879
1880int ImStrlenW(const ImWchar* str)
1881{
1882 //return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bit
1883 int n = 0;
1884 while (*str++) n++;
1885 return n;
1886}
1887
1888// Find end-of-line. Return pointer will point to either first \n, either str_end.
1889const char* ImStreolRange(const char* str, const char* str_end)
1890{
1891 const char* p = (const char*)memchr(str, '\n', str_end - str);
1892 return p ? p : str_end;
1893}
1894
1895const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
1896{
1897 while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
1898 buf_mid_line--;
1899 return buf_mid_line;
1900}
1901
1902const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
1903{
1904 if (!needle_end)
1905 needle_end = needle + strlen(needle);
1906
1907 const char un0 = (char)ImToUpper(*needle);
1908 while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
1909 {
1910 if (ImToUpper(*haystack) == un0)
1911 {
1912 const char* b = needle + 1;
1913 for (const char* a = haystack + 1; b < needle_end; a++, b++)
1914 if (ImToUpper(*a) != ImToUpper(*b))
1915 break;
1916 if (b == needle_end)
1917 return haystack;
1918 }
1919 haystack++;
1920 }
1921 return NULL;
1922}
1923
1924// 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.
1925void ImStrTrimBlanks(char* buf)
1926{
1927 char* p = buf;
1928 while (p[0] == ' ' || p[0] == '\t') // Leading blanks
1929 p++;
1930 char* p_start = p;
1931 while (*p != 0) // Find end of string
1932 p++;
1933 while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks
1934 p--;
1935 if (p_start != buf) // Copy memory if we had leading blanks
1936 memmove(buf, p_start, p - p_start);
1937 buf[p - p_start] = 0; // Zero terminate
1938}
1939
1940const char* ImStrSkipBlank(const char* str)
1941{
1942 while (str[0] == ' ' || str[0] == '\t')
1943 str++;
1944 return str;
1945}
1946
1947// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
1948// 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.
1949// B) When buf==NULL vsnprintf() will return the output size.
1950#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1951
1952// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
1953// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1954// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
1955// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
1956#ifdef IMGUI_USE_STB_SPRINTF
1957#ifndef IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION
1958#define STB_SPRINTF_IMPLEMENTATION
1959#endif
1960#ifdef IMGUI_STB_SPRINTF_FILENAME
1961#include IMGUI_STB_SPRINTF_FILENAME
1962#else
1963#include "stb_sprintf.h"
1964#endif
1965#endif // #ifdef IMGUI_USE_STB_SPRINTF
1966
1967#if defined(_MSC_VER) && !defined(vsnprintf)
1968#define vsnprintf _vsnprintf
1969#endif
1970
1971int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
1972{
1973 va_list args;
1974 va_start(args, fmt);
1975#ifdef IMGUI_USE_STB_SPRINTF
1976 int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1977#else
1978 int w = vsnprintf(buf, buf_size, fmt, args);
1979#endif
1980 va_end(args);
1981 if (buf == NULL)
1982 return w;
1983 if (w == -1 || w >= (int)buf_size)
1984 w = (int)buf_size - 1;
1985 buf[w] = 0;
1986 return w;
1987}
1988
1989int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
1990{
1991#ifdef IMGUI_USE_STB_SPRINTF
1992 int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1993#else
1994 int w = vsnprintf(buf, buf_size, fmt, args);
1995#endif
1996 if (buf == NULL)
1997 return w;
1998 if (w == -1 || w >= (int)buf_size)
1999 w = (int)buf_size - 1;
2000 buf[w] = 0;
2001 return w;
2002}
2003#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2004
2005void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
2006{
2007 va_list args;
2008 va_start(args, fmt);
2009 ImFormatStringToTempBufferV(out_buf, out_buf_end, fmt, args);
2010 va_end(args);
2011}
2012
2013void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
2014{
2015 ImGuiContext& g = *GImGui;
2016 if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
2017 {
2018 const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
2019 if (buf == NULL)
2020 buf = "(null)";
2021 *out_buf = buf;
2022 if (out_buf_end) { *out_buf_end = buf + strlen(buf); }
2023 }
2024 else if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '*' && fmt[3] == 's' && fmt[4] == 0)
2025 {
2026 int buf_len = va_arg(args, int); // Skip formatting when using "%.*s"
2027 const char* buf = va_arg(args, const char*);
2028 if (buf == NULL)
2029 {
2030 buf = "(null)";
2031 buf_len = ImMin(buf_len, 6);
2032 }
2033 *out_buf = buf;
2034 *out_buf_end = buf + buf_len; // Disallow not passing 'out_buf_end' here. User is expected to use it.
2035 }
2036 else
2037 {
2038 int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
2039 *out_buf = g.TempBuffer.Data;
2040 if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
2041 }
2042}
2043
2044// CRC32 needs a 1KB lookup table (not cache friendly)
2045// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
2046// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
2047static const ImU32 GCrc32LookupTable[256] =
2048{
2049 0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
2050 0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
2051 0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
2052 0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
2053 0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
2054 0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
2055 0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
2056 0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
2057 0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
2058 0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
2059 0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
2060 0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
2061 0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
2062 0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
2063 0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
2064 0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
2065};
2066
2067// Known size hash
2068// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
2069// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2070ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
2071{
2072 ImU32 crc = ~seed;
2073 const unsigned char* data = (const unsigned char*)data_p;
2074 const ImU32* crc32_lut = GCrc32LookupTable;
2075 while (data_size-- != 0)
2076 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
2077 return ~crc;
2078}
2079
2080// Zero-terminated string hash, with support for ### to reset back to seed value
2081// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
2082// Because this syntax is rarely used we are optimizing for the common case.
2083// - If we reach ### in the string we discard the hash so far and reset to the seed.
2084// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
2085// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2086ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
2087{
2088 seed = ~seed;
2089 ImU32 crc = seed;
2090 const unsigned char* data = (const unsigned char*)data_p;
2091 const ImU32* crc32_lut = GCrc32LookupTable;
2092 if (data_size != 0)
2093 {
2094 while (data_size-- != 0)
2095 {
2096 unsigned char c = *data++;
2097 if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
2098 crc = seed;
2099 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2100 }
2101 }
2102 else
2103 {
2104 while (unsigned char c = *data++)
2105 {
2106 if (c == '#' && data[0] == '#' && data[1] == '#')
2107 crc = seed;
2108 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2109 }
2110 }
2111 return ~crc;
2112}
2113
2114//-----------------------------------------------------------------------------
2115// [SECTION] MISC HELPERS/UTILITIES (File functions)
2116//-----------------------------------------------------------------------------
2117
2118// Default file functions
2119#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2120
2121ImFileHandle ImFileOpen(const char* filename, const char* mode)
2122{
2123#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
2124 // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
2125 // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
2126 const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
2127 const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
2128
2129 // Use stack buffer if possible, otherwise heap buffer. Sizes include zero terminator.
2130 // We don't rely on current ImGuiContext as this is implied to be a helper function which doesn't depend on it (see #7314).
2131 wchar_t local_temp_stack[FILENAME_MAX];
2132 ImVector<wchar_t> local_temp_heap;
2133 if (filename_wsize + mode_wsize > IM_ARRAYSIZE(local_temp_stack))
2134 local_temp_heap.resize(filename_wsize + mode_wsize);
2135 wchar_t* filename_wbuf = local_temp_heap.Data ? local_temp_heap.Data : local_temp_stack;
2136 wchar_t* mode_wbuf = filename_wbuf + filename_wsize;
2137 ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, filename_wbuf, filename_wsize);
2138 ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, mode_wbuf, mode_wsize);
2139 return ::_wfopen(filename_wbuf, mode_wbuf);
2140#else
2141 return fopen(filename, mode);
2142#endif
2143}
2144
2145// 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.
2146bool ImFileClose(ImFileHandle f) { return fclose(f) == 0; }
2147ImU64 ImFileGetSize(ImFileHandle f) { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
2148ImU64 ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fread(data, (size_t)sz, (size_t)count, f); }
2149ImU64 ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fwrite(data, (size_t)sz, (size_t)count, f); }
2150#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2151
2152// Helper: Load file content into memory
2153// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
2154// This can't really be used with "rt" because fseek size won't match read size.
2155void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
2156{
2157 IM_ASSERT(filename && mode);
2158 if (out_file_size)
2159 *out_file_size = 0;
2160
2161 ImFileHandle f;
2162 if ((f = ImFileOpen(filename, mode)) == NULL)
2163 return NULL;
2164
2165 size_t file_size = (size_t)ImFileGetSize(f);
2166 if (file_size == (size_t)-1)
2167 {
2168 ImFileClose(f);
2169 return NULL;
2170 }
2171
2172 void* file_data = IM_ALLOC(file_size + padding_bytes);
2173 if (file_data == NULL)
2174 {
2175 ImFileClose(f);
2176 return NULL;
2177 }
2178 if (ImFileRead(file_data, 1, file_size, f) != file_size)
2179 {
2180 ImFileClose(f);
2181 IM_FREE(file_data);
2182 return NULL;
2183 }
2184 if (padding_bytes > 0)
2185 memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
2186
2187 ImFileClose(f);
2188 if (out_file_size)
2189 *out_file_size = file_size;
2190
2191 return file_data;
2192}
2193
2194//-----------------------------------------------------------------------------
2195// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2196//-----------------------------------------------------------------------------
2197
2198IM_MSVC_RUNTIME_CHECKS_OFF
2199
2200// Convert UTF-8 to 32-bit character, process single character input.
2201// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2202// We handle UTF-8 decoding error by skipping forward.
2203int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2204{
2205 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 };
2206 static const int masks[] = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2207 static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2208 static const int shiftc[] = { 0, 18, 12, 6, 0 };
2209 static const int shifte[] = { 0, 6, 4, 2, 0 };
2210 int len = lengths[*(const unsigned char*)in_text >> 3];
2211 int wanted = len + (len ? 0 : 1);
2212
2213 if (in_text_end == NULL)
2214 in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2215
2216 // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2217 // so it is fast even with excessive branching.
2218 unsigned char s[4];
2219 s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2220 s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2221 s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2222 s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2223
2224 // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2225 *out_char = (uint32_t)(s[0] & masks[len]) << 18;
2226 *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2227 *out_char |= (uint32_t)(s[2] & 0x3f) << 6;
2228 *out_char |= (uint32_t)(s[3] & 0x3f) << 0;
2229 *out_char >>= shiftc[len];
2230
2231 // Accumulate the various error conditions.
2232 int e = 0;
2233 e = (*out_char < mins[len]) << 6; // non-canonical encoding
2234 e |= ((*out_char >> 11) == 0x1b) << 7; // surrogate half?
2235 e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8; // out of range?
2236 e |= (s[1] & 0xc0) >> 2;
2237 e |= (s[2] & 0xc0) >> 4;
2238 e |= (s[3] ) >> 6;
2239 e ^= 0x2a; // top two bits of each tail byte correct?
2240 e >>= shifte[len];
2241
2242 if (e)
2243 {
2244 // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2245 // One byte is consumed in case of invalid first byte of in_text.
2246 // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2247 // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2248 wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2249 *out_char = IM_UNICODE_CODEPOINT_INVALID;
2250 }
2251
2252 return wanted;
2253}
2254
2255int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2256{
2257 ImWchar* buf_out = buf;
2258 ImWchar* buf_end = buf + buf_size;
2259 while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2260 {
2261 unsigned int c;
2262 in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2263 *buf_out++ = (ImWchar)c;
2264 }
2265 *buf_out = 0;
2266 if (in_text_remaining)
2267 *in_text_remaining = in_text;
2268 return (int)(buf_out - buf);
2269}
2270
2271int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2272{
2273 int char_count = 0;
2274 while ((!in_text_end || in_text < in_text_end) && *in_text)
2275 {
2276 unsigned int c;
2277 in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2278 char_count++;
2279 }
2280 return char_count;
2281}
2282
2283// Based on stb_to_utf8() from github.com/nothings/stb/
2284static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2285{
2286 if (c < 0x80)
2287 {
2288 buf[0] = (char)c;
2289 return 1;
2290 }
2291 if (c < 0x800)
2292 {
2293 if (buf_size < 2) return 0;
2294 buf[0] = (char)(0xc0 + (c >> 6));
2295 buf[1] = (char)(0x80 + (c & 0x3f));
2296 return 2;
2297 }
2298 if (c < 0x10000)
2299 {
2300 if (buf_size < 3) return 0;
2301 buf[0] = (char)(0xe0 + (c >> 12));
2302 buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2303 buf[2] = (char)(0x80 + ((c ) & 0x3f));
2304 return 3;
2305 }
2306 if (c <= 0x10FFFF)
2307 {
2308 if (buf_size < 4) return 0;
2309 buf[0] = (char)(0xf0 + (c >> 18));
2310 buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2311 buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2312 buf[3] = (char)(0x80 + ((c ) & 0x3f));
2313 return 4;
2314 }
2315 // Invalid code point, the max unicode is 0x10FFFF
2316 return 0;
2317}
2318
2319const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
2320{
2321 int count = ImTextCharToUtf8_inline(out_buf, 5, c);
2322 out_buf[count] = 0;
2323 return out_buf;
2324}
2325
2326// Not optimal but we very rarely use this function.
2327int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2328{
2329 unsigned int unused = 0;
2330 return ImTextCharFromUtf8(&unused, in_text, in_text_end);
2331}
2332
2333static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2334{
2335 if (c < 0x80) return 1;
2336 if (c < 0x800) return 2;
2337 if (c < 0x10000) return 3;
2338 if (c <= 0x10FFFF) return 4;
2339 return 3;
2340}
2341
2342int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2343{
2344 char* buf_p = out_buf;
2345 const char* buf_end = out_buf + out_buf_size;
2346 while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2347 {
2348 unsigned int c = (unsigned int)(*in_text++);
2349 if (c < 0x80)
2350 *buf_p++ = (char)c;
2351 else
2352 buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);
2353 }
2354 *buf_p = 0;
2355 return (int)(buf_p - out_buf);
2356}
2357
2358int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2359{
2360 int bytes_count = 0;
2361 while ((!in_text_end || in_text < in_text_end) && *in_text)
2362 {
2363 unsigned int c = (unsigned int)(*in_text++);
2364 if (c < 0x80)
2365 bytes_count++;
2366 else
2367 bytes_count += ImTextCountUtf8BytesFromChar(c);
2368 }
2369 return bytes_count;
2370}
2371
2372const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_text_curr)
2373{
2374 while (in_text_curr > in_text_start)
2375 {
2376 in_text_curr--;
2377 if ((*in_text_curr & 0xC0) != 0x80)
2378 return in_text_curr;
2379 }
2380 return in_text_start;
2381}
2382
2383IM_MSVC_RUNTIME_CHECKS_RESTORE
2384
2385//-----------------------------------------------------------------------------
2386// [SECTION] MISC HELPERS/UTILITIES (Color functions)
2387// Note: The Convert functions are early design which are not consistent with other API.
2388//-----------------------------------------------------------------------------
2389
2390IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2391{
2392 float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2393 int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2394 int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2395 int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2396 return IM_COL32(r, g, b, 0xFF);
2397}
2398
2399ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2400{
2401 float s = 1.0f / 255.0f;
2402 return ImVec4(
2403 ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2404 ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2405 ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2406 ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2407}
2408
2409ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2410{
2411 ImU32 out;
2412 out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2413 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2414 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2415 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2416 return out;
2417}
2418
2419// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2420// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2421void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2422{
2423 float K = 0.f;
2424 if (g < b)
2425 {
2426 ImSwap(g, b);
2427 K = -1.f;
2428 }
2429 if (r < g)
2430 {
2431 ImSwap(r, g);
2432 K = -2.f / 6.f - K;
2433 }
2434
2435 const float chroma = r - (g < b ? g : b);
2436 out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2437 out_s = chroma / (r + 1e-20f);
2438 out_v = r;
2439}
2440
2441// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2442// also http://en.wikipedia.org/wiki/HSL_and_HSV
2443void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2444{
2445 if (s == 0.0f)
2446 {
2447 // gray
2448 out_r = out_g = out_b = v;
2449 return;
2450 }
2451
2452 h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2453 int i = (int)h;
2454 float f = h - (float)i;
2455 float p = v * (1.0f - s);
2456 float q = v * (1.0f - s * f);
2457 float t = v * (1.0f - s * (1.0f - f));
2458
2459 switch (i)
2460 {
2461 case 0: out_r = v; out_g = t; out_b = p; break;
2462 case 1: out_r = q; out_g = v; out_b = p; break;
2463 case 2: out_r = p; out_g = v; out_b = t; break;
2464 case 3: out_r = p; out_g = q; out_b = v; break;
2465 case 4: out_r = t; out_g = p; out_b = v; break;
2466 case 5: default: out_r = v; out_g = p; out_b = q; break;
2467 }
2468}
2469
2470//-----------------------------------------------------------------------------
2471// [SECTION] ImGuiStorage
2472// Helper: Key->value storage
2473//-----------------------------------------------------------------------------
2474
2475// std::lower_bound but without the bullshit
2476static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)
2477{
2478 ImGuiStorage::ImGuiStoragePair* first = data.Data;
2479 ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;
2480 size_t count = (size_t)(last - first);
2481 while (count > 0)
2482 {
2483 size_t count2 = count >> 1;
2484 ImGuiStorage::ImGuiStoragePair* mid = first + count2;
2485 if (mid->key < key)
2486 {
2487 first = ++mid;
2488 count -= count2 + 1;
2489 }
2490 else
2491 {
2492 count = count2;
2493 }
2494 }
2495 return first;
2496}
2497
2498// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2499void ImGuiStorage::BuildSortByKey()
2500{
2501 struct StaticFunc
2502 {
2503 static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2504 {
2505 // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2506 if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;
2507 if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;
2508 return 0;
2509 }
2510 };
2511 ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairComparerByID);
2512}
2513
2514int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2515{
2516 ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2517 if (it == Data.end() || it->key != key)
2518 return default_val;
2519 return it->val_i;
2520}
2521
2522bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2523{
2524 return GetInt(key, default_val ? 1 : 0) != 0;
2525}
2526
2527float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2528{
2529 ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2530 if (it == Data.end() || it->key != key)
2531 return default_val;
2532 return it->val_f;
2533}
2534
2535void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
2536{
2537 ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2538 if (it == Data.end() || it->key != key)
2539 return NULL;
2540 return it->val_p;
2541}
2542
2543// 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.
2544int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
2545{
2546 ImGuiStoragePair* it = LowerBound(Data, key);
2547 if (it == Data.end() || it->key != key)
2548 it = Data.insert(it, ImGuiStoragePair(key, default_val));
2549 return &it->val_i;
2550}
2551
2552bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
2553{
2554 return (bool*)GetIntRef(key, default_val ? 1 : 0);
2555}
2556
2557float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
2558{
2559 ImGuiStoragePair* it = LowerBound(Data, key);
2560 if (it == Data.end() || it->key != key)
2561 it = Data.insert(it, ImGuiStoragePair(key, default_val));
2562 return &it->val_f;
2563}
2564
2565void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2566{
2567 ImGuiStoragePair* it = LowerBound(Data, key);
2568 if (it == Data.end() || it->key != key)
2569 it = Data.insert(it, ImGuiStoragePair(key, default_val));
2570 return &it->val_p;
2571}
2572
2573// 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)
2574void ImGuiStorage::SetInt(ImGuiID key, int val)
2575{
2576 ImGuiStoragePair* it = LowerBound(Data, key);
2577 if (it == Data.end() || it->key != key)
2578 Data.insert(it, ImGuiStoragePair(key, val));
2579 else
2580 it->val_i = val;
2581}
2582
2583void ImGuiStorage::SetBool(ImGuiID key, bool val)
2584{
2585 SetInt(key, val ? 1 : 0);
2586}
2587
2588void ImGuiStorage::SetFloat(ImGuiID key, float val)
2589{
2590 ImGuiStoragePair* it = LowerBound(Data, key);
2591 if (it == Data.end() || it->key != key)
2592 Data.insert(it, ImGuiStoragePair(key, val));
2593 else
2594 it->val_f = val;
2595}
2596
2597void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2598{
2599 ImGuiStoragePair* it = LowerBound(Data, key);
2600 if (it == Data.end() || it->key != key)
2601 Data.insert(it, ImGuiStoragePair(key, val));
2602 else
2603 it->val_p = val;
2604}
2605
2606void ImGuiStorage::SetAllInt(int v)
2607{
2608 for (int i = 0; i < Data.Size; i++)
2609 Data[i].val_i = v;
2610}
2611
2612//-----------------------------------------------------------------------------
2613// [SECTION] ImGuiTextFilter
2614//-----------------------------------------------------------------------------
2615
2616// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2617ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
2618{
2619 InputBuf[0] = 0;
2620 CountGrep = 0;
2621 if (default_filter)
2622 {
2623 ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
2624 Build();
2625 }
2626}
2627
2628bool ImGuiTextFilter::Draw(const char* label, float width)
2629{
2630 if (width != 0.0f)
2631 ImGui::SetNextItemWidth(width);
2632 bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
2633 if (value_changed)
2634 Build();
2635 return value_changed;
2636}
2637
2638void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
2639{
2640 out->resize(0);
2641 const char* wb = b;
2642 const char* we = wb;
2643 while (we < e)
2644 {
2645 if (*we == separator)
2646 {
2647 out->push_back(ImGuiTextRange(wb, we));
2648 wb = we + 1;
2649 }
2650 we++;
2651 }
2652 if (wb != we)
2653 out->push_back(ImGuiTextRange(wb, we));
2654}
2655
2656void ImGuiTextFilter::Build()
2657{
2658 Filters.resize(0);
2659 ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
2660 input_range.split(',', &Filters);
2661
2662 CountGrep = 0;
2663 for (ImGuiTextRange& f : Filters)
2664 {
2665 while (f.b < f.e && ImCharIsBlankA(f.b[0]))
2666 f.b++;
2667 while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
2668 f.e--;
2669 if (f.empty())
2670 continue;
2671 if (f.b[0] != '-')
2672 CountGrep += 1;
2673 }
2674}
2675
2676bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
2677{
2678 if (Filters.empty())
2679 return true;
2680
2681 if (text == NULL)
2682 text = "";
2683
2684 for (const ImGuiTextRange& f : Filters)
2685 {
2686 if (f.empty())
2687 continue;
2688 if (f.b[0] == '-')
2689 {
2690 // Subtract
2691 if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
2692 return false;
2693 }
2694 else
2695 {
2696 // Grep
2697 if (ImStristr(text, text_end, f.b, f.e) != NULL)
2698 return true;
2699 }
2700 }
2701
2702 // Implicit * grep
2703 if (CountGrep == 0)
2704 return true;
2705
2706 return false;
2707}
2708
2709//-----------------------------------------------------------------------------
2710// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
2711//-----------------------------------------------------------------------------
2712
2713// On some platform vsnprintf() takes va_list by reference and modifies it.
2714// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
2715#ifndef va_copy
2716#if defined(__GNUC__) || defined(__clang__)
2717#define va_copy(dest, src) __builtin_va_copy(dest, src)
2718#else
2719#define va_copy(dest, src) (dest = src)
2720#endif
2721#endif
2722
2723char ImGuiTextBuffer::EmptyString[1] = { 0 };
2724
2725void ImGuiTextBuffer::append(const char* str, const char* str_end)
2726{
2727 int len = str_end ? (int)(str_end - str) : (int)strlen(str);
2728
2729 // Add zero-terminator the first time
2730 const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2731 const int needed_sz = write_off + len;
2732 if (write_off + len >= Buf.Capacity)
2733 {
2734 int new_capacity = Buf.Capacity * 2;
2735 Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2736 }
2737
2738 Buf.resize(needed_sz);
2739 memcpy(&Buf[write_off - 1], str, (size_t)len);
2740 Buf[write_off - 1 + len] = 0;
2741}
2742
2743void ImGuiTextBuffer::appendf(const char* fmt, ...)
2744{
2745 va_list args;
2746 va_start(args, fmt);
2747 appendfv(fmt, args);
2748 va_end(args);
2749}
2750
2751// Helper: Text buffer for logging/accumulating text
2752void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
2753{
2754 va_list args_copy;
2755 va_copy(args_copy, args);
2756
2757 int len = ImFormatStringV(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
2758 if (len <= 0)
2759 {
2760 va_end(args_copy);
2761 return;
2762 }
2763
2764 // Add zero-terminator the first time
2765 const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2766 const int needed_sz = write_off + len;
2767 if (write_off + len >= Buf.Capacity)
2768 {
2769 int new_capacity = Buf.Capacity * 2;
2770 Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2771 }
2772
2773 Buf.resize(needed_sz);
2774 ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
2775 va_end(args_copy);
2776}
2777
2778void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
2779{
2780 IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
2781 if (old_size == new_size)
2782 return;
2783 if (EndOffset == 0 || base[EndOffset - 1] == '\n')
2784 LineOffsets.push_back(EndOffset);
2785 const char* base_end = base + new_size;
2786 for (const char* p = base + old_size; (p = (const char*)memchr(p, '\n', base_end - p)) != 0; )
2787 if (++p < base_end) // Don't push a trailing offset on last \n
2788 LineOffsets.push_back((int)(intptr_t)(p - base));
2789 EndOffset = ImMax(EndOffset, new_size);
2790}
2791
2792//-----------------------------------------------------------------------------
2793// [SECTION] ImGuiListClipper
2794//-----------------------------------------------------------------------------
2795
2796// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
2797// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
2798static bool GetSkipItemForListClipping()
2799{
2800 ImGuiContext& g = *GImGui;
2801 return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
2802}
2803
2804static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
2805{
2806 if (ranges.Size - offset <= 1)
2807 return;
2808
2809 // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
2810 for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
2811 for (int i = offset; i < sort_end + offset; ++i)
2812 if (ranges[i].Min > ranges[i + 1].Min)
2813 ImSwap(ranges[i], ranges[i + 1]);
2814
2815 // Now fuse ranges together as much as possible.
2816 for (int i = 1 + offset; i < ranges.Size; i++)
2817 {
2818 IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
2819 if (ranges[i - 1].Max < ranges[i].Min)
2820 continue;
2821 ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min);
2822 ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max);
2823 ranges.erase(ranges.Data + i);
2824 i--;
2825 }
2826}
2827
2828static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
2829{
2830 // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
2831 // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
2832 // 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?
2833 ImGuiContext& g = *GImGui;
2834 ImGuiWindow* window = g.CurrentWindow;
2835 float off_y = pos_y - window->DC.CursorPos.y;
2836 window->DC.CursorPos.y = pos_y;
2837 window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y);
2838 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.
2839 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.
2840 if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
2841 columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
2842 if (ImGuiTable* table = g.CurrentTable)
2843 {
2844 if (table->IsInsideRow)
2845 ImGui::TableEndRow(table);
2846 table->RowPosY2 = window->DC.CursorPos.y;
2847 const int row_increase = (int)((off_y / line_height) + 0.5f);
2848 //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
2849 table->RowBgColorCounter += row_increase;
2850 }
2851}
2852
2853static void ImGuiListClipper_SeekCursorForItem(ImGuiListClipper* clipper, int item_n)
2854{
2855 // StartPosY starts from ItemsFrozen hence the subtraction
2856 // Perform the add and multiply with double to allow seeking through larger ranges
2857 ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2858 float pos_y = (float)((double)clipper->StartPosY + data->LossynessOffset + (double)(item_n - data->ItemsFrozen) * clipper->ItemsHeight);
2859 ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, clipper->ItemsHeight);
2860}
2861
2862ImGuiListClipper::ImGuiListClipper()
2863{
2864 memset(this, 0, sizeof(*this));
2865}
2866
2867ImGuiListClipper::~ImGuiListClipper()
2868{
2869 End();
2870}
2871
2872void ImGuiListClipper::Begin(int items_count, float items_height)
2873{
2874 if (Ctx == NULL)
2875 Ctx = ImGui::GetCurrentContext();
2876
2877 ImGuiContext& g = *Ctx;
2878 ImGuiWindow* window = g.CurrentWindow;
2879 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
2880
2881 if (ImGuiTable* table = g.CurrentTable)
2882 if (table->IsInsideRow)
2883 ImGui::TableEndRow(table);
2884
2885 StartPosY = window->DC.CursorPos.y;
2886 ItemsHeight = items_height;
2887 ItemsCount = items_count;
2888 DisplayStart = -1;
2889 DisplayEnd = 0;
2890
2891 // Acquire temporary buffer
2892 if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
2893 g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData());
2894 ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2895 data->Reset(this);
2896 data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
2897 TempData = data;
2898}
2899
2900void ImGuiListClipper::End()
2901{
2902 if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
2903 {
2904 // 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.
2905 ImGuiContext& g = *Ctx;
2906 IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
2907 if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
2908 ImGuiListClipper_SeekCursorForItem(this, ItemsCount);
2909
2910 // Restore temporary buffer and fix back pointers which may be invalidated when nesting
2911 IM_ASSERT(data->ListClipper == this);
2912 data->StepNo = data->Ranges.Size;
2913 if (--g.ClipperTempDataStacked > 0)
2914 {
2915 data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2916 data->ListClipper->TempData = data;
2917 }
2918 TempData = NULL;
2919 }
2920 ItemsCount = -1;
2921}
2922
2923void ImGuiListClipper::IncludeItemsByIndex(int item_begin, int item_end)
2924{
2925 ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
2926 IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
2927 IM_ASSERT(item_begin <= item_end);
2928 if (item_begin < item_end)
2929 data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_begin, item_end));
2930}
2931
2932static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
2933{
2934 ImGuiContext& g = *clipper->Ctx;
2935 ImGuiWindow* window = g.CurrentWindow;
2936 ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2937 IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
2938
2939 ImGuiTable* table = g.CurrentTable;
2940 if (table && table->IsInsideRow)
2941 ImGui::TableEndRow(table);
2942
2943 // No items
2944 if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
2945 return false;
2946
2947 // While we are in frozen row state, keep displaying items one by one, unclipped
2948 // FIXME: Could be stored as a table-agnostic state.
2949 if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
2950 {
2951 clipper->DisplayStart = data->ItemsFrozen;
2952 clipper->DisplayEnd = ImMin(data->ItemsFrozen + 1, clipper->ItemsCount);
2953 if (clipper->DisplayStart < clipper->DisplayEnd)
2954 data->ItemsFrozen++;
2955 return true;
2956 }
2957
2958 // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
2959 bool calc_clipping = false;
2960 if (data->StepNo == 0)
2961 {
2962 clipper->StartPosY = window->DC.CursorPos.y;
2963 if (clipper->ItemsHeight <= 0.0f)
2964 {
2965 // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
2966 data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1));
2967 clipper->DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen);
2968 clipper->DisplayEnd = ImMin(data->Ranges[0].Max, clipper->ItemsCount);
2969 data->StepNo = 1;
2970 return true;
2971 }
2972 calc_clipping = true; // If on the first step with known item height, calculate clipping.
2973 }
2974
2975 // Step 1: Let the clipper infer height from first range
2976 if (clipper->ItemsHeight <= 0.0f)
2977 {
2978 IM_ASSERT(data->StepNo == 1);
2979 if (table)
2980 IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
2981
2982 clipper->ItemsHeight = (window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
2983 bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);
2984 if (affected_by_floating_point_precision)
2985 clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
2986
2987 IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
2988 calc_clipping = true; // If item height had to be calculated, calculate clipping afterwards.
2989 }
2990
2991 // Step 0 or 1: Calculate the actual ranges of visible elements.
2992 const int already_submitted = clipper->DisplayEnd;
2993 if (calc_clipping)
2994 {
2995 if (g.LogEnabled)
2996 {
2997 // If logging is active, do not perform any clipping
2998 data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, clipper->ItemsCount));
2999 }
3000 else
3001 {
3002 // Add range selected to be included for navigation
3003 const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
3004 if (is_nav_request)
3005 data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0));
3006 if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && g.NavTabbingDir == -1)
3007 data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount));
3008
3009 // Add focused/active item
3010 ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]);
3011 if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
3012 data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0));
3013
3014 // Add visible range
3015 const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
3016 const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
3017 data->Ranges.push_back(ImGuiListClipperRange::FromPositions(window->ClipRect.Min.y, window->ClipRect.Max.y, off_min, off_max));
3018 }
3019
3020 // Convert position ranges to item index ranges
3021 // - 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.
3022 // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
3023 // which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
3024 for (ImGuiListClipperRange& range : data->Ranges)
3025 if (range.PosToIndexConvert)
3026 {
3027 int m1 = (int)(((double)range.Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
3028 int m2 = (int)((((double)range.Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
3029 range.Min = ImClamp(already_submitted + m1 + range.PosToIndexOffsetMin, already_submitted, clipper->ItemsCount - 1);
3030 range.Max = ImClamp(already_submitted + m2 + range.PosToIndexOffsetMax, range.Min + 1, clipper->ItemsCount);
3031 range.PosToIndexConvert = false;
3032 }
3033 ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo);
3034 }
3035
3036 // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
3037 while (data->StepNo < data->Ranges.Size)
3038 {
3039 clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted);
3040 clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount);
3041 if (clipper->DisplayStart > already_submitted) //-V1051
3042 ImGuiListClipper_SeekCursorForItem(clipper, clipper->DisplayStart);
3043 data->StepNo++;
3044 if (clipper->DisplayStart == clipper->DisplayEnd && data->StepNo < data->Ranges.Size)
3045 continue;
3046 return true;
3047 }
3048
3049 // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
3050 // Advance the cursor to the end of the list and then returns 'false' to end the loop.
3051 if (clipper->ItemsCount < INT_MAX)
3052 ImGuiListClipper_SeekCursorForItem(clipper, clipper->ItemsCount);
3053
3054 return false;
3055}
3056
3057bool ImGuiListClipper::Step()
3058{
3059 ImGuiContext& g = *Ctx;
3060 bool need_items_height = (ItemsHeight <= 0.0f);
3061 bool ret = ImGuiListClipper_StepInternal(this);
3062 if (ret && (DisplayStart == DisplayEnd))
3063 ret = false;
3064 if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
3065 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
3066 if (need_items_height && ItemsHeight > 0.0f)
3067 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
3068 if (ret)
3069 {
3070 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
3071 }
3072 else
3073 {
3074 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
3075 End();
3076 }
3077 return ret;
3078}
3079
3080//-----------------------------------------------------------------------------
3081// [SECTION] STYLING
3082//-----------------------------------------------------------------------------
3083
3084ImGuiStyle& ImGui::GetStyle()
3085{
3086 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
3087 return GImGui->Style;
3088}
3089
3090ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
3091{
3092 ImGuiStyle& style = GImGui->Style;
3093 ImVec4 c = style.Colors[idx];
3094 c.w *= style.Alpha * alpha_mul;
3095 return ColorConvertFloat4ToU32(c);
3096}
3097
3098ImU32 ImGui::GetColorU32(const ImVec4& col)
3099{
3100 ImGuiStyle& style = GImGui->Style;
3101 ImVec4 c = col;
3102 c.w *= style.Alpha;
3103 return ColorConvertFloat4ToU32(c);
3104}
3105
3106const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
3107{
3108 ImGuiStyle& style = GImGui->Style;
3109 return style.Colors[idx];
3110}
3111
3112ImU32 ImGui::GetColorU32(ImU32 col, float alpha_mul)
3113{
3114 ImGuiStyle& style = GImGui->Style;
3115 alpha_mul *= style.Alpha;
3116 if (alpha_mul >= 1.0f)
3117 return col;
3118 ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
3119 a = (ImU32)(a * alpha_mul); // We don't need to clamp 0..255 because alpha is in 0..1 range.
3120 return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
3121}
3122
3123// 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
3124void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
3125{
3126 ImGuiContext& g = *GImGui;
3127 ImGuiColorMod backup;
3128 backup.Col = idx;
3129 backup.BackupValue = g.Style.Colors[idx];
3130 g.ColorStack.push_back(backup);
3131 if (g.DebugFlashStyleColorIdx != idx)
3132 g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
3133}
3134
3135void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
3136{
3137 ImGuiContext& g = *GImGui;
3138 ImGuiColorMod backup;
3139 backup.Col = idx;
3140 backup.BackupValue = g.Style.Colors[idx];
3141 g.ColorStack.push_back(backup);
3142 if (g.DebugFlashStyleColorIdx != idx)
3143 g.Style.Colors[idx] = col;
3144}
3145
3146void ImGui::PopStyleColor(int count)
3147{
3148 ImGuiContext& g = *GImGui;
3149 if (g.ColorStack.Size < count)
3150 {
3151 IM_ASSERT_USER_ERROR(g.ColorStack.Size > count, "Calling PopStyleColor() too many times!");
3152 count = g.ColorStack.Size;
3153 }
3154 while (count > 0)
3155 {
3156 ImGuiColorMod& backup = g.ColorStack.back();
3157 g.Style.Colors[backup.Col] = backup.BackupValue;
3158 g.ColorStack.pop_back();
3159 count--;
3160 }
3161}
3162
3163static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] =
3164{
3165 ImGuiCol_Text, ImGuiCol_Tab, ImGuiCol_TabHovered, ImGuiCol_TabActive, ImGuiCol_TabUnfocused, ImGuiCol_TabUnfocusedActive
3166};
3167
3168static const ImGuiDataVarInfo GStyleVarInfo[] =
3169{
3170 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
3171 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, DisabledAlpha) }, // ImGuiStyleVar_DisabledAlpha
3172 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
3173 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
3174 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
3175 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
3176 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
3177 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
3178 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
3179 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
3180 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
3181 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
3182 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
3183 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
3184 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
3185 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
3186 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
3187 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, CellPadding) }, // ImGuiStyleVar_CellPadding
3188 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
3189 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
3190 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
3191 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
3192 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding
3193 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBarBorderSize) }, // ImGuiStyleVar_TabBarBorderSize
3194 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
3195 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
3196 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize) },// ImGuiStyleVar_SeparatorTextBorderSize
3197 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextAlign) }, // ImGuiStyleVar_SeparatorTextAlign
3198 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextPadding) }, // ImGuiStyleVar_SeparatorTextPadding
3199 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, DockingSeparatorSize) }, // ImGuiStyleVar_DockingSeparatorSize
3200};
3201
3202const ImGuiDataVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx)
3203{
3204 IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3205 IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
3206 return &GStyleVarInfo[idx];
3207}
3208
3209void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3210{
3211 ImGuiContext& g = *GImGui;
3212 const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3213 if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
3214 {
3215 float* pvar = (float*)var_info->GetVarPtr(&g.Style);
3216 g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3217 *pvar = val;
3218 return;
3219 }
3220 IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3221}
3222
3223void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3224{
3225 ImGuiContext& g = *GImGui;
3226 const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3227 if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
3228 {
3229 ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3230 g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3231 *pvar = val;
3232 return;
3233 }
3234 IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3235}
3236
3237void ImGui::PopStyleVar(int count)
3238{
3239 ImGuiContext& g = *GImGui;
3240 if (g.StyleVarStack.Size < count)
3241 {
3242 IM_ASSERT_USER_ERROR(g.StyleVarStack.Size > count, "Calling PopStyleVar() too many times!");
3243 count = g.StyleVarStack.Size;
3244 }
3245 while (count > 0)
3246 {
3247 // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3248 ImGuiStyleMod& backup = g.StyleVarStack.back();
3249 const ImGuiDataVarInfo* info = GetStyleVarInfo(backup.VarIdx);
3250 void* data = info->GetVarPtr(&g.Style);
3251 if (info->Type == ImGuiDataType_Float && info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; }
3252 else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3253 g.StyleVarStack.pop_back();
3254 count--;
3255 }
3256}
3257
3258const char* ImGui::GetStyleColorName(ImGuiCol idx)
3259{
3260 // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3261 switch (idx)
3262 {
3263 case ImGuiCol_Text: return "Text";
3264 case ImGuiCol_TextDisabled: return "TextDisabled";
3265 case ImGuiCol_WindowBg: return "WindowBg";
3266 case ImGuiCol_ChildBg: return "ChildBg";
3267 case ImGuiCol_PopupBg: return "PopupBg";
3268 case ImGuiCol_Border: return "Border";
3269 case ImGuiCol_BorderShadow: return "BorderShadow";
3270 case ImGuiCol_FrameBg: return "FrameBg";
3271 case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3272 case ImGuiCol_FrameBgActive: return "FrameBgActive";
3273 case ImGuiCol_TitleBg: return "TitleBg";
3274 case ImGuiCol_TitleBgActive: return "TitleBgActive";
3275 case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3276 case ImGuiCol_MenuBarBg: return "MenuBarBg";
3277 case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3278 case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3279 case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3280 case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3281 case ImGuiCol_CheckMark: return "CheckMark";
3282 case ImGuiCol_SliderGrab: return "SliderGrab";
3283 case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3284 case ImGuiCol_Button: return "Button";
3285 case ImGuiCol_ButtonHovered: return "ButtonHovered";
3286 case ImGuiCol_ButtonActive: return "ButtonActive";
3287 case ImGuiCol_Header: return "Header";
3288 case ImGuiCol_HeaderHovered: return "HeaderHovered";
3289 case ImGuiCol_HeaderActive: return "HeaderActive";
3290 case ImGuiCol_Separator: return "Separator";
3291 case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3292 case ImGuiCol_SeparatorActive: return "SeparatorActive";
3293 case ImGuiCol_ResizeGrip: return "ResizeGrip";
3294 case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3295 case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3296 case ImGuiCol_Tab: return "Tab";
3297 case ImGuiCol_TabHovered: return "TabHovered";
3298 case ImGuiCol_TabActive: return "TabActive";
3299 case ImGuiCol_TabUnfocused: return "TabUnfocused";
3300 case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
3301 case ImGuiCol_DockingPreview: return "DockingPreview";
3302 case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
3303 case ImGuiCol_PlotLines: return "PlotLines";
3304 case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3305 case ImGuiCol_PlotHistogram: return "PlotHistogram";
3306 case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3307 case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3308 case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3309 case ImGuiCol_TableBorderLight: return "TableBorderLight";
3310 case ImGuiCol_TableRowBg: return "TableRowBg";
3311 case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3312 case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3313 case ImGuiCol_DragDropTarget: return "DragDropTarget";
3314 case ImGuiCol_NavHighlight: return "NavHighlight";
3315 case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3316 case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3317 case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3318 }
3319 IM_ASSERT(0);
3320 return "Unknown";
3321}
3322
3323
3324//-----------------------------------------------------------------------------
3325// [SECTION] RENDER HELPERS
3326// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3327// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3328// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3329//-----------------------------------------------------------------------------
3330
3331const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3332{
3333 const char* text_display_end = text;
3334 if (!text_end)
3335 text_end = (const char*)-1;
3336
3337 while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3338 text_display_end++;
3339 return text_display_end;
3340}
3341
3342// Internal ImGui functions to render text
3343// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3344void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3345{
3346 ImGuiContext& g = *GImGui;
3347 ImGuiWindow* window = g.CurrentWindow;
3348
3349 // Hide anything after a '##' string
3350 const char* text_display_end;
3351 if (hide_text_after_hash)
3352 {
3353 text_display_end = FindRenderedTextEnd(text, text_end);
3354 }
3355 else
3356 {
3357 if (!text_end)
3358 text_end = text + strlen(text); // FIXME-OPT
3359 text_display_end = text_end;
3360 }
3361
3362 if (text != text_display_end)
3363 {
3364 window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
3365 if (g.LogEnabled)
3366 LogRenderedText(&pos, text, text_display_end);
3367 }
3368}
3369
3370void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3371{
3372 ImGuiContext& g = *GImGui;
3373 ImGuiWindow* window = g.CurrentWindow;
3374
3375 if (!text_end)
3376 text_end = text + strlen(text); // FIXME-OPT
3377
3378 if (text != text_end)
3379 {
3380 window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
3381 if (g.LogEnabled)
3382 LogRenderedText(&pos, text, text_end);
3383 }
3384}
3385
3386// Default clip_rect uses (pos_min,pos_max)
3387// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3388// FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especally for text above draw_list->DrawList.
3389// Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take
3390// better advantage of the render function taking size into account for coarse clipping.
3391void 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)
3392{
3393 // Perform CPU side clipping for single clipped element to avoid using scissor state
3394 ImVec2 pos = pos_min;
3395 const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
3396
3397 const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3398 const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3399 bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3400 if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3401 need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3402
3403 // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3404 if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3405 if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3406
3407 // Render
3408 if (need_clipping)
3409 {
3410 ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3411 draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
3412 }
3413 else
3414 {
3415 draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
3416 }
3417}
3418
3419void 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)
3420{
3421 // Hide anything after a '##' string
3422 const char* text_display_end = FindRenderedTextEnd(text, text_end);
3423 const int text_len = (int)(text_display_end - text);
3424 if (text_len == 0)
3425 return;
3426
3427 ImGuiContext& g = *GImGui;
3428 ImGuiWindow* window = g.CurrentWindow;
3429 RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3430 if (g.LogEnabled)
3431 LogRenderedText(&pos_min, text, text_display_end);
3432}
3433
3434// Another overly complex function until we reorganize everything into a nice all-in-one helper.
3435// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
3436// 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.
3437void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
3438{
3439 ImGuiContext& g = *GImGui;
3440 if (text_end_full == NULL)
3441 text_end_full = FindRenderedTextEnd(text);
3442 const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
3443
3444 //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
3445 //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
3446 //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
3447 // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3448 if (text_size.x > pos_max.x - pos_min.x)
3449 {
3450 // Hello wo...
3451 // | | |
3452 // min max ellipsis_max
3453 // <-> this is generally some padding value
3454
3455 const ImFont* font = draw_list->_Data->Font;
3456 const float font_size = draw_list->_Data->FontSize;
3457 const float font_scale = font_size / font->FontSize;
3458 const char* text_end_ellipsis = NULL;
3459 const float ellipsis_width = font->EllipsisWidth * font_scale;
3460
3461 // We can now claim the space between pos_max.x and ellipsis_max.x
3462 const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_width) - pos_min.x, 1.0f);
3463 float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
3464 if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
3465 {
3466 // Always display at least 1 character if there's no room for character + ellipsis
3467 text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
3468 text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
3469 }
3470 while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
3471 {
3472 // 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)
3473 text_end_ellipsis--;
3474 text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
3475 }
3476
3477 // Render text, render ellipsis
3478 RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
3479 ImVec2 ellipsis_pos = ImTrunc(ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
3480 if (ellipsis_pos.x + ellipsis_width <= ellipsis_max_x)
3481 for (int i = 0; i < font->EllipsisCharCount; i++, ellipsis_pos.x += font->EllipsisCharStep * font_scale)
3482 font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar);
3483 }
3484 else
3485 {
3486 RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
3487 }
3488
3489 if (g.LogEnabled)
3490 LogRenderedText(&pos_min, text, text_end_full);
3491}
3492
3493// Render a rectangle shaped with optional rounding and borders
3494void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
3495{
3496 ImGuiContext& g = *GImGui;
3497 ImGuiWindow* window = g.CurrentWindow;
3498 window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
3499 const float border_size = g.Style.FrameBorderSize;
3500 if (border && border_size > 0.0f)
3501 {
3502 window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3503 window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3504 }
3505}
3506
3507void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
3508{
3509 ImGuiContext& g = *GImGui;
3510 ImGuiWindow* window = g.CurrentWindow;
3511 const float border_size = g.Style.FrameBorderSize;
3512 if (border_size > 0.0f)
3513 {
3514 window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3515 window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3516 }
3517}
3518
3519void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
3520{
3521 ImGuiContext& g = *GImGui;
3522 if (id != g.NavId)
3523 return;
3524 if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
3525 return;
3526 ImGuiWindow* window = g.CurrentWindow;
3527 if (window->DC.NavHideHighlightOneFrame)
3528 return;
3529
3530 float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
3531 ImRect display_rect = bb;
3532 display_rect.ClipWith(window->ClipRect);
3533 const float thickness = 2.0f;
3534 if (flags & ImGuiNavHighlightFlags_Compact)
3535 {
3536 window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, thickness);
3537 }
3538 else
3539 {
3540 const float distance = 3.0f + thickness * 0.5f;
3541 display_rect.Expand(ImVec2(distance, distance));
3542 bool fully_visible = window->ClipRect.Contains(display_rect);
3543 if (!fully_visible)
3544 window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
3545 window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, thickness);
3546 if (!fully_visible)
3547 window->DrawList->PopClipRect();
3548 }
3549}
3550
3551void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
3552{
3553 ImGuiContext& g = *GImGui;
3554 IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT);
3555 ImFontAtlas* font_atlas = g.DrawListSharedData.Font->ContainerAtlas;
3556 for (ImGuiViewportP* viewport : g.Viewports)
3557 {
3558 // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
3559 ImVec2 offset, size, uv[4];
3560 if (!font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2]))
3561 continue;
3562 const ImVec2 pos = base_pos - offset;
3563 const float scale = base_scale * viewport->DpiScale;
3564 if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
3565 continue;
3566 ImDrawList* draw_list = GetForegroundDrawList(viewport);
3567 ImTextureID tex_id = font_atlas->TexID;
3568 draw_list->PushTextureID(tex_id);
3569 draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow);
3570 draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow);
3571 draw_list->AddImage(tex_id, pos, pos + size * scale, uv[2], uv[3], col_border);
3572 draw_list->AddImage(tex_id, pos, pos + size * scale, uv[0], uv[1], col_fill);
3573 draw_list->PopTextureID();
3574 }
3575}
3576
3577//-----------------------------------------------------------------------------
3578// [SECTION] INITIALIZATION, SHUTDOWN
3579//-----------------------------------------------------------------------------
3580
3581// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
3582// 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
3583ImGuiContext* ImGui::GetCurrentContext()
3584{
3585 return GImGui;
3586}
3587
3588void ImGui::SetCurrentContext(ImGuiContext* ctx)
3589{
3590#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
3591 IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
3592#else
3593 GImGui = ctx;
3594#endif
3595}
3596
3597void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
3598{
3599 GImAllocatorAllocFunc = alloc_func;
3600 GImAllocatorFreeFunc = free_func;
3601 GImAllocatorUserData = user_data;
3602}
3603
3604// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
3605void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
3606{
3607 *p_alloc_func = GImAllocatorAllocFunc;
3608 *p_free_func = GImAllocatorFreeFunc;
3609 *p_user_data = GImAllocatorUserData;
3610}
3611
3612ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
3613{
3614 ImGuiContext* prev_ctx = GetCurrentContext();
3615 ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
3616 SetCurrentContext(ctx);
3617 Initialize();
3618 if (prev_ctx != NULL)
3619 SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
3620 return ctx;
3621}
3622
3623void ImGui::DestroyContext(ImGuiContext* ctx)
3624{
3625 ImGuiContext* prev_ctx = GetCurrentContext();
3626 if (ctx == NULL) //-V1051
3627 ctx = prev_ctx;
3628 SetCurrentContext(ctx);
3629 Shutdown();
3630 SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
3631 IM_DELETE(ctx);
3632}
3633
3634// IMPORTANT: ###xxx suffixes must be same in ALL languages
3635static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
3636{
3637 { ImGuiLocKey_VersionStr, "Dear ImGui " IMGUI_VERSION " (" IM_STRINGIFY(IMGUI_VERSION_NUM) ")" },
3638 { ImGuiLocKey_TableSizeOne, "Size column to fit###SizeOne" },
3639 { ImGuiLocKey_TableSizeAllFit, "Size all columns to fit###SizeAll" },
3640 { ImGuiLocKey_TableSizeAllDefault, "Size all columns to default###SizeAll" },
3641 { ImGuiLocKey_TableResetOrder, "Reset order###ResetOrder" },
3642 { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)" },
3643 { ImGuiLocKey_WindowingPopup, "(Popup)" },
3644 { ImGuiLocKey_WindowingUntitled, "(Untitled)" },
3645 { ImGuiLocKey_DockingHideTabBar, "Hide tab bar###HideTabBar" },
3646 { ImGuiLocKey_DockingHoldShiftToDock, "Hold SHIFT to enable Docking window." },
3647 { ImGuiLocKey_DockingDragToUndockOrMoveNode,"Click and drag to move or undock whole node." },
3648};
3649
3650void ImGui::Initialize()
3651{
3652 ImGuiContext& g = *GImGui;
3653 IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
3654
3655 // Add .ini handle for ImGuiWindow and ImGuiTable types
3656 {
3657 ImGuiSettingsHandler ini_handler;
3658 ini_handler.TypeName = "Window";
3659 ini_handler.TypeHash = ImHashStr("Window");
3660 ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
3661 ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
3662 ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
3663 ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
3664 ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
3665 AddSettingsHandler(&ini_handler);
3666 }
3667 TableSettingsAddSettingsHandler();
3668
3669 // Setup default localization table
3670 LocalizeRegisterEntries(GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS));
3671
3672 // Setup default platform clipboard/IME handlers.
3673 g.IO.GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
3674 g.IO.SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
3675 g.IO.ClipboardUserData = (void*)&g; // Default implementation use the ImGuiContext as user data (ideally those would be arguments to the function)
3676 g.IO.SetPlatformImeDataFn = SetPlatformImeDataFn_DefaultImpl;
3677
3678 // Create default viewport
3679 ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
3680 viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
3681 viewport->Idx = 0;
3682 viewport->PlatformWindowCreated = true;
3683 viewport->Flags = ImGuiViewportFlags_OwnedByApp;
3684 g.Viewports.push_back(viewport);
3685 g.TempBuffer.resize(1024 * 3 + 1, 0);
3686 g.ViewportCreatedCount++;
3687 g.PlatformIO.Viewports.push_back(g.Viewports[0]);
3688
3689 // Build KeysMayBeCharInput[] lookup table (1 bool per named key)
3690 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
3691 if ((key >= ImGuiKey_0 && key <= ImGuiKey_9) || (key >= ImGuiKey_A && key <= ImGuiKey_Z) || (key >= ImGuiKey_Keypad0 && key <= ImGuiKey_Keypad9)
3692 || key == ImGuiKey_Tab || key == ImGuiKey_Space || key == ImGuiKey_Apostrophe || key == ImGuiKey_Comma || key == ImGuiKey_Minus || key == ImGuiKey_Period
3693 || key == ImGuiKey_Slash || key == ImGuiKey_Semicolon || key == ImGuiKey_Equal || key == ImGuiKey_LeftBracket || key == ImGuiKey_RightBracket || key == ImGuiKey_GraveAccent
3694 || key == ImGuiKey_KeypadDecimal || key == ImGuiKey_KeypadDivide || key == ImGuiKey_KeypadMultiply || key == ImGuiKey_KeypadSubtract || key == ImGuiKey_KeypadAdd || key == ImGuiKey_KeypadEqual)
3695 g.KeysMayBeCharInput.SetBit(key);
3696
3697#ifdef IMGUI_HAS_DOCK
3698 // Initialize Docking
3699 DockContextInitialize(&g);
3700#endif
3701
3702 g.Initialized = true;
3703}
3704
3705// This function is merely here to free heap allocations.
3706void ImGui::Shutdown()
3707{
3708 ImGuiContext& g = *GImGui;
3709 IM_ASSERT_USER_ERROR(g.IO.BackendPlatformUserData == NULL, "Forgot to shutdown Platform backend?");
3710 IM_ASSERT_USER_ERROR(g.IO.BackendRendererUserData == NULL, "Forgot to shutdown Renderer backend?");
3711
3712 // 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)
3713 if (g.IO.Fonts && g.FontAtlasOwnedByContext)
3714 {
3715 g.IO.Fonts->Locked = false;
3716 IM_DELETE(g.IO.Fonts);
3717 }
3718 g.IO.Fonts = NULL;
3719 g.DrawListSharedData.TempBuffer.clear();
3720
3721 // Cleanup of other data are conditional on actually having initialized Dear ImGui.
3722 if (!g.Initialized)
3723 return;
3724
3725 // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
3726 if (g.SettingsLoaded && g.IO.IniFilename != NULL)
3727 SaveIniSettingsToDisk(g.IO.IniFilename);
3728
3729 // Destroy platform windows
3730 DestroyPlatformWindows();
3731
3732 // Shutdown extensions
3733 DockContextShutdown(&g);
3734
3735 CallContextHooks(&g, ImGuiContextHookType_Shutdown);
3736
3737 // Clear everything else
3738 g.Windows.clear_delete();
3739 g.WindowsFocusOrder.clear();
3740 g.WindowsTempSortBuffer.clear();
3741 g.CurrentWindow = NULL;
3742 g.CurrentWindowStack.clear();
3743 g.WindowsById.Clear();
3744 g.NavWindow = NULL;
3745 g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
3746 g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
3747 g.MovingWindow = NULL;
3748
3749 g.KeysRoutingTable.Clear();
3750
3751 g.ColorStack.clear();
3752 g.StyleVarStack.clear();
3753 g.FontStack.clear();
3754 g.OpenPopupStack.clear();
3755 g.BeginPopupStack.clear();
3756 g.NavTreeNodeStack.clear();
3757
3758 g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
3759 g.Viewports.clear_delete();
3760
3761 g.TabBars.Clear();
3762 g.CurrentTabBarStack.clear();
3763 g.ShrinkWidthBuffer.clear();
3764
3765 g.ClipperTempData.clear_destruct();
3766
3767 g.Tables.Clear();
3768 g.TablesTempData.clear_destruct();
3769 g.DrawChannelsTempMergeBuffer.clear();
3770
3771 g.ClipboardHandlerData.clear();
3772 g.MenusIdSubmittedThisFrame.clear();
3773 g.InputTextState.ClearFreeMemory();
3774 g.InputTextDeactivatedState.ClearFreeMemory();
3775
3776 g.SettingsWindows.clear();
3777 g.SettingsHandlers.clear();
3778
3779 if (g.LogFile)
3780 {
3781#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
3782 if (g.LogFile != stdout)
3783#endif
3784 ImFileClose(g.LogFile);
3785 g.LogFile = NULL;
3786 }
3787 g.LogBuffer.clear();
3788 g.DebugLogBuf.clear();
3789 g.DebugLogIndex.clear();
3790
3791 g.Initialized = false;
3792}
3793
3794// No specific ordering/dependency support, will see as needed
3795ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
3796{
3797 ImGuiContext& g = *ctx;
3798 IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
3799 g.Hooks.push_back(*hook);
3800 g.Hooks.back().HookId = ++g.HookIdNext;
3801 return g.HookIdNext;
3802}
3803
3804// Deferred removal, avoiding issue with changing vector while iterating it
3805void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
3806{
3807 ImGuiContext& g = *ctx;
3808 IM_ASSERT(hook_id != 0);
3809 for (ImGuiContextHook& hook : g.Hooks)
3810 if (hook.HookId == hook_id)
3811 hook.Type = ImGuiContextHookType_PendingRemoval_;
3812}
3813
3814// Call context hooks (used by e.g. test engine)
3815// We assume a small number of hooks so all stored in same array
3816void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
3817{
3818 ImGuiContext& g = *ctx;
3819 for (ImGuiContextHook& hook : g.Hooks)
3820 if (hook.Type == hook_type)
3821 hook.Callback(&g, &hook);
3822}
3823
3824
3825//-----------------------------------------------------------------------------
3826// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
3827//-----------------------------------------------------------------------------
3828
3829// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
3830ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NULL)
3831{
3832 memset(this, 0, sizeof(*this));
3833 Ctx = ctx;
3834 Name = ImStrdup(name);
3835 NameBufLen = (int)strlen(name) + 1;
3836 ID = ImHashStr(name);
3837 IDStack.push_back(ID);
3838 ViewportAllowPlatformMonitorExtend = -1;
3839 ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
3840 MoveId = GetID("#MOVE");
3841 TabId = GetID("#TAB");
3842 ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
3843 ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
3844 AutoFitFramesX = AutoFitFramesY = -1;
3845 AutoPosLastDirection = ImGuiDir_None;
3846 SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = 0;
3847 SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
3848 LastFrameActive = -1;
3849 LastFrameJustFocused = -1;
3850 LastTimeActive = -1.0f;
3851 FontWindowScale = FontDpiScale = 1.0f;
3852 SettingsOffset = -1;
3853 DockOrder = -1;
3854 DrawList = &DrawListInst;
3855 DrawList->_Data = &Ctx->DrawListSharedData;
3856 DrawList->_OwnerName = Name;
3857 NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX);
3858 IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass();
3859}
3860
3861ImGuiWindow::~ImGuiWindow()
3862{
3863 IM_ASSERT(DrawList == &DrawListInst);
3864 IM_DELETE(Name);
3865 ColumnsStorage.clear_destruct();
3866}
3867
3868ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
3869{
3870 ImGuiID seed = IDStack.back();
3871 ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
3872 ImGuiContext& g = *Ctx;
3873 if (g.DebugHookIdInfo == id)
3874 ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
3875 return id;
3876}
3877
3878ImGuiID ImGuiWindow::GetID(const void* ptr)
3879{
3880 ImGuiID seed = IDStack.back();
3881 ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
3882 ImGuiContext& g = *Ctx;
3883 if (g.DebugHookIdInfo == id)
3884 ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
3885 return id;
3886}
3887
3888ImGuiID ImGuiWindow::GetID(int n)
3889{
3890 ImGuiID seed = IDStack.back();
3891 ImGuiID id = ImHashData(&n, sizeof(n), seed);
3892 ImGuiContext& g = *Ctx;
3893 if (g.DebugHookIdInfo == id)
3894 ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
3895 return id;
3896}
3897
3898// This is only used in rare/specific situations to manufacture an ID out of nowhere.
3899ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
3900{
3901 ImGuiID seed = IDStack.back();
3902 ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs);
3903 ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
3904 return id;
3905}
3906
3907static void SetCurrentWindow(ImGuiWindow* window)
3908{
3909 ImGuiContext& g = *GImGui;
3910 g.CurrentWindow = window;
3911 g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
3912 if (window)
3913 {
3914 g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
3915 ImGui::NavUpdateCurrentWindowIsScrollPushableX();
3916 }
3917}
3918
3919void ImGui::GcCompactTransientMiscBuffers()
3920{
3921 ImGuiContext& g = *GImGui;
3922 g.ItemFlagsStack.clear();
3923 g.GroupStack.clear();
3924 TableGcCompactSettings();
3925}
3926
3927// Free up/compact internal window buffers, we can use this when a window becomes unused.
3928// Not freed:
3929// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
3930// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
3931void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
3932{
3933 window->MemoryCompacted = true;
3934 window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
3935 window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
3936 window->IDStack.clear();
3937 window->DrawList->_ClearFreeMemory();
3938 window->DC.ChildWindows.clear();
3939 window->DC.ItemWidthStack.clear();
3940 window->DC.TextWrapPosStack.clear();
3941}
3942
3943void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
3944{
3945 // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
3946 // The other buffers tends to amortize much faster.
3947 window->MemoryCompacted = false;
3948 window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
3949 window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
3950 window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
3951}
3952
3953void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
3954{
3955 ImGuiContext& g = *GImGui;
3956
3957 // Clear previous active id
3958 if (g.ActiveId != 0)
3959 {
3960 // While most behaved code would make an effort to not steal active id during window move/drag operations,
3961 // we at least need to be resilient to it. Canceling the move is rather aggressive and users of 'master' branch
3962 // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
3963 if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
3964 {
3965 IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
3966 g.MovingWindow = NULL;
3967 }
3968
3969 // This could be written in a more general way (e.g associate a hook to ActiveId),
3970 // but since this is currently quite an exception we'll leave it as is.
3971 // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveId()
3972 if (g.InputTextState.ID == g.ActiveId)
3973 InputTextDeactivateHook(g.ActiveId);
3974 }
3975
3976 // Set active id
3977 g.ActiveIdIsJustActivated = (g.ActiveId != id);
3978 if (g.ActiveIdIsJustActivated)
3979 {
3980 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 : "");
3981 g.ActiveIdTimer = 0.0f;
3982 g.ActiveIdHasBeenPressedBefore = false;
3983 g.ActiveIdHasBeenEditedBefore = false;
3984 g.ActiveIdMouseButton = -1;
3985 if (id != 0)
3986 {
3987 g.LastActiveId = id;
3988 g.LastActiveIdTimer = 0.0f;
3989 }
3990 }
3991 g.ActiveId = id;
3992 g.ActiveIdAllowOverlap = false;
3993 g.ActiveIdNoClearOnFocusLoss = false;
3994 g.ActiveIdWindow = window;
3995 g.ActiveIdHasBeenEditedThisFrame = false;
3996 g.ActiveIdFromShortcut = false;
3997 if (id)
3998 {
3999 g.ActiveIdIsAlive = id;
4000 g.ActiveIdSource = (g.NavActivateId == id || g.NavJustMovedToId == id) ? g.NavInputSource : ImGuiInputSource_Mouse;
4001 IM_ASSERT(g.ActiveIdSource != ImGuiInputSource_None);
4002 }
4003
4004 // Clear declaration of inputs claimed by the widget
4005 // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
4006 g.ActiveIdUsingNavDirMask = 0x00;
4007 g.ActiveIdUsingAllKeyboardKeys = false;
4008#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4009 g.ActiveIdUsingNavInputMask = 0x00;
4010#endif
4011}
4012
4013void ImGui::ClearActiveID()
4014{
4015 SetActiveID(0, NULL); // g.ActiveId = 0;
4016}
4017
4018void ImGui::SetHoveredID(ImGuiID id)
4019{
4020 ImGuiContext& g = *GImGui;
4021 g.HoveredId = id;
4022 g.HoveredIdAllowOverlap = false;
4023 if (id != 0 && g.HoveredIdPreviousFrame != id)
4024 g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
4025}
4026
4027ImGuiID ImGui::GetHoveredID()
4028{
4029 ImGuiContext& g = *GImGui;
4030 return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
4031}
4032
4033void ImGui::MarkItemEdited(ImGuiID id)
4034{
4035 // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
4036 // 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.
4037 ImGuiContext& g = *GImGui;
4038 if (g.LockMarkEdited > 0)
4039 return;
4040 if (g.ActiveId == id || g.ActiveId == 0)
4041 {
4042 g.ActiveIdHasBeenEditedThisFrame = true;
4043 g.ActiveIdHasBeenEditedBefore = true;
4044 }
4045
4046 // We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343)
4047 // We accept 'ActiveIdPreviousFrame == id' for InputText() returning an edit after it has been taken ActiveId away (#4714)
4048 IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.ActiveIdPreviousFrame == id);
4049
4050 //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
4051 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
4052}
4053
4054bool ImGui::IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
4055{
4056 // An active popup disable hovering on other windows (apart from its own children)
4057 // FIXME-OPT: This could be cached/stored within the window.
4058 ImGuiContext& g = *GImGui;
4059 if (g.NavWindow)
4060 if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindowDockTree)
4061 if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree)
4062 {
4063 // For the purpose of those flags we differentiate "standard popup" from "modal popup"
4064 // NB: The 'else' is important because Modal windows are also Popups.
4065 bool want_inhibit = false;
4066 if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
4067 want_inhibit = true;
4068 else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
4069 want_inhibit = true;
4070
4071 // Inhibit hover unless the window is within the stack of our modal/popup
4072 if (want_inhibit)
4073 if (!IsWindowWithinBeginStackOf(window->RootWindow, focused_root_window))
4074 return false;
4075 }
4076
4077 // Filter by viewport
4078 if (window->Viewport != g.MouseViewport)
4079 if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)
4080 return false;
4081
4082 return true;
4083}
4084
4085static inline float CalcDelayFromHoveredFlags(ImGuiHoveredFlags flags)
4086{
4087 ImGuiContext& g = *GImGui;
4088 if (flags & ImGuiHoveredFlags_DelayNormal)
4089 return g.Style.HoverDelayNormal;
4090 if (flags & ImGuiHoveredFlags_DelayShort)
4091 return g.Style.HoverDelayShort;
4092 return 0.0f;
4093}
4094
4095static ImGuiHoveredFlags ApplyHoverFlagsForTooltip(ImGuiHoveredFlags user_flags, ImGuiHoveredFlags shared_flags)
4096{
4097 // Allow instance flags to override shared flags
4098 if (user_flags & (ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal))
4099 shared_flags &= ~(ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal);
4100 return user_flags | shared_flags;
4101}
4102
4103// This is roughly matching the behavior of internal-facing ItemHoverable()
4104// - 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()
4105// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
4106bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
4107{
4108 ImGuiContext& g = *GImGui;
4109 ImGuiWindow* window = g.CurrentWindow;
4110 IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsItemHovered) == 0 && "Invalid flags for IsItemHovered()!");
4111
4112 if (g.NavDisableMouseHover && !g.NavDisableHighlight && !(flags & ImGuiHoveredFlags_NoNavOverride))
4113 {
4114 if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4115 return false;
4116 if (!IsItemFocused())
4117 return false;
4118
4119 if (flags & ImGuiHoveredFlags_ForTooltip)
4120 flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipNav);
4121 }
4122 else
4123 {
4124 // Test for bounding box overlap, as updated as ItemAdd()
4125 ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
4126 if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
4127 return false;
4128
4129 if (flags & ImGuiHoveredFlags_ForTooltip)
4130 flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
4131
4132 IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_DockHierarchy)) == 0); // Flags not supported by this function
4133
4134 // Done with rectangle culling so we can perform heavier checks now
4135 // Test if we are hovering the right window (our window could be behind another window)
4136 // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
4137 // [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
4138 // 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
4139 // the test that has been running for a long while.
4140 if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
4141 if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByWindow) == 0)
4142 return false;
4143
4144 // Test if another item is active (e.g. being dragged)
4145 const ImGuiID id = g.LastItemData.ID;
4146 if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
4147 if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4148 if (g.ActiveId != window->MoveId && g.ActiveId != window->TabId)
4149 return false;
4150
4151 // Test if interactions on this window are blocked by an active popup or modal.
4152 // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
4153 if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.InFlags & ImGuiItemFlags_NoWindowHoverableCheck))
4154 return false;
4155
4156 // Test if the item is disabled
4157 if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4158 return false;
4159
4160 // Special handling for calling after Begin() which represent the title bar or tab.
4161 // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin)
4162 // will never be overwritten so we need to detect the case.
4163 if (id == window->MoveId && window->WriteAccessed)
4164 return false;
4165
4166 // Test if using AllowOverlap and overlapped
4167 if ((g.LastItemData.InFlags & ImGuiItemFlags_AllowOverlap) && id != 0)
4168 if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByItem) == 0)
4169 if (g.HoveredIdPreviousFrame != g.LastItemData.ID)
4170 return false;
4171 }
4172
4173 // Handle hover delay
4174 // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
4175 const float delay = CalcDelayFromHoveredFlags(flags);
4176 if (delay > 0.0f || (flags & ImGuiHoveredFlags_Stationary))
4177 {
4178 ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromRectangle(g.LastItemData.Rect);
4179 if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverItemDelayIdPreviousFrame != hover_delay_id))
4180 g.HoverItemDelayTimer = 0.0f;
4181 g.HoverItemDelayId = hover_delay_id;
4182
4183 // When changing hovered item we requires a bit of stationary delay before activating hover timer,
4184 // but once unlocked on a given item we also moving.
4185 //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); }
4186 if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverItemUnlockedStationaryId != hover_delay_id)
4187 return false;
4188
4189 if (g.HoverItemDelayTimer < delay)
4190 return false;
4191 }
4192
4193 return true;
4194}
4195
4196// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
4197// (this does not rely on LastItemData it can be called from a ButtonBehavior() call not following an ItemAdd() call)
4198// FIXME-LEGACY: the 'ImGuiItemFlags item_flags' parameter was added on 2023-06-28.
4199// If you used this in your legacy/custom widgets code:
4200// - Commonly: if your ItemHoverable() call comes after an ItemAdd() call: pass 'item_flags = g.LastItemData.InFlags'.
4201// - Rare: otherwise you may pass 'item_flags = 0' (ImGuiItemFlags_None) unless you want to benefit from special behavior handled by ItemHoverable.
4202bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flags)
4203{
4204 ImGuiContext& g = *GImGui;
4205 ImGuiWindow* window = g.CurrentWindow;
4206 if (g.HoveredWindow != window)
4207 return false;
4208 if (!IsMouseHoveringRect(bb.Min, bb.Max))
4209 return false;
4210
4211 if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
4212 return false;
4213 if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4214 if (!g.ActiveIdFromShortcut)
4215 return false;
4216
4217 // Done with rectangle culling so we can perform heavier checks now.
4218 if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
4219 {
4220 g.HoveredIdDisabled = true;
4221 return false;
4222 }
4223
4224 // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
4225 // hover test in widgets code. We could also decide to split this function is two.
4226 if (id != 0)
4227 {
4228 // Drag source doesn't report as hovered
4229 if (g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover))
4230 return false;
4231
4232 SetHoveredID(id);
4233
4234 // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match.
4235 // This allows using patterns where a later submitted widget overlaps a previous one. Generally perceived as a front-to-back hit-test.
4236 if (item_flags & ImGuiItemFlags_AllowOverlap)
4237 {
4238 g.HoveredIdAllowOverlap = true;
4239 if (g.HoveredIdPreviousFrame != id)
4240 return false;
4241 }
4242 }
4243
4244 // When disabled we'll return false but still set HoveredId
4245 if (item_flags & ImGuiItemFlags_Disabled)
4246 {
4247 // Release active id if turning disabled
4248 if (g.ActiveId == id && id != 0)
4249 ClearActiveID();
4250 g.HoveredIdDisabled = true;
4251 return false;
4252 }
4253
4254#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4255 if (id != 0)
4256 {
4257 // [DEBUG] Item Picker tool!
4258 // We perform the check here because reaching is path is rare (1~ time a frame),
4259 // making the cost of this tool near-zero! We could get better call-stack and support picking non-hovered
4260 // items if we performed the test in ItemAdd(), but that would incur a bigger runtime cost.
4261 if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
4262 GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
4263 if (g.DebugItemPickerBreakId == id)
4264 IM_DEBUG_BREAK();
4265 }
4266#endif
4267
4268 if (g.NavDisableMouseHover)
4269 return false;
4270
4271 return true;
4272}
4273
4274// FIXME: This is inlined/duplicated in ItemAdd()
4275// FIXME: The id != 0 path is not used by our codebase, may get rid of it?
4276bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
4277{
4278 ImGuiContext& g = *GImGui;
4279 ImGuiWindow* window = g.CurrentWindow;
4280 if (!bb.Overlaps(window->ClipRect))
4281 if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
4282 if (!g.LogEnabled)
4283 return true;
4284 return false;
4285}
4286
4287// This is also inlined in ItemAdd()
4288// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect.
4289void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
4290{
4291 ImGuiContext& g = *GImGui;
4292 g.LastItemData.ID = item_id;
4293 g.LastItemData.InFlags = in_flags;
4294 g.LastItemData.StatusFlags = item_flags;
4295 g.LastItemData.Rect = g.LastItemData.NavRect = item_rect;
4296}
4297
4298float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
4299{
4300 if (wrap_pos_x < 0.0f)
4301 return 0.0f;
4302
4303 ImGuiContext& g = *GImGui;
4304 ImGuiWindow* window = g.CurrentWindow;
4305 if (wrap_pos_x == 0.0f)
4306 {
4307 // We could decide to setup a default wrapping max point for auto-resizing windows,
4308 // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
4309 //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
4310 // wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
4311 //else
4312 wrap_pos_x = window->WorkRect.Max.x;
4313 }
4314 else if (wrap_pos_x > 0.0f)
4315 {
4316 wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
4317 }
4318
4319 return ImMax(wrap_pos_x - pos.x, 1.0f);
4320}
4321
4322// IM_ALLOC() == ImGui::MemAlloc()
4323void* ImGui::MemAlloc(size_t size)
4324{
4325 void* ptr = (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
4326#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4327 if (ImGuiContext* ctx = GImGui)
4328 DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, size);
4329#endif
4330 return ptr;
4331}
4332
4333// IM_FREE() == ImGui::MemFree()
4334void ImGui::MemFree(void* ptr)
4335{
4336#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4337 if (ptr != NULL)
4338 if (ImGuiContext* ctx = GImGui)
4339 DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, (size_t)-1);
4340#endif
4341 return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
4342}
4343
4344// 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"
4345void ImGui::DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size)
4346{
4347 ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4348 IM_UNUSED(ptr);
4349 if (entry->FrameCount != frame_count)
4350 {
4351 info->LastEntriesIdx = (info->LastEntriesIdx + 1) % IM_ARRAYSIZE(info->LastEntriesBuf);
4352 entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4353 entry->FrameCount = frame_count;
4354 entry->AllocCount = entry->FreeCount = 0;
4355 }
4356 if (size != (size_t)-1)
4357 {
4358 entry->AllocCount++;
4359 info->TotalAllocCount++;
4360 //printf("[%05d] MemAlloc(%d) -> 0x%p\n", frame_count, size, ptr);
4361 }
4362 else
4363 {
4364 entry->FreeCount++;
4365 info->TotalFreeCount++;
4366 //printf("[%05d] MemFree(0x%p)\n", frame_count, ptr);
4367 }
4368}
4369
4370const char* ImGui::GetClipboardText()
4371{
4372 ImGuiContext& g = *GImGui;
4373 return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
4374}
4375
4376void ImGui::SetClipboardText(const char* text)
4377{
4378 ImGuiContext& g = *GImGui;
4379 if (g.IO.SetClipboardTextFn)
4380 g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
4381}
4382
4383const char* ImGui::GetVersion()
4384{
4385 return IMGUI_VERSION;
4386}
4387
4388ImGuiIO& ImGui::GetIO()
4389{
4390 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4391 return GImGui->IO;
4392}
4393
4394ImGuiPlatformIO& ImGui::GetPlatformIO()
4395{
4396 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
4397 return GImGui->PlatformIO;
4398}
4399
4400// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
4401ImDrawData* ImGui::GetDrawData()
4402{
4403 ImGuiContext& g = *GImGui;
4404 ImGuiViewportP* viewport = g.Viewports[0];
4405 return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
4406}
4407
4408double ImGui::GetTime()
4409{
4410 return GImGui->Time;
4411}
4412
4413int ImGui::GetFrameCount()
4414{
4415 return GImGui->FrameCount;
4416}
4417
4418static ImDrawList* GetViewportBgFgDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
4419{
4420 // Create the draw list on demand, because they are not frequently used for all viewports
4421 ImGuiContext& g = *GImGui;
4422 IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->BgFgDrawLists));
4423 ImDrawList* draw_list = viewport->BgFgDrawLists[drawlist_no];
4424 if (draw_list == NULL)
4425 {
4426 draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
4427 draw_list->_OwnerName = drawlist_name;
4428 viewport->BgFgDrawLists[drawlist_no] = draw_list;
4429 }
4430
4431 // Our ImDrawList system requires that there is always a command
4432 if (viewport->BgFgDrawListsLastFrame[drawlist_no] != g.FrameCount)
4433 {
4434 draw_list->_ResetForNewFrame();
4435 draw_list->PushTextureID(g.IO.Fonts->TexID);
4436 draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
4437 viewport->BgFgDrawListsLastFrame[drawlist_no] = g.FrameCount;
4438 }
4439 return draw_list;
4440}
4441
4442ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
4443{
4444 return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 0, "##Background");
4445}
4446
4447ImDrawList* ImGui::GetBackgroundDrawList()
4448{
4449 ImGuiContext& g = *GImGui;
4450 return GetBackgroundDrawList(g.CurrentWindow->Viewport);
4451}
4452
4453ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
4454{
4455 return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
4456}
4457
4458ImDrawList* ImGui::GetForegroundDrawList()
4459{
4460 ImGuiContext& g = *GImGui;
4461 return GetForegroundDrawList(g.CurrentWindow->Viewport);
4462}
4463
4464ImDrawListSharedData* ImGui::GetDrawListSharedData()
4465{
4466 return &GImGui->DrawListSharedData;
4467}
4468
4469void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
4470{
4471 // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
4472 // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
4473 // This is because we want ActiveId to be set even when the window is not permitted to move.
4474 ImGuiContext& g = *GImGui;
4475 FocusWindow(window);
4476 SetActiveID(window->MoveId, window);
4477 g.NavDisableHighlight = true;
4478 g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos;
4479 g.ActiveIdNoClearOnFocusLoss = true;
4480 SetActiveIdUsingAllKeyboardKeys();
4481
4482 bool can_move_window = true;
4483 if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove))
4484 can_move_window = false;
4485 if (ImGuiDockNode* node = window->DockNodeAsHost)
4486 if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
4487 can_move_window = false;
4488 if (can_move_window)
4489 g.MovingWindow = window;
4490}
4491
4492// We use 'undock == false' when dragging from title bar to allow moving groups of floating nodes without undocking them.
4493void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock)
4494{
4495 ImGuiContext& g = *GImGui;
4496 bool can_undock_node = false;
4497 if (undock && node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0 && (node->MergedFlags & ImGuiDockNodeFlags_NoUndocking) == 0)
4498 {
4499 // Can undock if:
4500 // - part of a hierarchy with more than one visible node (if only one is visible, we'll just move the root window)
4501 // - part of a dockspace node hierarchy: so we can undock the last single visible node too (trivia: undocking from a fixed/central node will create a new node and copy windows)
4502 ImGuiDockNode* root_node = DockNodeGetRootNode(node);
4503 if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL) // -V1051 PVS-Studio thinks node should be root_node and is wrong about that.
4504 can_undock_node = true;
4505 }
4506
4507 const bool clicked = IsMouseClicked(0);
4508 const bool dragging = IsMouseDragging(0);
4509 if (can_undock_node && dragging)
4510 DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame
4511 else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window)
4512 StartMouseMovingWindow(window);
4513}
4514
4515// Handle mouse moving window
4516// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
4517// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
4518// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
4519// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
4520void ImGui::UpdateMouseMovingWindowNewFrame()
4521{
4522 ImGuiContext& g = *GImGui;
4523 if (g.MovingWindow != NULL)
4524 {
4525 // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
4526 // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
4527 KeepAliveID(g.ActiveId);
4528 IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree);
4529 ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree;
4530
4531 // When a window stop being submitted while being dragged, it may will its viewport until next Begin()
4532 const bool window_disappared = (!moving_window->WasActive && !moving_window->Active);
4533 if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos) && !window_disappared)
4534 {
4535 ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
4536 if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
4537 {
4538 SetWindowPos(moving_window, pos, ImGuiCond_Always);
4539 if (moving_window->Viewport && moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
4540 {
4541 moving_window->Viewport->Pos = pos;
4542 moving_window->Viewport->UpdateWorkRect();
4543 }
4544 }
4545 FocusWindow(g.MovingWindow);
4546 }
4547 else
4548 {
4549 if (!window_disappared)
4550 {
4551 // Try to merge the window back into the main viewport.
4552 // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
4553 if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
4554 UpdateTryMergeWindowIntoHostViewport(moving_window, g.MouseViewport);
4555
4556 // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
4557 if (moving_window->Viewport && !IsDragDropPayloadBeingAccepted())
4558 g.MouseViewport = moving_window->Viewport;
4559
4560 // Clear the NoInput window flag set by the Viewport system
4561 if (moving_window->Viewport)
4562 moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs;
4563 }
4564
4565 g.MovingWindow = NULL;
4566 ClearActiveID();
4567 }
4568 }
4569 else
4570 {
4571 // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
4572 if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
4573 {
4574 KeepAliveID(g.ActiveId);
4575 if (!g.IO.MouseDown[0])
4576 ClearActiveID();
4577 }
4578 }
4579}
4580
4581// Initiate moving window when clicking on empty space or title bar.
4582// Handle left-click and right-click focus.
4583void ImGui::UpdateMouseMovingWindowEndFrame()
4584{
4585 ImGuiContext& g = *GImGui;
4586 if (g.ActiveId != 0 || g.HoveredId != 0)
4587 return;
4588
4589 // Unless we just made a window/popup appear
4590 if (g.NavWindow && g.NavWindow->Appearing)
4591 return;
4592
4593 // Click on empty space to focus window and start moving
4594 // (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!)
4595 if (g.IO.MouseClicked[0])
4596 {
4597 // Handle the edge case of a popup being closed while clicking in its empty space.
4598 // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
4599 ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
4600 const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
4601
4602 if (root_window != NULL && !is_closed_popup)
4603 {
4604 StartMouseMovingWindow(g.HoveredWindow); //-V595
4605
4606 // Cancel moving if clicked outside of title bar
4607 if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
4608 if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
4609 if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
4610 g.MovingWindow = NULL;
4611
4612 // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
4613 if (g.HoveredIdDisabled)
4614 g.MovingWindow = NULL;
4615 }
4616 else if (root_window == NULL && g.NavWindow != NULL)
4617 {
4618 // Clicking on void disable focus
4619 FocusWindow(NULL, ImGuiFocusRequestFlags_UnlessBelowModal);
4620 }
4621 }
4622
4623 // With right mouse button we close popups without changing focus based on where the mouse is aimed
4624 // Instead, focus will be restored to the window under the bottom-most closed popup.
4625 // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
4626 if (g.IO.MouseClicked[1])
4627 {
4628 // Find the top-most window between HoveredWindow and the top-most Modal Window.
4629 // This is where we can trim the popup stack.
4630 ImGuiWindow* modal = GetTopMostPopupModal();
4631 bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(g.HoveredWindow, modal));
4632 ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
4633 }
4634}
4635
4636// This is called during NewFrame()->UpdateViewportsNewFrame() only.
4637// Need to keep in sync with SetWindowPos()
4638static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
4639{
4640 window->Pos += delta;
4641 window->ClipRect.Translate(delta);
4642 window->OuterRectClipped.Translate(delta);
4643 window->InnerRect.Translate(delta);
4644 window->DC.CursorPos += delta;
4645 window->DC.CursorStartPos += delta;
4646 window->DC.CursorMaxPos += delta;
4647 window->DC.IdealMaxPos += delta;
4648}
4649
4650static void ScaleWindow(ImGuiWindow* window, float scale)
4651{
4652 ImVec2 origin = window->Viewport->Pos;
4653 window->Pos = ImFloor((window->Pos - origin) * scale + origin);
4654 window->Size = ImTrunc(window->Size * scale);
4655 window->SizeFull = ImTrunc(window->SizeFull * scale);
4656 window->ContentSize = ImTrunc(window->ContentSize * scale);
4657}
4658
4659static bool IsWindowActiveAndVisible(ImGuiWindow* window)
4660{
4661 return (window->Active) && (!window->Hidden);
4662}
4663
4664// 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)
4665void ImGui::UpdateHoveredWindowAndCaptureFlags()
4666{
4667 ImGuiContext& g = *GImGui;
4668 ImGuiIO& io = g.IO;
4669 g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
4670
4671 // Find the window hovered by mouse:
4672 // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
4673 // - 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.
4674 // - 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.
4675 bool clear_hovered_windows = false;
4676 FindHoveredWindow();
4677 IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
4678
4679 // Modal windows prevents mouse from hovering behind them.
4680 ImGuiWindow* modal_window = GetTopMostPopupModal();
4681 if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window)) // FIXME-MERGE: RootWindowDockTree ?
4682 clear_hovered_windows = true;
4683
4684 // Disabled mouse?
4685 if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
4686 clear_hovered_windows = true;
4687
4688 // We track click ownership. When clicked outside of a window the click is owned by the application and
4689 // won't report hovering nor request capture even while dragging over our windows afterward.
4690 const bool has_open_popup = (g.OpenPopupStack.Size > 0);
4691 const bool has_open_modal = (modal_window != NULL);
4692 int mouse_earliest_down = -1;
4693 bool mouse_any_down = false;
4694 for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
4695 {
4696 if (io.MouseClicked[i])
4697 {
4698 io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
4699 io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
4700 }
4701 mouse_any_down |= io.MouseDown[i];
4702 if (io.MouseDown[i])
4703 if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
4704 mouse_earliest_down = i;
4705 }
4706 const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
4707 const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
4708
4709 // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
4710 // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
4711 const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
4712 if (!mouse_avail && !mouse_dragging_extern_payload)
4713 clear_hovered_windows = true;
4714
4715 if (clear_hovered_windows)
4716 g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4717
4718 // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
4719 // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
4720 if (g.WantCaptureMouseNextFrame != -1)
4721 {
4722 io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
4723 }
4724 else
4725 {
4726 io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
4727 io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
4728 }
4729
4730 // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
4731 io.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
4732 if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
4733 io.WantCaptureKeyboard = true;
4734 if (g.WantCaptureKeyboardNextFrame != -1) // Manual override
4735 io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
4736
4737 // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
4738 io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
4739}
4740
4741void ImGui::NewFrame()
4742{
4743 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4744 ImGuiContext& g = *GImGui;
4745
4746 // Remove pending delete hooks before frame start.
4747 // This deferred removal avoid issues of removal while iterating the hook vector
4748 for (int n = g.Hooks.Size - 1; n >= 0; n--)
4749 if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
4750 g.Hooks.erase(&g.Hooks[n]);
4751
4752 CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
4753
4754 // Check and assert for various common IO and Configuration mistakes
4755 g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame;
4756 ErrorCheckNewFrameSanityChecks();
4757 g.ConfigFlagsCurrFrame = g.IO.ConfigFlags;
4758
4759 // Load settings on first frame, save settings when modified (after a delay)
4760 UpdateSettings();
4761
4762 g.Time += g.IO.DeltaTime;
4763 g.WithinFrameScope = true;
4764 g.FrameCount += 1;
4765 g.TooltipOverrideCount = 0;
4766 g.WindowsActiveCount = 0;
4767 g.MenusIdSubmittedThisFrame.resize(0);
4768
4769 // Calculate frame-rate for the user, as a purely luxurious feature
4770 g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
4771 g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
4772 g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
4773 g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
4774 g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
4775
4776 // Process input queue (trickle as many events as possible), turn events into writes to IO structure
4777 g.InputEventsTrail.resize(0);
4778 UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue);
4779
4780 // Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
4781 UpdateViewportsNewFrame();
4782
4783 // Setup current font and draw list shared data
4784 // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
4785 g.IO.Fonts->Locked = true;
4786 SetCurrentFont(GetDefaultFont());
4787 IM_ASSERT(g.Font->IsLoaded());
4788 ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
4789 for (ImGuiViewportP* viewport : g.Viewports)
4790 virtual_space.Add(viewport->GetMainRect());
4791 g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
4792 g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
4793 g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
4794 g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
4795 if (g.Style.AntiAliasedLines)
4796 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
4797 if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines))
4798 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
4799 if (g.Style.AntiAliasedFill)
4800 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
4801 if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
4802 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
4803
4804 // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
4805 for (ImGuiViewportP* viewport : g.Viewports)
4806 {
4807 viewport->DrawData = NULL;
4808 viewport->DrawDataP.Valid = false;
4809 }
4810
4811 // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
4812 if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
4813 KeepAliveID(g.DragDropPayload.SourceId);
4814
4815 // Update HoveredId data
4816 if (!g.HoveredIdPreviousFrame)
4817 g.HoveredIdTimer = 0.0f;
4818 if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
4819 g.HoveredIdNotActiveTimer = 0.0f;
4820 if (g.HoveredId)
4821 g.HoveredIdTimer += g.IO.DeltaTime;
4822 if (g.HoveredId && g.ActiveId != g.HoveredId)
4823 g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
4824 g.HoveredIdPreviousFrame = g.HoveredId;
4825 g.HoveredId = 0;
4826 g.HoveredIdAllowOverlap = false;
4827 g.HoveredIdDisabled = false;
4828
4829 // Clear ActiveID if the item is not alive anymore.
4830 // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
4831 // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
4832 if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
4833 {
4834 IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n");
4835 ClearActiveID();
4836 }
4837
4838 // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
4839 if (g.ActiveId)
4840 g.ActiveIdTimer += g.IO.DeltaTime;
4841 g.LastActiveIdTimer += g.IO.DeltaTime;
4842 g.ActiveIdPreviousFrame = g.ActiveId;
4843 g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
4844 g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
4845 g.ActiveIdIsAlive = 0;
4846 g.ActiveIdHasBeenEditedThisFrame = false;
4847 g.ActiveIdPreviousFrameIsAlive = false;
4848 g.ActiveIdIsJustActivated = false;
4849 if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
4850 g.TempInputId = 0;
4851 if (g.ActiveId == 0)
4852 {
4853 g.ActiveIdUsingNavDirMask = 0x00;
4854 g.ActiveIdUsingAllKeyboardKeys = false;
4855#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4856 g.ActiveIdUsingNavInputMask = 0x00;
4857#endif
4858 }
4859
4860#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4861 if (g.ActiveId == 0)
4862 g.ActiveIdUsingNavInputMask = 0;
4863 else if (g.ActiveIdUsingNavInputMask != 0)
4864 {
4865 // If your custom widget code used: { g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel); }
4866 // Since IMGUI_VERSION_NUM >= 18804 it should be: { SetKeyOwner(ImGuiKey_Escape, g.ActiveId); SetKeyOwner(ImGuiKey_NavGamepadCancel, g.ActiveId); }
4867 if (g.ActiveIdUsingNavInputMask & (1 << ImGuiNavInput_Cancel))
4868 SetKeyOwner(ImGuiKey_Escape, g.ActiveId);
4869 if (g.ActiveIdUsingNavInputMask & ~(1 << ImGuiNavInput_Cancel))
4870 IM_ASSERT(0); // Other values unsupported
4871 }
4872#endif
4873
4874 // Record when we have been stationary as this state is preserved while over same item.
4875 // FIXME: The way this is expressed means user cannot alter HoverStationaryDelay during the frame to use varying values.
4876 // To allow this we should store HoverItemMaxStationaryTime+ID and perform the >= check in IsItemHovered() function.
4877 if (g.HoverItemDelayId != 0 && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
4878 g.HoverItemUnlockedStationaryId = g.HoverItemDelayId;
4879 else if (g.HoverItemDelayId == 0)
4880 g.HoverItemUnlockedStationaryId = 0;
4881 if (g.HoveredWindow != NULL && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
4882 g.HoverWindowUnlockedStationaryId = g.HoveredWindow->ID;
4883 else if (g.HoveredWindow == NULL)
4884 g.HoverWindowUnlockedStationaryId = 0;
4885
4886 // Update hover delay for IsItemHovered() with delays and tooltips
4887 g.HoverItemDelayIdPreviousFrame = g.HoverItemDelayId;
4888 if (g.HoverItemDelayId != 0)
4889 {
4890 g.HoverItemDelayTimer += g.IO.DeltaTime;
4891 g.HoverItemDelayClearTimer = 0.0f;
4892 g.HoverItemDelayId = 0;
4893 }
4894 else if (g.HoverItemDelayTimer > 0.0f)
4895 {
4896 // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
4897 // We could expose 0.25f as style.HoverClearDelay but I am not sure of the logic yet, this is particularly subtle.
4898 g.HoverItemDelayClearTimer += g.IO.DeltaTime;
4899 if (g.HoverItemDelayClearTimer >= ImMax(0.25f, g.IO.DeltaTime * 2.0f)) // ~7 frames at 30 Hz + allow for low framerate
4900 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.
4901 }
4902
4903 // Drag and drop
4904 g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
4905 g.DragDropAcceptIdCurr = 0;
4906 g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
4907 g.DragDropWithinSource = false;
4908 g.DragDropWithinTarget = false;
4909 g.DragDropHoldJustPressedId = 0;
4910
4911 // Close popups on focus lost (currently wip/opt-in)
4912 //if (g.IO.AppFocusLost)
4913 // ClosePopupsExceptModals();
4914
4915 // Update keyboard input state
4916 UpdateKeyboardInputs();
4917
4918 //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
4919 //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
4920 //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
4921 //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
4922
4923 // Update gamepad/keyboard navigation
4924 NavUpdate();
4925
4926 // Update mouse input state
4927 UpdateMouseInputs();
4928
4929 // Undocking
4930 // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
4931 DockContextNewFrameUpdateUndocking(&g);
4932
4933 // Find hovered window
4934 // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
4935 UpdateHoveredWindowAndCaptureFlags();
4936
4937 // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
4938 UpdateMouseMovingWindowNewFrame();
4939
4940 // Background darkening/whitening
4941 if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
4942 g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
4943 else
4944 g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
4945
4946 g.MouseCursor = ImGuiMouseCursor_Arrow;
4947 g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
4948
4949 // Platform IME data: reset for the frame
4950 g.PlatformImeDataPrev = g.PlatformImeData;
4951 g.PlatformImeData.WantVisible = false;
4952
4953 // Mouse wheel scrolling, scale
4954 UpdateMouseWheel();
4955
4956 // Mark all windows as not visible and compact unused memory.
4957 IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
4958 const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
4959 for (ImGuiWindow* window : g.Windows)
4960 {
4961 window->WasActive = window->Active;
4962 window->Active = false;
4963 window->WriteAccessed = false;
4964 window->BeginCountPreviousFrame = window->BeginCount;
4965 window->BeginCount = 0;
4966
4967 // Garbage collect transient buffers of recently unused windows
4968 if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
4969 GcCompactTransientWindowBuffers(window);
4970 }
4971
4972 // Garbage collect transient buffers of recently unused tables
4973 for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
4974 if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
4975 TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
4976 for (ImGuiTableTempData& table_temp_data : g.TablesTempData)
4977 if (table_temp_data.LastTimeActive >= 0.0f && table_temp_data.LastTimeActive < memory_compact_start_time)
4978 TableGcCompactTransientBuffers(&table_temp_data);
4979 if (g.GcCompactAll)
4980 GcCompactTransientMiscBuffers();
4981 g.GcCompactAll = false;
4982
4983 // Closing the focused window restore focus to the first active root window in descending z-order
4984 if (g.NavWindow && !g.NavWindow->WasActive)
4985 FocusTopMostWindowUnderOne(NULL, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild);
4986
4987 // No window should be open at the beginning of the frame.
4988 // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
4989 g.CurrentWindowStack.resize(0);
4990 g.BeginPopupStack.resize(0);
4991 g.ItemFlagsStack.resize(0);
4992 g.ItemFlagsStack.push_back(ImGuiItemFlags_None);
4993 g.GroupStack.resize(0);
4994
4995 // Docking
4996 DockContextNewFrameUpdateDocking(&g);
4997
4998 // [DEBUG] Update debug features
4999#ifndef IMGUI_DISABLE_DEBUG_TOOLS
5000 UpdateDebugToolItemPicker();
5001 UpdateDebugToolStackQueries();
5002 UpdateDebugToolFlashStyleColor();
5003 if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0)
5004 {
5005 g.DebugLocateId = 0;
5006 g.DebugBreakInLocateId = false;
5007 }
5008 if (g.DebugLogAutoDisableFrames > 0 && --g.DebugLogAutoDisableFrames == 0)
5009 {
5010 DebugLog("(Debug Log: Auto-disabled some ImGuiDebugLogFlags after 2 frames)\n");
5011 g.DebugLogFlags &= ~g.DebugLogAutoDisableFlags;
5012 g.DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None;
5013 }
5014#endif
5015
5016 // Create implicit/fallback window - which we will only render it if the user has added something to it.
5017 // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
5018 // This fallback is particularly important as it prevents ImGui:: calls from crashing.
5019 g.WithinFrameScopeWithImplicitWindow = true;
5020 SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
5021 Begin("Debug##Default");
5022 IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
5023
5024 // [DEBUG] When io.ConfigDebugBeginReturnValue is set, we make Begin()/BeginChild() return false at different level of the window-stack,
5025 // allowing to validate correct Begin/End behavior in user code.
5026#ifndef IMGUI_DISABLE_DEBUG_TOOLS
5027 if (g.IO.ConfigDebugBeginReturnValueLoop)
5028 g.DebugBeginReturnValueCullDepth = (g.DebugBeginReturnValueCullDepth == -1) ? 0 : ((g.DebugBeginReturnValueCullDepth + ((g.FrameCount % 4) == 0 ? 1 : 0)) % 10);
5029 else
5030 g.DebugBeginReturnValueCullDepth = -1;
5031#endif
5032
5033 CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
5034}
5035
5036// FIXME: Add a more explicit sort order in the window structure.
5037static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
5038{
5039 const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
5040 const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
5041 if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
5042 return d;
5043 if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
5044 return d;
5045 return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
5046}
5047
5048static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
5049{
5050 out_sorted_windows->push_back(window);
5051 if (window->Active)
5052 {
5053 int count = window->DC.ChildWindows.Size;
5054 ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
5055 for (int i = 0; i < count; i++)
5056 {
5057 ImGuiWindow* child = window->DC.ChildWindows[i];
5058 if (child->Active)
5059 AddWindowToSortBuffer(out_sorted_windows, child);
5060 }
5061 }
5062}
5063
5064static void AddWindowToDrawData(ImGuiWindow* window, int layer)
5065{
5066 ImGuiContext& g = *GImGui;
5067 ImGuiViewportP* viewport = window->Viewport;
5068 IM_ASSERT(viewport != NULL);
5069 g.IO.MetricsRenderWindows++;
5070 if (window->DrawList->_Splitter._Count > 1)
5071 window->DrawList->ChannelsMerge(); // Merge if user forgot to merge back. Also required in Docking branch for ImGuiWindowFlags_DockNodeHost windows.
5072 ImGui::AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[layer], window->DrawList);
5073 for (ImGuiWindow* child : window->DC.ChildWindows)
5074 if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
5075 AddWindowToDrawData(child, layer);
5076}
5077
5078static inline int GetWindowDisplayLayer(ImGuiWindow* window)
5079{
5080 return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
5081}
5082
5083// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
5084static inline void AddRootWindowToDrawData(ImGuiWindow* window)
5085{
5086 AddWindowToDrawData(window, GetWindowDisplayLayer(window));
5087}
5088
5089static void FlattenDrawDataIntoSingleLayer(ImDrawDataBuilder* builder)
5090{
5091 int n = builder->Layers[0]->Size;
5092 int full_size = n;
5093 for (int i = 1; i < IM_ARRAYSIZE(builder->Layers); i++)
5094 full_size += builder->Layers[i]->Size;
5095 builder->Layers[0]->resize(full_size);
5096 for (int layer_n = 1; layer_n < IM_ARRAYSIZE(builder->Layers); layer_n++)
5097 {
5098 ImVector<ImDrawList*>* layer = builder->Layers[layer_n];
5099 if (layer->empty())
5100 continue;
5101 memcpy(builder->Layers[0]->Data + n, layer->Data, layer->Size * sizeof(ImDrawList*));
5102 n += layer->Size;
5103 layer->resize(0);
5104 }
5105}
5106
5107static void InitViewportDrawData(ImGuiViewportP* viewport)
5108{
5109 ImGuiIO& io = ImGui::GetIO();
5110 ImDrawData* draw_data = &viewport->DrawDataP;
5111
5112 viewport->DrawData = draw_data; // Make publicly accessible
5113 viewport->DrawDataBuilder.Layers[0] = &draw_data->CmdLists;
5114 viewport->DrawDataBuilder.Layers[1] = &viewport->DrawDataBuilder.LayerData1;
5115 viewport->DrawDataBuilder.Layers[0]->resize(0);
5116 viewport->DrawDataBuilder.Layers[1]->resize(0);
5117
5118 // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode,
5119 // and to allow applications/backends to easily skip rendering.
5120 // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure.
5121 // This is because the work has been done already, and its wasted! We should fix that and add optimizations for
5122 // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline.
5123 const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0;
5124
5125 draw_data->Valid = true;
5126 draw_data->CmdListsCount = 0;
5127 draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
5128 draw_data->DisplayPos = viewport->Pos;
5129 draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size;
5130 draw_data->FramebufferScale = io.DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis?
5131 draw_data->OwnerViewport = viewport;
5132}
5133
5134// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
5135// - When using this function it is sane to ensure that float are perfectly rounded to integer values,
5136// so that e.g. (int)(max.x-min.x) in user's render produce correct result.
5137// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
5138// some frequently called functions which to modify both channels and clipping simultaneously tend to use the
5139// more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
5140void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
5141{
5142 ImGuiWindow* window = GetCurrentWindow();
5143 window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
5144 window->ClipRect = window->DrawList->_ClipRectStack.back();
5145}
5146
5147void ImGui::PopClipRect()
5148{
5149 ImGuiWindow* window = GetCurrentWindow();
5150 window->DrawList->PopClipRect();
5151 window->ClipRect = window->DrawList->_ClipRectStack.back();
5152}
5153
5154static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
5155{
5156 for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
5157 if (IsWindowActiveAndVisible(window->DC.ChildWindows[n]))
5158 return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]);
5159 return window;
5160}
5161
5162static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
5163{
5164 if ((col & IM_COL32_A_MASK) == 0)
5165 return;
5166
5167 ImGuiViewportP* viewport = window->Viewport;
5168 ImRect viewport_rect = viewport->GetMainRect();
5169
5170 // Draw behind window by moving the draw command at the FRONT of the draw list
5171 {
5172 // Draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
5173 // 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.
5174 ImDrawList* draw_list = window->RootWindowDockTree->DrawList;
5175 draw_list->ChannelsMerge();
5176 if (draw_list->CmdBuffer.Size == 0)
5177 draw_list->AddDrawCmd();
5178 draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // FIXME: Need to stricty ensure ImDrawCmd are not merged (ElemCount==6 checks below will verify that)
5179 draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col);
5180 ImDrawCmd cmd = draw_list->CmdBuffer.back();
5181 IM_ASSERT(cmd.ElemCount == 6);
5182 draw_list->CmdBuffer.pop_back();
5183 draw_list->CmdBuffer.push_front(cmd);
5184 draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
5185 draw_list->PopClipRect();
5186 }
5187
5188 // Draw over sibling docking nodes in a same docking tree
5189 if (window->RootWindow->DockIsActive)
5190 {
5191 ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindowDockTree)->DrawList;
5192 draw_list->ChannelsMerge();
5193 if (draw_list->CmdBuffer.Size == 0)
5194 draw_list->AddDrawCmd();
5195 draw_list->PushClipRect(viewport_rect.Min, viewport_rect.Max, false);
5196 RenderRectFilledWithHole(draw_list, window->RootWindowDockTree->Rect(), window->RootWindow->Rect(), col, 0.0f);// window->RootWindowDockTree->WindowRounding);
5197 draw_list->PopClipRect();
5198 }
5199}
5200
5201ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
5202{
5203 ImGuiContext& g = *GImGui;
5204 ImGuiWindow* bottom_most_visible_window = parent_window;
5205 for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--)
5206 {
5207 ImGuiWindow* window = g.Windows[i];
5208 if (window->Flags & ImGuiWindowFlags_ChildWindow)
5209 continue;
5210 if (!IsWindowWithinBeginStackOf(window, parent_window))
5211 break;
5212 if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window))
5213 bottom_most_visible_window = window;
5214 }
5215 return bottom_most_visible_window;
5216}
5217
5218// Important: AddWindowToDrawData() has not been called yet, meaning DockNodeHost windows needs a DrawList->ChannelsMerge() before usage.
5219// We call ChannelsMerge() lazily here at it is faster that doing a full iteration of g.Windows[] prior to calling RenderDimmedBackgrounds().
5220static void ImGui::RenderDimmedBackgrounds()
5221{
5222 ImGuiContext& g = *GImGui;
5223 ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
5224 if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
5225 return;
5226 const bool dim_bg_for_modal = (modal_window != NULL);
5227 const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
5228 if (!dim_bg_for_modal && !dim_bg_for_window_list)
5229 return;
5230
5231 ImGuiViewport* viewports_already_dimmed[2] = { NULL, NULL };
5232 if (dim_bg_for_modal)
5233 {
5234 // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
5235 ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window);
5236 RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(modal_window->DC.ModalDimBgColor, g.DimBgRatio));
5237 viewports_already_dimmed[0] = modal_window->Viewport;
5238 }
5239 else if (dim_bg_for_window_list)
5240 {
5241 // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window
5242 RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5243 if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->Viewport && g.NavWindowingListWindow->Viewport != g.NavWindowingTargetAnim->Viewport)
5244 RenderDimmedBackgroundBehindWindow(g.NavWindowingListWindow, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5245 viewports_already_dimmed[0] = g.NavWindowingTargetAnim->Viewport;
5246 viewports_already_dimmed[1] = g.NavWindowingListWindow ? g.NavWindowingListWindow->Viewport : NULL;
5247
5248 // Draw border around CTRL+Tab target window
5249 ImGuiWindow* window = g.NavWindowingTargetAnim;
5250 ImGuiViewport* viewport = window->Viewport;
5251 float distance = g.FontSize;
5252 ImRect bb = window->Rect();
5253 bb.Expand(distance);
5254 if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
5255 bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
5256 window->DrawList->ChannelsMerge();
5257 if (window->DrawList->CmdBuffer.Size == 0)
5258 window->DrawList->AddDrawCmd();
5259 window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size);
5260 window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f);
5261 window->DrawList->PopClipRect();
5262 }
5263
5264 // Draw dimming background on _other_ viewports than the ones our windows are in
5265 for (ImGuiViewportP* viewport : g.Viewports)
5266 {
5267 if (viewport == viewports_already_dimmed[0] || viewport == viewports_already_dimmed[1])
5268 continue;
5269 if (modal_window && viewport->Window && IsWindowAbove(viewport->Window, modal_window))
5270 continue;
5271 ImDrawList* draw_list = GetForegroundDrawList(viewport);
5272 const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
5273 draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col);
5274 }
5275}
5276
5277// 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.
5278void ImGui::EndFrame()
5279{
5280 ImGuiContext& g = *GImGui;
5281 IM_ASSERT(g.Initialized);
5282
5283 // Don't process EndFrame() multiple times.
5284 if (g.FrameCountEnded == g.FrameCount)
5285 return;
5286 IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
5287
5288 CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
5289
5290 ErrorCheckEndFrameSanityChecks();
5291
5292 // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
5293 ImGuiPlatformImeData* ime_data = &g.PlatformImeData;
5294 if (g.IO.SetPlatformImeDataFn && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0)
5295 {
5296 ImGuiViewport* viewport = FindViewportByID(g.PlatformImeViewport);
5297 IMGUI_DEBUG_LOG_IO("[io] Calling io.SetPlatformImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y);
5298 if (viewport == NULL)
5299 viewport = GetMainViewport();
5300 g.IO.SetPlatformImeDataFn(viewport, ime_data);
5301 }
5302
5303 // Hide implicit/fallback "Debug" window if it hasn't been used
5304 g.WithinFrameScopeWithImplicitWindow = false;
5305 if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
5306 g.CurrentWindow->Active = false;
5307 End();
5308
5309 // Update navigation: CTRL+Tab, wrap-around requests
5310 NavEndFrame();
5311
5312 // Update docking
5313 DockContextEndFrame(&g);
5314
5315 SetCurrentViewport(NULL, NULL);
5316
5317 // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
5318 if (g.DragDropActive)
5319 {
5320 bool is_delivered = g.DragDropPayload.Delivery;
5321 bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));
5322 if (is_delivered || is_elapsed)
5323 ClearDragDrop();
5324 }
5325
5326 // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
5327 if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
5328 {
5329 g.DragDropWithinSource = true;
5330 SetTooltip("...");
5331 g.DragDropWithinSource = false;
5332 }
5333
5334 // End frame
5335 g.WithinFrameScope = false;
5336 g.FrameCountEnded = g.FrameCount;
5337
5338 // Initiate moving window + handle left-click and right-click focus
5339 UpdateMouseMovingWindowEndFrame();
5340
5341 // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
5342 UpdateViewportsEndFrame();
5343
5344 // Sort the window list so that all child windows are after their parent
5345 // We cannot do that on FocusWindow() because children may not exist yet
5346 g.WindowsTempSortBuffer.resize(0);
5347 g.WindowsTempSortBuffer.reserve(g.Windows.Size);
5348 for (ImGuiWindow* window : g.Windows)
5349 {
5350 if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
5351 continue;
5352 AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
5353 }
5354
5355 // 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.
5356 IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
5357 g.Windows.swap(g.WindowsTempSortBuffer);
5358 g.IO.MetricsActiveWindows = g.WindowsActiveCount;
5359
5360 // Unlock font atlas
5361 g.IO.Fonts->Locked = false;
5362
5363 // Clear Input data for next frame
5364 g.IO.MousePosPrev = g.IO.MousePos;
5365 g.IO.AppFocusLost = false;
5366 g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
5367 g.IO.InputQueueCharacters.resize(0);
5368
5369 CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
5370}
5371
5372// Prepare the data for rendering so you can call GetDrawData()
5373// (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all:
5374// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
5375void ImGui::Render()
5376{
5377 ImGuiContext& g = *GImGui;
5378 IM_ASSERT(g.Initialized);
5379
5380 if (g.FrameCountEnded != g.FrameCount)
5381 EndFrame();
5382 if (g.FrameCountRendered == g.FrameCount)
5383 return;
5384 g.FrameCountRendered = g.FrameCount;
5385
5386 g.IO.MetricsRenderWindows = 0;
5387 CallContextHooks(&g, ImGuiContextHookType_RenderPre);
5388
5389 // Add background ImDrawList (for each active viewport)
5390 for (ImGuiViewportP* viewport : g.Viewports)
5391 {
5392 InitViewportDrawData(viewport);
5393 if (viewport->BgFgDrawLists[0] != NULL)
5394 AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
5395 }
5396
5397 // Draw modal/window whitening backgrounds
5398 RenderDimmedBackgrounds();
5399
5400 // Add ImDrawList to render
5401 ImGuiWindow* windows_to_render_top_most[2];
5402 windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL;
5403 windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
5404 for (ImGuiWindow* window : g.Windows)
5405 {
5406 IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
5407 if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
5408 AddRootWindowToDrawData(window);
5409 }
5410 for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
5411 if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
5412 AddRootWindowToDrawData(windows_to_render_top_most[n]);
5413
5414 // Draw software mouse cursor if requested by io.MouseDrawCursor flag
5415 if (g.IO.MouseDrawCursor && g.MouseCursor != ImGuiMouseCursor_None)
5416 RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
5417
5418 // Setup ImDrawData structures for end-user
5419 g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
5420 for (ImGuiViewportP* viewport : g.Viewports)
5421 {
5422 FlattenDrawDataIntoSingleLayer(&viewport->DrawDataBuilder);
5423
5424 // Add foreground ImDrawList (for each active viewport)
5425 if (viewport->BgFgDrawLists[1] != NULL)
5426 AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
5427
5428 // We call _PopUnusedDrawCmd() last thing, as RenderDimmedBackgrounds() rely on a valid command being there (especially in docking branch).
5429 ImDrawData* draw_data = &viewport->DrawDataP;
5430 IM_ASSERT(draw_data->CmdLists.Size == draw_data->CmdListsCount);
5431 for (ImDrawList* draw_list : draw_data->CmdLists)
5432 draw_list->_PopUnusedDrawCmd();
5433
5434 g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
5435 g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
5436 }
5437
5438 CallContextHooks(&g, ImGuiContextHookType_RenderPost);
5439}
5440
5441// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
5442// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
5443ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
5444{
5445 ImGuiContext& g = *GImGui;
5446
5447 const char* text_display_end;
5448 if (hide_text_after_double_hash)
5449 text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string
5450 else
5451 text_display_end = text_end;
5452
5453 ImFont* font = g.Font;
5454 const float font_size = g.FontSize;
5455 if (text == text_display_end)
5456 return ImVec2(0.0f, font_size);
5457 ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
5458
5459 // Round
5460 // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
5461 // FIXME: Investigate using ceilf or e.g.
5462 // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
5463 // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
5464 text_size.x = IM_TRUNC(text_size.x + 0.99999f);
5465
5466 return text_size;
5467}
5468
5469// Find window given position, search front-to-back
5470// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
5471// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
5472// called, aka before the next Begin(). Moving window isn't affected.
5473static void FindHoveredWindow()
5474{
5475 ImGuiContext& g = *GImGui;
5476
5477 // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
5478 ImGuiViewportP* moving_window_viewport = g.MovingWindow ? g.MovingWindow->Viewport : NULL;
5479 if (g.MovingWindow)
5480 g.MovingWindow->Viewport = g.MouseViewport;
5481
5482 ImGuiWindow* hovered_window = NULL;
5483 ImGuiWindow* hovered_window_ignoring_moving_window = NULL;
5484 if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
5485 hovered_window = g.MovingWindow;
5486
5487 ImVec2 padding_regular = g.Style.TouchExtraPadding;
5488 ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;
5489 for (int i = g.Windows.Size - 1; i >= 0; i--)
5490 {
5491 ImGuiWindow* window = g.Windows[i];
5492 IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5493 if (!window->Active || window->Hidden)
5494 continue;
5495 if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
5496 continue;
5497 IM_ASSERT(window->Viewport);
5498 if (window->Viewport != g.MouseViewport)
5499 continue;
5500
5501 // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
5502 ImVec2 hit_padding = (window->Flags & (ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) ? padding_regular : padding_for_resize;
5503 if (!window->OuterRectClipped.ContainsWithPad(g.IO.MousePos, hit_padding))
5504 continue;
5505
5506 // Support for one rectangular hole in any given window
5507 // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
5508 if (window->HitTestHoleSize.x != 0)
5509 {
5510 ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
5511 ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
5512 if (ImRect(hole_pos, hole_pos + hole_size).Contains(g.IO.MousePos))
5513 continue;
5514 }
5515
5516 if (hovered_window == NULL)
5517 hovered_window = window;
5518 IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5519 if (hovered_window_ignoring_moving_window == NULL && (!g.MovingWindow || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree))
5520 hovered_window_ignoring_moving_window = window;
5521 if (hovered_window && hovered_window_ignoring_moving_window)
5522 break;
5523 }
5524
5525 g.HoveredWindow = hovered_window;
5526 g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window;
5527
5528 if (g.MovingWindow)
5529 g.MovingWindow->Viewport = moving_window_viewport;
5530}
5531
5532bool ImGui::IsItemActive()
5533{
5534 ImGuiContext& g = *GImGui;
5535 if (g.ActiveId)
5536 return g.ActiveId == g.LastItemData.ID;
5537 return false;
5538}
5539
5540bool ImGui::IsItemActivated()
5541{
5542 ImGuiContext& g = *GImGui;
5543 if (g.ActiveId)
5544 if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
5545 return true;
5546 return false;
5547}
5548
5549bool ImGui::IsItemDeactivated()
5550{
5551 ImGuiContext& g = *GImGui;
5552 if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
5553 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
5554 return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID);
5555}
5556
5557bool ImGui::IsItemDeactivatedAfterEdit()
5558{
5559 ImGuiContext& g = *GImGui;
5560 return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
5561}
5562
5563// == GetItemID() == GetFocusID()
5564bool ImGui::IsItemFocused()
5565{
5566 ImGuiContext& g = *GImGui;
5567 if (g.NavId != g.LastItemData.ID || g.NavId == 0)
5568 return false;
5569
5570 // Special handling for the dummy item after Begin() which represent the title bar or tab.
5571 // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
5572 ImGuiWindow* window = g.CurrentWindow;
5573 if (g.LastItemData.ID == window->ID && window->WriteAccessed)
5574 return false;
5575
5576 return true;
5577}
5578
5579// Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
5580// Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
5581bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
5582{
5583 return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
5584}
5585
5586bool ImGui::IsItemToggledOpen()
5587{
5588 ImGuiContext& g = *GImGui;
5589 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
5590}
5591
5592bool ImGui::IsItemToggledSelection()
5593{
5594 ImGuiContext& g = *GImGui;
5595 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
5596}
5597
5598// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
5599// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
5600// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
5601bool ImGui::IsAnyItemHovered()
5602{
5603 ImGuiContext& g = *GImGui;
5604 return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
5605}
5606
5607bool ImGui::IsAnyItemActive()
5608{
5609 ImGuiContext& g = *GImGui;
5610 return g.ActiveId != 0;
5611}
5612
5613bool ImGui::IsAnyItemFocused()
5614{
5615 ImGuiContext& g = *GImGui;
5616 return g.NavId != 0 && !g.NavDisableHighlight;
5617}
5618
5619bool ImGui::IsItemVisible()
5620{
5621 ImGuiContext& g = *GImGui;
5622 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0;
5623}
5624
5625bool ImGui::IsItemEdited()
5626{
5627 ImGuiContext& g = *GImGui;
5628 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
5629}
5630
5631// Allow next item to be overlapped by subsequent items.
5632// This works by requiring HoveredId to match for two subsequent frames,
5633// so if a following items overwrite it our interactions will naturally be disabled.
5634void ImGui::SetNextItemAllowOverlap()
5635{
5636 ImGuiContext& g = *GImGui;
5637 g.NextItemData.ItemFlags |= ImGuiItemFlags_AllowOverlap;
5638}
5639
5640#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5641// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
5642// FIXME-LEGACY: Use SetNextItemAllowOverlap() *before* your item instead.
5643void ImGui::SetItemAllowOverlap()
5644{
5645 ImGuiContext& g = *GImGui;
5646 ImGuiID id = g.LastItemData.ID;
5647 if (g.HoveredId == id)
5648 g.HoveredIdAllowOverlap = true;
5649 if (g.ActiveId == id) // Before we made this obsolete, most calls to SetItemAllowOverlap() used to avoid this path by testing g.ActiveId != id.
5650 g.ActiveIdAllowOverlap = true;
5651}
5652#endif
5653
5654// FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version for the two users of this function.
5655void ImGui::SetActiveIdUsingAllKeyboardKeys()
5656{
5657 ImGuiContext& g = *GImGui;
5658 IM_ASSERT(g.ActiveId != 0);
5659 g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1;
5660 g.ActiveIdUsingAllKeyboardKeys = true;
5661 NavMoveRequestCancel();
5662}
5663
5664ImGuiID ImGui::GetItemID()
5665{
5666 ImGuiContext& g = *GImGui;
5667 return g.LastItemData.ID;
5668}
5669
5670ImVec2 ImGui::GetItemRectMin()
5671{
5672 ImGuiContext& g = *GImGui;
5673 return g.LastItemData.Rect.Min;
5674}
5675
5676ImVec2 ImGui::GetItemRectMax()
5677{
5678 ImGuiContext& g = *GImGui;
5679 return g.LastItemData.Rect.Max;
5680}
5681
5682ImVec2 ImGui::GetItemRectSize()
5683{
5684 ImGuiContext& g = *GImGui;
5685 return g.LastItemData.Rect.GetSize();
5686}
5687
5688// Prior to v1.90 2023/10/16, the BeginChild() function took a 'bool border = false' parameter instead of 'ImGuiChildFlags child_flags = 0'.
5689// ImGuiChildFlags_Border is defined as always == 1 in order to allow old code passing 'true'. Read comments in imgui.h for details!
5690bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5691{
5692 ImGuiID id = GetCurrentWindow()->GetID(str_id);
5693 return BeginChildEx(str_id, id, size_arg, child_flags, window_flags);
5694}
5695
5696bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5697{
5698 return BeginChildEx(NULL, id, size_arg, child_flags, window_flags);
5699}
5700
5701bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5702{
5703 ImGuiContext& g = *GImGui;
5704 ImGuiWindow* parent_window = g.CurrentWindow;
5705 IM_ASSERT(id != 0);
5706
5707 // Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument.
5708 const ImGuiChildFlags ImGuiChildFlags_SupportedMask_ = ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize | ImGuiChildFlags_FrameStyle;
5709 IM_UNUSED(ImGuiChildFlags_SupportedMask_);
5710 IM_ASSERT((child_flags & ~ImGuiChildFlags_SupportedMask_) == 0 && "Illegal ImGuiChildFlags value. Did you pass ImGuiWindowFlags values instead of ImGuiChildFlags?");
5711 IM_ASSERT((window_flags & ImGuiWindowFlags_AlwaysAutoResize) == 0 && "Cannot specify ImGuiWindowFlags_AlwaysAutoResize for BeginChild(). Use ImGuiChildFlags_AlwaysAutoResize!");
5712 if (child_flags & ImGuiChildFlags_AlwaysAutoResize)
5713 {
5714 IM_ASSERT((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0 && "Cannot use ImGuiChildFlags_ResizeX or ImGuiChildFlags_ResizeY with ImGuiChildFlags_AlwaysAutoResize!");
5715 IM_ASSERT((child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY)) != 0 && "Must use ImGuiChildFlags_AutoResizeX or ImGuiChildFlags_AutoResizeY with ImGuiChildFlags_AlwaysAutoResize!");
5716 }
5717#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5718 if (window_flags & ImGuiWindowFlags_AlwaysUseWindowPadding)
5719 child_flags |= ImGuiChildFlags_AlwaysUseWindowPadding;
5720#endif
5721 if (child_flags & ImGuiChildFlags_AutoResizeX)
5722 child_flags &= ~ImGuiChildFlags_ResizeX;
5723 if (child_flags & ImGuiChildFlags_AutoResizeY)
5724 child_flags &= ~ImGuiChildFlags_ResizeY;
5725
5726 // Set window flags
5727 window_flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking;
5728 window_flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
5729 if (child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize))
5730 window_flags |= ImGuiWindowFlags_AlwaysAutoResize;
5731 if ((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0)
5732 window_flags |= ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings;
5733
5734 // Special framed style
5735 if (child_flags & ImGuiChildFlags_FrameStyle)
5736 {
5737 PushStyleColor(ImGuiCol_ChildBg, g.Style.Colors[ImGuiCol_FrameBg]);
5738 PushStyleVar(ImGuiStyleVar_ChildRounding, g.Style.FrameRounding);
5739 PushStyleVar(ImGuiStyleVar_ChildBorderSize, g.Style.FrameBorderSize);
5740 PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.FramePadding);
5741 child_flags |= ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding;
5742 window_flags |= ImGuiWindowFlags_NoMove;
5743 }
5744
5745 // Forward child flags
5746 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasChildFlags;
5747 g.NextWindowData.ChildFlags = child_flags;
5748
5749 // Forward size
5750 // Important: Begin() has special processing to switch condition to ImGuiCond_FirstUseEver for a given axis when ImGuiChildFlags_ResizeXXX is set.
5751 // (the alternative would to store conditional flags per axis, which is possible but more code)
5752 const ImVec2 size_avail = GetContentRegionAvail();
5753 const ImVec2 size_default((child_flags & ImGuiChildFlags_AutoResizeX) ? 0.0f : size_avail.x, (child_flags & ImGuiChildFlags_AutoResizeY) ? 0.0f : size_avail.y);
5754 const ImVec2 size = CalcItemSize(size_arg, size_default.x, size_default.y);
5755 SetNextWindowSize(size);
5756
5757 // 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.
5758 // 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.
5759 // e.g. "ParentName###ParentIdentifier/ChildName###ChildIdentifier" would get hashed incorrectly by ImHashStr(), trailing _%08X somehow fixes it.
5760 const char* temp_window_name;
5761 /*if (name && parent_window->IDStack.back() == parent_window->ID)
5762 ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s", parent_window->Name, name); // May omit ID if in root of ID stack
5763 else*/
5764 if (name)
5765 ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s_%08X", parent_window->Name, name, id);
5766 else
5767 ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%08X", parent_window->Name, id);
5768
5769 // Set style
5770 const float backup_border_size = g.Style.ChildBorderSize;
5771 if ((child_flags & ImGuiChildFlags_Border) == 0)
5772 g.Style.ChildBorderSize = 0.0f;
5773
5774 // Begin into window
5775 const bool ret = Begin(temp_window_name, NULL, window_flags);
5776
5777 // Restore style
5778 g.Style.ChildBorderSize = backup_border_size;
5779 if (child_flags & ImGuiChildFlags_FrameStyle)
5780 {
5781 PopStyleVar(3);
5782 PopStyleColor();
5783 }
5784
5785 ImGuiWindow* child_window = g.CurrentWindow;
5786 child_window->ChildId = id;
5787
5788 // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
5789 // While this is not really documented/defined, it seems that the expected thing to do.
5790 if (child_window->BeginCount == 1)
5791 parent_window->DC.CursorPos = child_window->Pos;
5792
5793 // Process navigation-in immediately so NavInit can run on first frame
5794 // Can enter a child if (A) it has navigable items or (B) it can be scrolled.
5795 const ImGuiID temp_id_for_activation = ImHashStr("##Child", 0, id);
5796 if (g.ActiveId == temp_id_for_activation)
5797 ClearActiveID();
5798 if (g.NavActivateId == id && !(window_flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY))
5799 {
5800 FocusWindow(child_window);
5801 NavInitWindow(child_window, false);
5802 SetActiveID(temp_id_for_activation, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
5803 g.ActiveIdSource = g.NavInputSource;
5804 }
5805 return ret;
5806}
5807
5808void ImGui::EndChild()
5809{
5810 ImGuiContext& g = *GImGui;
5811 ImGuiWindow* child_window = g.CurrentWindow;
5812
5813 IM_ASSERT(g.WithinEndChild == false);
5814 IM_ASSERT(child_window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() calls
5815
5816 g.WithinEndChild = true;
5817 ImVec2 child_size = child_window->Size;
5818 End();
5819 if (child_window->BeginCount == 1)
5820 {
5821 ImGuiWindow* parent_window = g.CurrentWindow;
5822 ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + child_size);
5823 ItemSize(child_size);
5824 if ((child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY) && !(child_window->Flags & ImGuiWindowFlags_NavFlattened))
5825 {
5826 ItemAdd(bb, child_window->ChildId);
5827 RenderNavHighlight(bb, child_window->ChildId);
5828
5829 // 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)
5830 if (child_window->DC.NavLayersActiveMask == 0 && child_window == g.NavWindow)
5831 RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_Compact);
5832 }
5833 else
5834 {
5835 // Not navigable into
5836 ItemAdd(bb, 0);
5837
5838 // But when flattened we directly reach items, adjust active layer mask accordingly
5839 if (child_window->Flags & ImGuiWindowFlags_NavFlattened)
5840 parent_window->DC.NavLayersActiveMaskNext |= child_window->DC.NavLayersActiveMaskNext;
5841 }
5842 if (g.HoveredWindow == child_window)
5843 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
5844 }
5845 g.WithinEndChild = false;
5846 g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
5847}
5848
5849static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
5850{
5851 window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags);
5852 window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags);
5853 window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
5854 window->SetWindowDockAllowFlags = enabled ? (window->SetWindowDockAllowFlags | flags) : (window->SetWindowDockAllowFlags & ~flags);
5855}
5856
5857ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
5858{
5859 ImGuiContext& g = *GImGui;
5860 return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
5861}
5862
5863ImGuiWindow* ImGui::FindWindowByName(const char* name)
5864{
5865 ImGuiID id = ImHashStr(name);
5866 return FindWindowByID(id);
5867}
5868
5869static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5870{
5871 const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5872 window->ViewportPos = main_viewport->Pos;
5873 if (settings->ViewportId)
5874 {
5875 window->ViewportId = settings->ViewportId;
5876 window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
5877 }
5878 window->Pos = ImTrunc(ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y));
5879 if (settings->Size.x > 0 && settings->Size.y > 0)
5880 window->Size = window->SizeFull = ImTrunc(ImVec2(settings->Size.x, settings->Size.y));
5881 window->Collapsed = settings->Collapsed;
5882 window->DockId = settings->DockId;
5883 window->DockOrder = settings->DockOrder;
5884}
5885
5886static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
5887{
5888 ImGuiContext& g = *GImGui;
5889
5890 const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
5891 const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
5892 if ((just_created || child_flag_changed) && !new_is_explicit_child)
5893 {
5894 IM_ASSERT(!g.WindowsFocusOrder.contains(window));
5895 g.WindowsFocusOrder.push_back(window);
5896 window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
5897 }
5898 else if (!just_created && child_flag_changed && new_is_explicit_child)
5899 {
5900 IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
5901 for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
5902 g.WindowsFocusOrder[n]->FocusOrder--;
5903 g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder);
5904 window->FocusOrder = -1;
5905 }
5906 window->IsExplicitChild = new_is_explicit_child;
5907}
5908
5909static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5910{
5911 // Initial window state with e.g. default/arbitrary window position
5912 // Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
5913 const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5914 window->Pos = main_viewport->Pos + ImVec2(60, 60);
5915 window->Size = window->SizeFull = ImVec2(0, 0);
5916 window->ViewportPos = main_viewport->Pos;
5917 window->SetWindowPosAllowFlags = window->SetWindowSizeAllowFlags = window->SetWindowCollapsedAllowFlags = window->SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
5918
5919 if (settings != NULL)
5920 {
5921 SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
5922 ApplyWindowSettings(window, settings);
5923 }
5924 window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values
5925
5926 if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
5927 {
5928 window->AutoFitFramesX = window->AutoFitFramesY = 2;
5929 window->AutoFitOnlyGrows = false;
5930 }
5931 else
5932 {
5933 if (window->Size.x <= 0.0f)
5934 window->AutoFitFramesX = 2;
5935 if (window->Size.y <= 0.0f)
5936 window->AutoFitFramesY = 2;
5937 window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
5938 }
5939}
5940
5941static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
5942{
5943 // Create window the first time
5944 //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
5945 ImGuiContext& g = *GImGui;
5946 ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
5947 window->Flags = flags;
5948 g.WindowsById.SetVoidPtr(window->ID, window);
5949
5950 ImGuiWindowSettings* settings = NULL;
5951 if (!(flags & ImGuiWindowFlags_NoSavedSettings))
5952 if ((settings = ImGui::FindWindowSettingsByWindow(window)) != 0)
5953 window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
5954
5955 InitOrLoadWindowSettings(window, settings);
5956
5957 if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
5958 g.Windows.push_front(window); // Quite slow but rare and only once
5959 else
5960 g.Windows.push_back(window);
5961
5962 return window;
5963}
5964
5965static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window)
5966{
5967 return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window;
5968}
5969
5970static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window)
5971{
5972 return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window;
5973}
5974
5975static inline ImVec2 CalcWindowMinSize(ImGuiWindow* window)
5976{
5977 // We give windows non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
5978 // FIXME: Essentially we want to restrict manual resizing to WindowMinSize+Decoration, and allow api resizing to be smaller.
5979 // Perhaps should tend further a neater test for this.
5980 ImGuiContext& g = *GImGui;
5981 ImVec2 size_min;
5982 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup))
5983 {
5984 size_min.x = (window->ChildFlags & ImGuiChildFlags_ResizeX) ? g.Style.WindowMinSize.x : 4.0f;
5985 size_min.y = (window->ChildFlags & ImGuiChildFlags_ResizeY) ? g.Style.WindowMinSize.y : 4.0f;
5986 }
5987 else
5988 {
5989 size_min.x = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.x : 4.0f;
5990 size_min.y = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.y : 4.0f;
5991 }
5992
5993 // Reduce artifacts with very small windows
5994 ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window);
5995 size_min.y = ImMax(size_min.y, window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f));
5996 return size_min;
5997}
5998
5999static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
6000{
6001 ImGuiContext& g = *GImGui;
6002 ImVec2 new_size = size_desired;
6003 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
6004 {
6005 // See comments in SetNextWindowSizeConstraints() for details about setting size_min an size_max.
6006 ImRect cr = g.NextWindowData.SizeConstraintRect;
6007 new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
6008 new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
6009 if (g.NextWindowData.SizeCallback)
6010 {
6011 ImGuiSizeCallbackData data;
6012 data.UserData = g.NextWindowData.SizeCallbackUserData;
6013 data.Pos = window->Pos;
6014 data.CurrentSize = window->SizeFull;
6015 data.DesiredSize = new_size;
6016 g.NextWindowData.SizeCallback(&data);
6017 new_size = data.DesiredSize;
6018 }
6019 new_size.x = IM_TRUNC(new_size.x);
6020 new_size.y = IM_TRUNC(new_size.y);
6021 }
6022
6023 // Minimum size
6024 ImVec2 size_min = CalcWindowMinSize(window);
6025 return ImMax(new_size, size_min);
6026}
6027
6028static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
6029{
6030 bool preserve_old_content_sizes = false;
6031 if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
6032 preserve_old_content_sizes = true;
6033 else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
6034 preserve_old_content_sizes = true;
6035 if (preserve_old_content_sizes)
6036 {
6037 *content_size_current = window->ContentSize;
6038 *content_size_ideal = window->ContentSizeIdeal;
6039 return;
6040 }
6041
6042 content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
6043 content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
6044 content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
6045 content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
6046}
6047
6048static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
6049{
6050 ImGuiContext& g = *GImGui;
6051 ImGuiStyle& style = g.Style;
6052 const float decoration_w_without_scrollbars = window->DecoOuterSizeX1 + window->DecoOuterSizeX2 - window->ScrollbarSizes.x;
6053 const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y;
6054 ImVec2 size_pad = window->WindowPadding * 2.0f;
6055 ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars);
6056 if (window->Flags & ImGuiWindowFlags_Tooltip)
6057 {
6058 // Tooltip always resize
6059 return size_desired;
6060 }
6061 else
6062 {
6063 // Maximum window size is determined by the viewport size or monitor size
6064 ImVec2 size_min = CalcWindowMinSize(window);
6065 ImVec2 size_max = (window->ViewportOwned || ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup))) ? ImVec2(FLT_MAX, FLT_MAX) : ImGui::GetMainViewport()->WorkSize - style.DisplaySafeAreaPadding * 2.0f;
6066 const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
6067 if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0)
6068 size_max = g.PlatformIO.Monitors[monitor_idx].WorkSize - style.DisplaySafeAreaPadding * 2.0f;
6069 ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, size_max));
6070
6071 // When the window cannot fit all contents (either because of constraints, either because screen is too small),
6072 // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
6073 ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6074 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);
6075 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);
6076 if (will_have_scrollbar_x)
6077 size_auto_fit.y += style.ScrollbarSize;
6078 if (will_have_scrollbar_y)
6079 size_auto_fit.x += style.ScrollbarSize;
6080 return size_auto_fit;
6081 }
6082}
6083
6084ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
6085{
6086 ImVec2 size_contents_current;
6087 ImVec2 size_contents_ideal;
6088 CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
6089 ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);
6090 ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6091 return size_final;
6092}
6093
6094static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
6095{
6096 if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
6097 return ImGuiCol_PopupBg;
6098 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive)
6099 return ImGuiCol_ChildBg;
6100 return ImGuiCol_WindowBg;
6101}
6102
6103static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
6104{
6105 ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left
6106 ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
6107 ImVec2 size_expected = pos_max - pos_min;
6108 ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
6109 *out_pos = pos_min;
6110 if (corner_norm.x == 0.0f)
6111 out_pos->x -= (size_constrained.x - size_expected.x);
6112 if (corner_norm.y == 0.0f)
6113 out_pos->y -= (size_constrained.y - size_expected.y);
6114 *out_size = size_constrained;
6115}
6116
6117// Data for resizing from resize grip / corner
6124static const ImGuiResizeGripDef resize_grip_def[4] =
6125{
6126 { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 }, // Lower-right
6127 { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 }, // Lower-left
6128 { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 }, // Upper-left (Unused)
6129 { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 } // Upper-right (Unused)
6130};
6131
6132// Data for resizing from borders
6134{
6135 ImVec2 InnerDir; // Normal toward inside
6136 ImVec2 SegmentN1, SegmentN2; // End positions, normalized (0,0: upper left)
6137 float OuterAngle; // Angle toward outside
6138};
6139static const ImGuiResizeBorderDef resize_border_def[4] =
6140{
6141 { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left
6142 { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
6143 { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up
6144 { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f } // Down
6145};
6146
6147static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
6148{
6149 ImRect rect = window->Rect();
6150 if (thickness == 0.0f)
6151 rect.Max -= ImVec2(1, 1);
6152 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); }
6153 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); }
6154 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); }
6155 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); }
6156 IM_ASSERT(0);
6157 return ImRect();
6158}
6159
6160// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
6161ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
6162{
6163 IM_ASSERT(n >= 0 && n < 4);
6164 ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6165 id = ImHashStr("#RESIZE", 0, id);
6166 id = ImHashData(&n, sizeof(int), id);
6167 return id;
6168}
6169
6170// Borders (Left, Right, Up, Down)
6171ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
6172{
6173 IM_ASSERT(dir >= 0 && dir < 4);
6174 int n = (int)dir + 4;
6175 ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6176 id = ImHashStr("#RESIZE", 0, id);
6177 id = ImHashData(&n, sizeof(int), id);
6178 return id;
6179}
6180
6181// Handle resize for: Resize Grips, Borders, Gamepad
6182// Return true when using auto-fit (double-click on resize grip)
6183static 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)
6184{
6185 ImGuiContext& g = *GImGui;
6186 ImGuiWindowFlags flags = window->Flags;
6187
6188 if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6189 return false;
6190 if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
6191 return false;
6192
6193 int ret_auto_fit_mask = 0x00;
6194 const float grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
6195 const float grip_hover_inner_size = IM_TRUNC(grip_draw_size * 0.75f);
6196 const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;
6197
6198 ImRect clamp_rect = visibility_rect;
6199 const bool window_move_from_title_bar = g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar);
6200 if (window_move_from_title_bar)
6201 clamp_rect.Min.y -= window->TitleBarHeight();
6202
6203 ImVec2 pos_target(FLT_MAX, FLT_MAX);
6204 ImVec2 size_target(FLT_MAX, FLT_MAX);
6205
6206 // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time).
6207 // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
6208 // This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it.
6209 // - 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.
6210 // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold).
6211 // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup.
6212 const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration);
6213 if (clip_with_viewport_rect)
6214 window->ClipRect = window->Viewport->GetMainRect();
6215
6216 // Resize grips and borders are on layer 1
6217 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6218
6219 // Manual resize grips
6220 PushID("#RESIZE");
6221 for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6222 {
6223 const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
6224 const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);
6225
6226 // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
6227 bool hovered, held;
6228 ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
6229 if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
6230 if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
6231 ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()
6232 ItemAdd(resize_rect, resize_grip_id, NULL, ImGuiItemFlags_NoNav);
6233 ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6234 //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
6235 if (hovered || held)
6236 g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
6237
6238 if (held && g.IO.MouseDoubleClicked[0])
6239 {
6240 // Auto-fit when double-clicking
6241 size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6242 ret_auto_fit_mask = 0x03; // Both axises
6243 ClearActiveID();
6244 }
6245 else if (held)
6246 {
6247 // Resize from any of the four corners
6248 // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
6249 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);
6250 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);
6251 ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN); // Corner of the window corresponding to our corner grip
6252 corner_target = ImClamp(corner_target, clamp_min, clamp_max);
6253 CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
6254 }
6255
6256 // Only lower-left grip is visible before hovering/activating
6257 if (resize_grip_n == 0 || held || hovered)
6258 resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
6259 }
6260
6261 int resize_border_mask = 0x00;
6262 if (window->Flags & ImGuiWindowFlags_ChildWindow)
6263 resize_border_mask |= ((window->ChildFlags & ImGuiChildFlags_ResizeX) ? 0x02 : 0) | ((window->ChildFlags & ImGuiChildFlags_ResizeY) ? 0x08 : 0);
6264 else
6265 resize_border_mask = g.IO.ConfigWindowsResizeFromEdges ? 0x0F : 0x00;
6266 for (int border_n = 0; border_n < 4; border_n++)
6267 {
6268 if ((resize_border_mask & (1 << border_n)) == 0)
6269 continue;
6270 const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6271 const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
6272
6273 bool hovered, held;
6274 ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6275 ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
6276 ItemAdd(border_rect, border_id, NULL, ImGuiItemFlags_NoNav);
6277 ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6278 //GetForegroundDrawList(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
6279 if (hovered && g.HoveredIdTimer <= WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER)
6280 hovered = false;
6281 if (hovered || held)
6282 g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
6283 if (held && g.IO.MouseDoubleClicked[0])
6284 {
6285 // Double-clicking bottom or right border auto-fit on this axis
6286 // FIXME: Support top and right borders: rework CalcResizePosSizeFromAnyCorner() to be reusable in both cases.
6287 if (border_n == 1 || border_n == 3) // Right and bottom border
6288 {
6289 size_target[axis] = CalcWindowSizeAfterConstraint(window, size_auto_fit)[axis];
6290 ret_auto_fit_mask |= (1 << axis);
6291 hovered = held = false; // So border doesn't show highlighted at new position
6292 }
6293 ClearActiveID();
6294 }
6295 else if (held)
6296 {
6297 // Switch to relative resizing mode when border geometry moved (e.g. resizing a child altering parent scroll), in order to avoid resizing feedback loop.
6298 // 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.
6299 // FIXME: May want to generalize this idiom at lower-level, so more widgets can use it!
6300 const bool just_scrolled_manually_while_resizing = (g.WheelingWindow != NULL && g.WheelingWindowScrolledFrame == g.FrameCount && IsWindowChildOf(window, g.WheelingWindow, false, true));
6301 if (g.ActiveIdIsJustActivated || just_scrolled_manually_while_resizing)
6302 {
6303 g.WindowResizeBorderExpectedRect = border_rect;
6304 g.WindowResizeRelativeMode = false;
6305 }
6306 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && memcmp(&g.WindowResizeBorderExpectedRect, &border_rect, sizeof(ImRect)) != 0)
6307 g.WindowResizeRelativeMode = true;
6308
6309 const ImVec2 border_curr = (window->Pos + ImMin(def.SegmentN1, def.SegmentN2) * window->Size);
6310 const float border_target_rel_mode_for_axis = border_curr[axis] + g.IO.MouseDelta[axis];
6311 const float border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING; // Match ButtonBehavior() padding above.
6312
6313 // Use absolute mode position
6314 ImVec2 border_target = window->Pos;
6315 border_target[axis] = border_target_abs_mode_for_axis;
6316
6317 // Use relative mode target for child window, ignore resize when moving back toward the ideal absolute position.
6318 bool ignore_resize = false;
6319 if (g.WindowResizeRelativeMode)
6320 {
6321 //GetForegroundDrawList()->AddText(GetMainViewport()->WorkPos, IM_COL32_WHITE, "Relative Mode");
6322 border_target[axis] = border_target_rel_mode_for_axis;
6323 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))
6324 ignore_resize = true;
6325 }
6326
6327 // Clamp, apply
6328 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);
6329 ImVec2 clamp_max(border_n == ImGuiDir_Left ? clamp_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? clamp_rect.Max.y : +FLT_MAX);
6330 border_target = ImClamp(border_target, clamp_min, clamp_max);
6331 if (flags & ImGuiWindowFlags_ChildWindow) // Clamp resizing of childs within parent
6332 {
6333 if ((flags & (ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar)) == 0 || (flags & ImGuiWindowFlags_NoScrollbar))
6334 border_target.x = ImClamp(border_target.x, window->ParentWindow->InnerClipRect.Min.x, window->ParentWindow->InnerClipRect.Max.x);
6335 if (flags & ImGuiWindowFlags_NoScrollbar)
6336 border_target.y = ImClamp(border_target.y, window->ParentWindow->InnerClipRect.Min.y, window->ParentWindow->InnerClipRect.Max.y);
6337 }
6338 if (!ignore_resize)
6339 CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);
6340 }
6341 if (hovered)
6342 *border_hovered = border_n;
6343 if (held)
6344 *border_held = border_n;
6345 }
6346 PopID();
6347
6348 // Restore nav layer
6349 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6350
6351 // Navigation resize (keyboard/gamepad)
6352 // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user.
6353 // Not even sure the callback works here.
6354 if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindowDockTree == window)
6355 {
6356 ImVec2 nav_resize_dir;
6357 if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
6358 nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
6359 if (g.NavInputSource == ImGuiInputSource_Gamepad)
6360 nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown);
6361 if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f)
6362 {
6363 const float NAV_RESIZE_SPEED = 600.0f;
6364 const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y);
6365 g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
6366 g.NavWindowingAccumDeltaSize = ImMax(g.NavWindowingAccumDeltaSize, clamp_rect.Min - window->Pos - window->Size); // We need Pos+Size >= clmap_rect.Min, so Size >= clmap_rect.Min - Pos, so size_delta >= clmap_rect.Min - window->Pos - window->Size
6367 g.NavWindowingToggleLayer = false;
6368 g.NavDisableMouseHover = true;
6369 resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
6370 ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaSize);
6371 if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
6372 {
6373 // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
6374 size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + accum_floored);
6375 g.NavWindowingAccumDeltaSize -= accum_floored;
6376 }
6377 }
6378 }
6379
6380 // Apply back modified position/size to window
6381 const ImVec2 curr_pos = window->Pos;
6382 const ImVec2 curr_size = window->SizeFull;
6383 if (size_target.x != FLT_MAX && (window->Size.x != size_target.x || window->SizeFull.x != size_target.x))
6384 window->Size.x = window->SizeFull.x = size_target.x;
6385 if (size_target.y != FLT_MAX && (window->Size.y != size_target.y || window->SizeFull.y != size_target.y))
6386 window->Size.y = window->SizeFull.y = size_target.y;
6387 if (pos_target.x != FLT_MAX && window->Pos.x != ImTrunc(pos_target.x))
6388 window->Pos.x = ImTrunc(pos_target.x);
6389 if (pos_target.y != FLT_MAX && window->Pos.y != ImTrunc(pos_target.y))
6390 window->Pos.y = ImTrunc(pos_target.y);
6391 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)
6392 MarkIniSettingsDirty(window);
6393
6394 // Recalculate next expected border expected coordinates
6395 if (*border_held != -1)
6396 g.WindowResizeBorderExpectedRect = GetResizeBorderRect(window, *border_held, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6397
6398 return ret_auto_fit_mask;
6399}
6400
6401static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect)
6402{
6403 ImGuiContext& g = *GImGui;
6404 ImVec2 size_for_clamping = window->Size;
6405 if (g.IO.ConfigWindowsMoveFromTitleBarOnly && (!(window->Flags & ImGuiWindowFlags_NoTitleBar) || window->DockNodeAsHost))
6406 size_for_clamping.y = ImGui::GetFrameHeight(); // Not using window->TitleBarHeight() as DockNodeAsHost will report 0.0f here.
6407 window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
6408}
6409
6410static void RenderWindowOuterSingleBorder(ImGuiWindow* window, int border_n, ImU32 border_col, float border_size)
6411{
6412 const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6413 const float rounding = window->WindowRounding;
6414 const ImRect border_r = GetResizeBorderRect(window, border_n, rounding, 0.0f);
6415 window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle);
6416 window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f);
6417 window->DrawList->PathStroke(border_col, ImDrawFlags_None, border_size);
6418}
6419
6420static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
6421{
6422 ImGuiContext& g = *GImGui;
6423 const float border_size = window->WindowBorderSize;
6424 const ImU32 border_col = GetColorU32(ImGuiCol_Border);
6425 if (border_size > 0.0f && (window->Flags & ImGuiWindowFlags_NoBackground) == 0)
6426 window->DrawList->AddRect(window->Pos, window->Pos + window->Size, border_col, window->WindowRounding, 0, window->WindowBorderSize);
6427 else if (border_size > 0.0f)
6428 {
6429 if (window->ChildFlags & ImGuiChildFlags_ResizeX) // Similar code as 'resize_border_mask' computation in UpdateWindowManualResize() but we specifically only always draw explicit child resize border.
6430 RenderWindowOuterSingleBorder(window, 1, border_col, border_size);
6431 if (window->ChildFlags & ImGuiChildFlags_ResizeY)
6432 RenderWindowOuterSingleBorder(window, 3, border_col, border_size);
6433 }
6434 if (window->ResizeBorderHovered != -1 || window->ResizeBorderHeld != -1)
6435 {
6436 const int border_n = (window->ResizeBorderHeld != -1) ? window->ResizeBorderHeld : window->ResizeBorderHovered;
6437 const ImU32 border_col_resizing = GetColorU32((window->ResizeBorderHeld != -1) ? ImGuiCol_SeparatorActive : ImGuiCol_SeparatorHovered);
6438 RenderWindowOuterSingleBorder(window, border_n, border_col_resizing, ImMax(2.0f, window->WindowBorderSize)); // Thicker than usual
6439 }
6440 if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6441 {
6442 float y = window->Pos.y + window->TitleBarHeight() - 1;
6443 window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), border_col, g.Style.FrameBorderSize);
6444 }
6445}
6446
6447// Draw background and borders
6448// Draw and handle scrollbars
6449void 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)
6450{
6451 ImGuiContext& g = *GImGui;
6452 ImGuiStyle& style = g.Style;
6453 ImGuiWindowFlags flags = window->Flags;
6454
6455 // Ensure that ScrollBar doesn't read last frame's SkipItems
6456 IM_ASSERT(window->BeginCount == 0);
6457 window->SkipItems = false;
6458
6459 // Draw window + handle manual resize
6460 // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
6461 const float window_rounding = window->WindowRounding;
6462 const float window_border_size = window->WindowBorderSize;
6463 if (window->Collapsed)
6464 {
6465 // Title bar only
6466 const float backup_border_size = style.FrameBorderSize;
6467 g.Style.FrameBorderSize = window->WindowBorderSize;
6468 ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
6469 if (window->ViewportOwned)
6470 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)
6471 RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
6472 g.Style.FrameBorderSize = backup_border_size;
6473 }
6474 else
6475 {
6476 // Window background
6477 if (!(flags & ImGuiWindowFlags_NoBackground))
6478 {
6479 bool is_docking_transparent_payload = false;
6480 if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload)
6481 if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window)
6482 is_docking_transparent_payload = true;
6483
6484 ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window));
6485 if (window->ViewportOwned)
6486 {
6487 bg_col |= IM_COL32_A_MASK; // No alpha
6488 if (is_docking_transparent_payload)
6489 window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
6490 }
6491 else
6492 {
6493 // Adjust alpha. For docking
6494 bool override_alpha = false;
6495 float alpha = 1.0f;
6496 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
6497 {
6498 alpha = g.NextWindowData.BgAlphaVal;
6499 override_alpha = true;
6500 }
6501 if (is_docking_transparent_payload)
6502 {
6503 alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override?
6504 override_alpha = true;
6505 }
6506 if (override_alpha)
6507 bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
6508 }
6509
6510 // Render, for docked windows and host windows we ensure bg goes before decorations
6511 if (window->DockIsActive)
6512 window->DockNode->LastBgColor = bg_col;
6513 ImDrawList* bg_draw_list = window->DockIsActive ? window->DockNode->HostWindow->DrawList : window->DrawList;
6514 if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6515 bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
6516 bg_draw_list->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
6517 if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6518 bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
6519 }
6520 if (window->DockIsActive)
6521 window->DockNode->IsBgDrawnThisFrame = true;
6522
6523 // Title bar
6524 // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag,
6525 // in order for their pos/size to be matching their undocking state.)
6526 if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6527 {
6528 ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
6529 if (window->ViewportOwned)
6530 title_bar_col |= IM_COL32_A_MASK; // No alpha
6531 window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);
6532 }
6533
6534 // Menu bar
6535 if (flags & ImGuiWindowFlags_MenuBar)
6536 {
6537 ImRect menu_bar_rect = window->MenuBarRect();
6538 menu_bar_rect.ClipWith(window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
6539 window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop);
6540 if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
6541 window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
6542 }
6543
6544 // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock
6545 ImGuiDockNode* node = window->DockNode;
6546 if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar())
6547 {
6548 float unhide_sz_draw = ImTrunc(g.FontSize * 0.70f);
6549 float unhide_sz_hit = ImTrunc(g.FontSize * 0.55f);
6550 ImVec2 p = node->Pos;
6551 ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit));
6552 ImGuiID unhide_id = window->GetID("#UNHIDE");
6553 KeepAliveID(unhide_id);
6554 bool hovered, held;
6555 if (ButtonBehavior(r, unhide_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren))
6556 node->WantHiddenTabBarToggle = true;
6557 else if (held && IsMouseDragging(0))
6558 StartMouseMovingWindowOrNode(window, node, true); // Undock from tab-bar triangle = same as window/collapse menu button
6559
6560 // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size..
6561 ImU32 col = GetColorU32(((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
6562 window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col);
6563 }
6564
6565 // Scrollbars
6566 if (window->ScrollbarX)
6567 Scrollbar(ImGuiAxis_X);
6568 if (window->ScrollbarY)
6569 Scrollbar(ImGuiAxis_Y);
6570
6571 // Render resize grips (after their input handling so we don't have a frame of latency)
6572 if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
6573 {
6574 for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6575 {
6576 const ImU32 col = resize_grip_col[resize_grip_n];
6577 if ((col & IM_COL32_A_MASK) == 0)
6578 continue;
6579 const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
6580 const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
6581 window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
6582 window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
6583 window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
6584 window->DrawList->PathFillConvex(col);
6585 }
6586 }
6587
6588 // Borders (for dock node host they will be rendered over after the tab bar)
6589 if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
6590 RenderWindowOuterBorders(window);
6591 }
6592}
6593
6594// When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead.
6595// Render title text, collapse button, close button
6596void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
6597{
6598 ImGuiContext& g = *GImGui;
6599 ImGuiStyle& style = g.Style;
6600 ImGuiWindowFlags flags = window->Flags;
6601
6602 const bool has_close_button = (p_open != NULL);
6603 const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
6604
6605 // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
6606 // 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?
6607 const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
6608 g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
6609 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6610
6611 // Layout buttons
6612 // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
6613 float pad_l = style.FramePadding.x;
6614 float pad_r = style.FramePadding.x;
6615 float button_sz = g.FontSize;
6616 ImVec2 close_button_pos;
6617 ImVec2 collapse_button_pos;
6618 if (has_close_button)
6619 {
6620 close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6621 pad_r += button_sz + style.ItemInnerSpacing.x;
6622 }
6623 if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
6624 {
6625 collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6626 pad_r += button_sz + style.ItemInnerSpacing.x;
6627 }
6628 if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
6629 {
6630 collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y + style.FramePadding.y);
6631 pad_l += button_sz + style.ItemInnerSpacing.x;
6632 }
6633
6634 // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
6635 if (has_collapse_button)
6636 if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos, NULL))
6637 window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
6638
6639 // Close button
6640 if (has_close_button)
6641 if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
6642 *p_open = false;
6643
6644 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6645 g.CurrentItemFlags = item_flags_backup;
6646
6647 // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
6648 // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
6649 const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
6650 const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
6651
6652 // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
6653 // while uncentered title text will still reach edges correctly.
6654 if (pad_l > style.FramePadding.x)
6655 pad_l += g.Style.ItemInnerSpacing.x;
6656 if (pad_r > style.FramePadding.x)
6657 pad_r += g.Style.ItemInnerSpacing.x;
6658 if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
6659 {
6660 float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
6661 float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
6662 pad_l = ImMax(pad_l, pad_extend * centerness);
6663 pad_r = ImMax(pad_r, pad_extend * centerness);
6664 }
6665
6666 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);
6667 ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y);
6668 if (flags & ImGuiWindowFlags_UnsavedDocument)
6669 {
6670 ImVec2 marker_pos;
6671 marker_pos.x = ImClamp(layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, layout_r.Min.x, layout_r.Max.x);
6672 marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
6673 if (marker_pos.x > layout_r.Min.x)
6674 {
6675 RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_Text));
6676 clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f));
6677 }
6678 }
6679 //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6680 //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6681 RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
6682}
6683
6684void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
6685{
6686 window->ParentWindow = parent_window;
6687 window->RootWindow = window->RootWindowPopupTree = window->RootWindowDockTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
6688 if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
6689 {
6690 window->RootWindowDockTree = parent_window->RootWindowDockTree;
6691 if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost))
6692 window->RootWindow = parent_window->RootWindow;
6693 }
6694 if (parent_window && (flags & ImGuiWindowFlags_Popup))
6695 window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
6696 if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) // FIXME: simply use _NoTitleBar ?
6697 window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
6698 while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
6699 {
6700 IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
6701 window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
6702 }
6703}
6704
6705// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
6706// should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
6707// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
6708// - WindowA // FindBlockingModal() returns Modal1
6709// - WindowB // .. returns Modal1
6710// - Modal1 // .. returns Modal2
6711// - WindowC // .. returns Modal2
6712// - WindowD // .. returns Modal2
6713// - Modal2 // .. returns Modal2
6714// - WindowE // .. returns NULL
6715// Notes:
6716// - FindBlockingModal(NULL) == NULL is generally equivalent to GetTopMostPopupModal() == NULL.
6717// Only difference is here we check for ->Active/WasActive but it may be unecessary.
6718ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
6719{
6720 ImGuiContext& g = *GImGui;
6721 if (g.OpenPopupStack.Size <= 0)
6722 return NULL;
6723
6724 // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
6725 for (ImGuiPopupData& popup_data : g.OpenPopupStack)
6726 {
6727 ImGuiWindow* popup_window = popup_data.Window;
6728 if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
6729 continue;
6730 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.
6731 continue;
6732 if (window == NULL) // FindBlockingModal(NULL) test for if FocusWindow(NULL) is naturally possible via a mouse click.
6733 return popup_window;
6734 if (IsWindowWithinBeginStackOf(window, popup_window)) // Window may be over modal
6735 continue;
6736 return popup_window; // Place window right below first block modal
6737 }
6738 return NULL;
6739}
6740
6741// Push a new Dear ImGui window to add widgets to.
6742// - 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.
6743// - Begin/End can be called multiple times during the frame with the same window name to append content.
6744// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
6745// 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.
6746// - 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.
6747// - 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.
6748bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
6749{
6750 ImGuiContext& g = *GImGui;
6751 const ImGuiStyle& style = g.Style;
6752 IM_ASSERT(name != NULL && name[0] != '\0'); // Window name required
6753 IM_ASSERT(g.WithinFrameScope); // Forgot to call ImGui::NewFrame()
6754 IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
6755
6756 // Find or create
6757 ImGuiWindow* window = FindWindowByName(name);
6758 const bool window_just_created = (window == NULL);
6759 if (window_just_created)
6760 window = CreateNewWindow(name, flags);
6761
6762 // [DEBUG] Debug break requested by user
6763 if (g.DebugBreakInWindow == window->ID)
6764 IM_DEBUG_BREAK();
6765
6766 // Automatically disable manual moving/resizing when NoInputs is set
6767 if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
6768 flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
6769
6770 if (flags & ImGuiWindowFlags_NavFlattened)
6771 IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
6772
6773 const int current_frame = g.FrameCount;
6774 const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
6775 window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
6776
6777 // Update the Appearing flag (note: the BeginDocked() path may also set this to true later)
6778 bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
6779 if (flags & ImGuiWindowFlags_Popup)
6780 {
6781 ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6782 window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
6783 window_just_activated_by_user |= (window != popup_ref.Window);
6784 }
6785
6786 // Update Flags, LastFrameActive, BeginOrderXXX fields
6787 const bool window_was_appearing = window->Appearing;
6788 if (first_begin_of_the_frame)
6789 {
6790 UpdateWindowInFocusOrderList(window, window_just_created, flags);
6791 window->Appearing = window_just_activated_by_user;
6792 if (window->Appearing)
6793 SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6794 window->FlagsPreviousFrame = window->Flags;
6795 window->Flags = (ImGuiWindowFlags)flags;
6796 window->ChildFlags = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasChildFlags) ? g.NextWindowData.ChildFlags : 0;
6797 window->LastFrameActive = current_frame;
6798 window->LastTimeActive = (float)g.Time;
6799 window->BeginOrderWithinParent = 0;
6800 window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
6801 }
6802 else
6803 {
6804 flags = window->Flags;
6805 }
6806
6807 // Docking
6808 // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1)
6809 IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both
6810 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasDock)
6811 SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond);
6812 if (first_begin_of_the_frame)
6813 {
6814 bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL);
6815 bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window);
6816 bool dock_node_was_visible = window->DockNodeIsVisible;
6817 bool dock_tab_was_visible = window->DockTabIsVisible;
6818 if (has_dock_node || new_auto_dock_node)
6819 {
6820 BeginDocked(window, p_open);
6821 flags = window->Flags;
6822 if (window->DockIsActive)
6823 {
6824 IM_ASSERT(window->DockNode != NULL);
6825 g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints
6826 }
6827
6828 // Amend the Appearing flag
6829 if (window->DockTabIsVisible && !dock_tab_was_visible && dock_node_was_visible && !window->Appearing && !window_was_appearing)
6830 {
6831 window->Appearing = true;
6832 SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6833 }
6834 }
6835 else
6836 {
6837 window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
6838 }
6839 }
6840
6841 // 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
6842 ImGuiWindow* parent_window_in_stack = (window->DockIsActive && window->DockNode->HostWindow) ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
6843 ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
6844 IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
6845
6846 // We allow window memory to be compacted so recreate the base stack when needed.
6847 if (window->IDStack.Size == 0)
6848 window->IDStack.push_back(window->ID);
6849
6850 // Add to stack
6851 g.CurrentWindow = window;
6852 ImGuiWindowStackData window_stack_data;
6853 window_stack_data.Window = window;
6854 window_stack_data.ParentLastItemDataBackup = g.LastItemData;
6855 window_stack_data.StackSizesOnBegin.SetToContextState(&g);
6856 g.CurrentWindowStack.push_back(window_stack_data);
6857 if (flags & ImGuiWindowFlags_ChildMenu)
6858 g.BeginMenuDepth++;
6859
6860 // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
6861 if (first_begin_of_the_frame)
6862 {
6863 UpdateWindowParentAndRootLinks(window, flags, parent_window);
6864 window->ParentWindowInBeginStack = parent_window_in_stack;
6865
6866 // Focus route
6867 // There's little point to expose a flag to set this: because the interesting cases won't be using parent_window_in_stack,
6868 // Use for e.g. linking a tool window in a standalone viewport to a document window, regardless of their Begin() stack parenting. (#6798)
6869 window->ParentWindowForFocusRoute = (window->RootWindow != window) ? parent_window_in_stack : NULL;
6870 if (window->ParentWindowForFocusRoute == NULL && window->DockNode != NULL)
6871 if (window->DockNode->MergedFlags & ImGuiDockNodeFlags_DockedWindowsInFocusRoute)
6872 window->ParentWindowForFocusRoute = window->DockNode->HostWindow;
6873
6874 // Override with SetNextWindowClass() field or direct call to SetWindowParentWindowForFocusRoute()
6875 if (window->WindowClass.FocusRouteParentWindowId != 0)
6876 {
6877 window->ParentWindowForFocusRoute = FindWindowByID(window->WindowClass.FocusRouteParentWindowId);
6878 IM_ASSERT(window->ParentWindowForFocusRoute != 0); // Invalid value for FocusRouteParentWindowId.
6879 }
6880 }
6881
6882 // Add to focus scope stack
6883 PushFocusScope((flags & ImGuiWindowFlags_NavFlattened) ? g.CurrentFocusScopeId : window->ID);
6884 window->NavRootFocusScopeId = g.CurrentFocusScopeId;
6885
6886 // Add to popup stacks: update OpenPopupStack[] data, push to BeginPopupStack[]
6887 if (flags & ImGuiWindowFlags_Popup)
6888 {
6889 ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6890 popup_ref.Window = window;
6891 popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent;
6892 g.BeginPopupStack.push_back(popup_ref);
6893 window->PopupId = popup_ref.PopupId;
6894 }
6895
6896 // Process SetNextWindow***() calls
6897 // (FIXME: Consider splitting the HasXXX flags into X/Y components
6898 bool window_pos_set_by_api = false;
6899 bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
6900 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
6901 {
6902 window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
6903 if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
6904 {
6905 // May be processed on the next frame if this is our first frame and we are measuring size
6906 // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
6907 window->SetWindowPosVal = g.NextWindowData.PosVal;
6908 window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
6909 window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
6910 }
6911 else
6912 {
6913 SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
6914 }
6915 }
6916 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
6917 {
6918 window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
6919 window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
6920 if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0) // Axis-specific conditions for BeginChild()
6921 g.NextWindowData.SizeVal.x = window->SizeFull.x;
6922 if ((window->ChildFlags & ImGuiChildFlags_ResizeY) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0)
6923 g.NextWindowData.SizeVal.y = window->SizeFull.y;
6924 SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
6925 }
6926 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
6927 {
6928 if (g.NextWindowData.ScrollVal.x >= 0.0f)
6929 {
6930 window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
6931 window->ScrollTargetCenterRatio.x = 0.0f;
6932 }
6933 if (g.NextWindowData.ScrollVal.y >= 0.0f)
6934 {
6935 window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
6936 window->ScrollTargetCenterRatio.y = 0.0f;
6937 }
6938 }
6939 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
6940 window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
6941 else if (first_begin_of_the_frame)
6942 window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
6943 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasWindowClass)
6944 window->WindowClass = g.NextWindowData.WindowClass;
6945 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
6946 SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
6947 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
6948 FocusWindow(window);
6949 if (window->Appearing)
6950 SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
6951
6952 // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
6953 g.CurrentWindow = NULL;
6954
6955 // When reusing window again multiple times a frame, just append content (don't need to setup again)
6956 if (first_begin_of_the_frame)
6957 {
6958 // Initialize
6959 const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
6960 const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
6961 window->Active = true;
6962 window->HasCloseButton = (p_open != NULL);
6963 window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
6964 window->IDStack.resize(1);
6965 window->DrawList->_ResetForNewFrame();
6966 window->DC.CurrentTableIdx = -1;
6967 if (flags & ImGuiWindowFlags_DockNodeHost)
6968 {
6969 window->DrawList->ChannelsSplit(2);
6970 window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); // Render decorations on channel 1 as we will render the backgrounds manually later
6971 }
6972
6973 // Restore buffer capacity when woken from a compacted state, to avoid
6974 if (window->MemoryCompacted)
6975 GcAwakeTransientWindowBuffers(window);
6976
6977 // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
6978 // 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.
6979 bool window_title_visible_elsewhere = false;
6980 if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
6981 window_title_visible_elsewhere = true;
6982 else if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB
6983 window_title_visible_elsewhere = true;
6984 if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
6985 {
6986 size_t buf_len = (size_t)window->NameBufLen;
6987 window->Name = ImStrdupcpy(window->Name, &buf_len, name);
6988 window->NameBufLen = (int)buf_len;
6989 }
6990
6991 // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
6992
6993 // Update contents size from last frame for auto-fitting (or use explicit size)
6994 CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
6995
6996 // FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors
6997 // for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because
6998 // it has a single usage before this code block and may be set below before it is finally checked.
6999 if (window->HiddenFramesCanSkipItems > 0)
7000 window->HiddenFramesCanSkipItems--;
7001 if (window->HiddenFramesCannotSkipItems > 0)
7002 window->HiddenFramesCannotSkipItems--;
7003 if (window->HiddenFramesForRenderOnly > 0)
7004 window->HiddenFramesForRenderOnly--;
7005
7006 // Hide new windows for one frame until they calculate their size
7007 if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
7008 window->HiddenFramesCannotSkipItems = 1;
7009
7010 // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
7011 // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
7012 if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
7013 {
7014 window->HiddenFramesCannotSkipItems = 1;
7015 if (flags & ImGuiWindowFlags_AlwaysAutoResize)
7016 {
7017 if (!window_size_x_set_by_api)
7018 window->Size.x = window->SizeFull.x = 0.f;
7019 if (!window_size_y_set_by_api)
7020 window->Size.y = window->SizeFull.y = 0.f;
7021 window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
7022 }
7023 }
7024
7025 // SELECT VIEWPORT
7026 // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes.
7027
7028 WindowSelectViewport(window);
7029 SetCurrentViewport(window, window->Viewport);
7030 window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
7031 SetCurrentWindow(window);
7032 flags = window->Flags;
7033
7034 // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
7035 // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style.
7036
7037 if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow))
7038 window->WindowBorderSize = style.ChildBorderSize;
7039 else
7040 window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
7041 window->WindowPadding = style.WindowPadding;
7042 if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !(window->ChildFlags & ImGuiChildFlags_AlwaysUseWindowPadding) && window->WindowBorderSize == 0.0f)
7043 window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
7044
7045 // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
7046 window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
7047 window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
7048
7049 // Depending on condition we use previous or current window size to compare against contents size to decide if a scrollbar should be visible.
7050 // Those flags will be altered further down in the function depending on more conditions.
7051 bool use_current_size_for_scrollbar_x = window_just_created;
7052 bool use_current_size_for_scrollbar_y = window_just_created;
7053 if (window_size_x_set_by_api && window->ContentSizeExplicit.x != 0.0f)
7054 use_current_size_for_scrollbar_x = true;
7055 if (window_size_y_set_by_api && window->ContentSizeExplicit.y != 0.0f) // #7252
7056 use_current_size_for_scrollbar_y = true;
7057
7058 // Collapse window by double-clicking on title bar
7059 // 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
7060 if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive)
7061 {
7062 // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
7063 ImRect title_bar_rect = window->TitleBarRect();
7064 if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max))
7065 if (g.IO.MouseClickedCount[0] == 2 && GetKeyOwner(ImGuiKey_MouseLeft) == ImGuiKeyOwner_None)
7066 window->WantCollapseToggle = true;
7067 if (window->WantCollapseToggle)
7068 {
7069 window->Collapsed = !window->Collapsed;
7070 if (!window->Collapsed)
7071 use_current_size_for_scrollbar_y = true;
7072 MarkIniSettingsDirty(window);
7073 }
7074 }
7075 else
7076 {
7077 window->Collapsed = false;
7078 }
7079 window->WantCollapseToggle = false;
7080
7081 // SIZE
7082
7083 // Outer Decoration Sizes
7084 // (we need to clear ScrollbarSize immediatly as CalcWindowAutoFitSize() needs it and can be called from other locations).
7085 const ImVec2 scrollbar_sizes_from_last_frame = window->ScrollbarSizes;
7086 window->DecoOuterSizeX1 = 0.0f;
7087 window->DecoOuterSizeX2 = 0.0f;
7088 window->DecoOuterSizeY1 = window->TitleBarHeight() + window->MenuBarHeight();
7089 window->DecoOuterSizeY2 = 0.0f;
7090 window->ScrollbarSizes = ImVec2(0.0f, 0.0f);
7091
7092 // Calculate auto-fit size, handle automatic resize
7093 const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);
7094 if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
7095 {
7096 // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
7097 if (!window_size_x_set_by_api)
7098 {
7099 window->SizeFull.x = size_auto_fit.x;
7100 use_current_size_for_scrollbar_x = true;
7101 }
7102 if (!window_size_y_set_by_api)
7103 {
7104 window->SizeFull.y = size_auto_fit.y;
7105 use_current_size_for_scrollbar_y = true;
7106 }
7107 }
7108 else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7109 {
7110 // Auto-fit may only grow window during the first few frames
7111 // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
7112 if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
7113 {
7114 window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
7115 use_current_size_for_scrollbar_x = true;
7116 }
7117 if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
7118 {
7119 window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
7120 use_current_size_for_scrollbar_y = true;
7121 }
7122 if (!window->Collapsed)
7123 MarkIniSettingsDirty(window);
7124 }
7125
7126 // Apply minimum/maximum window size constraints and final size
7127 window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
7128 window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
7129
7130 // POSITION
7131
7132 // Popup latch its initial position, will position itself when it appears next frame
7133 if (window_just_activated_by_user)
7134 {
7135 window->AutoPosLastDirection = ImGuiDir_None;
7136 if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
7137 window->Pos = g.BeginPopupStack.back().OpenPopupPos;
7138 }
7139
7140 // Position child window
7141 if (flags & ImGuiWindowFlags_ChildWindow)
7142 {
7143 IM_ASSERT(parent_window && parent_window->Active);
7144 window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
7145 parent_window->DC.ChildWindows.push_back(window);
7146 if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
7147 window->Pos = parent_window->DC.CursorPos;
7148 }
7149
7150 const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
7151 if (window_pos_with_pivot)
7152 SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
7153 else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
7154 window->Pos = FindBestWindowPosForPopup(window);
7155 else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
7156 window->Pos = FindBestWindowPosForPopup(window);
7157 else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
7158 window->Pos = FindBestWindowPosForPopup(window);
7159
7160 // Late create viewport if we don't fit within our current host viewport.
7161 if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_IsMinimized))
7162 if (!window->Viewport->GetMainRect().Contains(window->Rect()))
7163 {
7164 // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
7165 //ImGuiViewport* old_viewport = window->Viewport;
7166 window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
7167
7168 // FIXME-DPI
7169 //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong
7170 SetCurrentViewport(window, window->Viewport);
7171 window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
7172 SetCurrentWindow(window);
7173 }
7174
7175 if (window->ViewportOwned)
7176 WindowSyncOwnedViewport(window, parent_window_in_stack);
7177
7178 // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
7179 // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
7180 ImRect viewport_rect(window->Viewport->GetMainRect());
7181 ImRect viewport_work_rect(window->Viewport->GetWorkRect());
7182 ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
7183 ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
7184
7185 // Clamp position/size so window stays visible within its viewport or monitor
7186 // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
7187 // FIXME: Similar to code in GetWindowAllowedExtentRect()
7188 if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow))
7189 {
7190 if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
7191 {
7192 ClampWindowPos(window, visibility_rect);
7193 }
7194 else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0)
7195 {
7196 if (g.MovingWindow != NULL && window->RootWindowDockTree == g.MovingWindow->RootWindowDockTree)
7197 {
7198 // While moving windows we allow them to straddle monitors (#7299, #3071)
7199 visibility_rect = g.PlatformMonitorsFullWorkRect;
7200 }
7201 else
7202 {
7203 // When not moving ensure visible in its monitor
7204 // Lost windows (e.g. a monitor disconnected) will naturally moved to the fallback/dummy monitor aka the main viewport.
7205 const ImGuiPlatformMonitor* monitor = GetViewportPlatformMonitor(window->Viewport);
7206 visibility_rect = ImRect(monitor->WorkPos, monitor->WorkPos + monitor->WorkSize);
7207 }
7208 visibility_rect.Expand(-visibility_padding);
7209 ClampWindowPos(window, visibility_rect);
7210 }
7211 }
7212 window->Pos = ImTrunc(window->Pos);
7213
7214 // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
7215 // Large values tend to lead to variety of artifacts and are not recommended.
7216 if (window->ViewportOwned || window->DockIsActive)
7217 window->WindowRounding = 0.0f;
7218 else
7219 window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
7220
7221 // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
7222 //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
7223 // window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
7224
7225 // Apply window focus (new and reactivated windows are moved to front)
7226 bool want_focus = false;
7227 if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
7228 {
7229 if (flags & ImGuiWindowFlags_Popup)
7230 want_focus = true;
7231 else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip))
7232 want_focus = true;
7233 }
7234
7235 // [Test Engine] Register whole window in the item system (before submitting further decorations)
7236#ifdef IMGUI_ENABLE_TEST_ENGINE
7237 if (g.TestEngineHookItems)
7238 {
7239 IM_ASSERT(window->IDStack.Size == 1);
7240 window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
7241 IMGUI_TEST_ENGINE_ITEM_ADD(window->ID, window->Rect(), NULL);
7242 IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
7243 window->IDStack.Size = 1;
7244 }
7245#endif
7246
7247 // Decide if we are going to handle borders and resize grips
7248 const bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
7249
7250 // Handle manual resize: Resize Grips, Borders, Gamepad
7251 int border_hovered = -1, border_held = -1;
7252 ImU32 resize_grip_col[4] = {};
7253 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.
7254 const float resize_grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
7255 if (handle_borders_and_resize_grips && !window->Collapsed)
7256 if (int auto_fit_mask = UpdateWindowManualResize(window, size_auto_fit, &border_hovered, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
7257 {
7258 if (auto_fit_mask & (1 << ImGuiAxis_X))
7259 use_current_size_for_scrollbar_x = true;
7260 if (auto_fit_mask & (1 << ImGuiAxis_Y))
7261 use_current_size_for_scrollbar_y = true;
7262 }
7263 window->ResizeBorderHovered = (signed char)border_hovered;
7264 window->ResizeBorderHeld = (signed char)border_held;
7265
7266 // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either)
7267 if (window->ViewportOwned)
7268 {
7269 if (!window->Viewport->PlatformRequestMove)
7270 window->Viewport->Pos = window->Pos;
7271 if (!window->Viewport->PlatformRequestResize)
7272 window->Viewport->Size = window->Size;
7273 window->Viewport->UpdateWorkRect();
7274 viewport_rect = window->Viewport->GetMainRect();
7275 }
7276
7277 // Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
7278 window->ViewportPos = window->Viewport->Pos;
7279
7280 // SCROLLBAR VISIBILITY
7281
7282 // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
7283 if (!window->Collapsed)
7284 {
7285 // When reading the current size we need to read it after size constraints have been applied.
7286 // Intentionally use previous frame values for InnerRect and ScrollbarSizes.
7287 // And when we use window->DecorationUp here it doesn't have ScrollbarSizes.y applied yet.
7288 ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2));
7289 ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + scrollbar_sizes_from_last_frame;
7290 ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
7291 float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
7292 float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
7293 //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
7294 window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
7295 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));
7296 if (window->ScrollbarX && !window->ScrollbarY)
7297 window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar);
7298 window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
7299
7300 // Amend the partially filled window->DecorationXXX values.
7301 window->DecoOuterSizeX2 += window->ScrollbarSizes.x;
7302 window->DecoOuterSizeY2 += window->ScrollbarSizes.y;
7303 }
7304
7305 // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
7306 // Update various regions. Variables they depend on should be set above in this function.
7307 // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
7308
7309 // Outer rectangle
7310 // Not affected by window border size. Used by:
7311 // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
7312 // - Begin() initial clipping rect for drawing window background and borders.
7313 // - Begin() clipping whole child
7314 const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
7315 const ImRect outer_rect = window->Rect();
7316 const ImRect title_bar_rect = window->TitleBarRect();
7317 window->OuterRectClipped = outer_rect;
7318 if (window->DockIsActive)
7319 window->OuterRectClipped.Min.y += window->TitleBarHeight();
7320 window->OuterRectClipped.ClipWith(host_rect);
7321
7322 // Inner rectangle
7323 // Not affected by window border size. Used by:
7324 // - InnerClipRect
7325 // - ScrollToRectEx()
7326 // - NavUpdatePageUpPageDown()
7327 // - Scrollbar()
7328 window->InnerRect.Min.x = window->Pos.x + window->DecoOuterSizeX1;
7329 window->InnerRect.Min.y = window->Pos.y + window->DecoOuterSizeY1;
7330 window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->DecoOuterSizeX2;
7331 window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->DecoOuterSizeY2;
7332
7333 // Inner clipping rectangle.
7334 // Will extend a little bit outside the normal work region.
7335 // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
7336 // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
7337 // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
7338 // Affected by window/frame border size. Used by:
7339 // - Begin() initial clip rect
7340 float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
7341 window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImTrunc(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
7342 window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
7343 window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImTrunc(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
7344 window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
7345 window->InnerClipRect.ClipWithFull(host_rect);
7346
7347 // Default item width. Make it proportional to window size if window manually resizes
7348 if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
7349 window->ItemWidthDefault = ImTrunc(window->Size.x * 0.65f);
7350 else
7351 window->ItemWidthDefault = ImTrunc(g.FontSize * 16.0f);
7352
7353 // SCROLLING
7354
7355 // Lock down maximum scrolling
7356 // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
7357 // for right/bottom aligned items without creating a scrollbar.
7358 window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
7359 window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
7360
7361 // Apply scrolling
7362 window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
7363 window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
7364 window->DecoInnerSizeX1 = window->DecoInnerSizeY1 = 0.0f;
7365
7366 // DRAWING
7367
7368 // Setup draw list and outer clipping rectangle
7369 IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
7370 window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
7371 PushClipRect(host_rect.Min, host_rect.Max, false);
7372
7373 // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
7374 // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
7375 // 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)
7376 const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible;
7377 if (is_undocked_or_docked_visible)
7378 {
7379 bool render_decorations_in_parent = false;
7380 if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
7381 {
7382 // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
7383 // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
7384 ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
7385 bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false;
7386 bool parent_is_empty = (parent_window->DrawList->VtxBuffer.Size == 0);
7387 if (window->DrawList->CmdBuffer.back().ElemCount == 0 && !parent_is_empty && !previous_child_overlapping)
7388 render_decorations_in_parent = true;
7389 }
7390 if (render_decorations_in_parent)
7391 window->DrawList = parent_window->DrawList;
7392
7393 // Handle title bar, scrollbar, resize grips and resize borders
7394 const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
7395 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)));
7396 RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
7397
7398 if (render_decorations_in_parent)
7399 window->DrawList = &window->DrawListInst;
7400 }
7401
7402 // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
7403
7404 // Work rectangle.
7405 // Affected by window padding and border size. Used by:
7406 // - Columns() for right-most edge
7407 // - TreeNode(), CollapsingHeader() for right-most edge
7408 // - BeginTabBar() for right-most edge
7409 const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
7410 const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
7411 const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7412 const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7413 window->WorkRect.Min.x = ImTrunc(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
7414 window->WorkRect.Min.y = ImTrunc(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
7415 window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
7416 window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
7417 window->ParentWorkRect = window->WorkRect;
7418
7419 // [LEGACY] Content Region
7420 // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
7421 // Unless explicit content size is specified by user, this currently represent the region leading to no scrolling.
7422 // Used by:
7423 // - Mouse wheel scrolling + many other things
7424 window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x + window->DecoOuterSizeX1;
7425 window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->DecoOuterSizeY1;
7426 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)));
7427 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)));
7428
7429 // Setup drawing context
7430 // (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.)
7431 window->DC.Indent.x = window->DecoOuterSizeX1 + window->WindowPadding.x - window->Scroll.x;
7432 window->DC.GroupOffset.x = 0.0f;
7433 window->DC.ColumnsOffset.x = 0.0f;
7434
7435 // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
7436 // 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.
7437 double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DecoOuterSizeX1 + window->DC.ColumnsOffset.x;
7438 double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + window->DecoOuterSizeY1;
7439 window->DC.CursorStartPos = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
7440 window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
7441 window->DC.CursorPos = window->DC.CursorStartPos;
7442 window->DC.CursorPosPrevLine = window->DC.CursorPos;
7443 window->DC.CursorMaxPos = window->DC.CursorStartPos;
7444 window->DC.IdealMaxPos = window->DC.CursorStartPos;
7445 window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
7446 window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
7447 window->DC.IsSameLine = window->DC.IsSetPos = false;
7448
7449 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7450 window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
7451 window->DC.NavLayersActiveMaskNext = 0x00;
7452 window->DC.NavIsScrollPushableX = true;
7453 window->DC.NavHideHighlightOneFrame = false;
7454 window->DC.NavWindowHasScrollY = (window->ScrollMax.y > 0.0f);
7455
7456 window->DC.MenuBarAppending = false;
7457 window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user);
7458 window->DC.TreeDepth = 0;
7459 window->DC.TreeJumpToParentOnPopMask = 0x00;
7460 window->DC.ChildWindows.resize(0);
7461 window->DC.StateStorage = &window->StateStorage;
7462 window->DC.CurrentColumns = NULL;
7463 window->DC.LayoutType = ImGuiLayoutType_Vertical;
7464 window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
7465
7466 window->DC.ItemWidth = window->ItemWidthDefault;
7467 window->DC.TextWrapPos = -1.0f; // disabled
7468 window->DC.ItemWidthStack.resize(0);
7469 window->DC.TextWrapPosStack.resize(0);
7470 if (flags & ImGuiWindowFlags_Modal)
7471 window->DC.ModalDimBgColor = ColorConvertFloat4ToU32(GetStyleColorVec4(ImGuiCol_ModalWindowDimBg));
7472
7473 if (window->AutoFitFramesX > 0)
7474 window->AutoFitFramesX--;
7475 if (window->AutoFitFramesY > 0)
7476 window->AutoFitFramesY--;
7477
7478 // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
7479 // We ImGuiFocusRequestFlags_UnlessBelowModal to:
7480 // - Avoid focusing a window that is created outside of a modal. This will prevent active modal from being closed.
7481 // - Position window behind the modal that is not a begin-parent of this window.
7482 if (want_focus)
7483 FocusWindow(window, ImGuiFocusRequestFlags_UnlessBelowModal);
7484 if (want_focus && window == g.NavWindow)
7485 NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
7486
7487 // Close requested by platform window (apply to all windows in this viewport)
7488 if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
7489 {
7490 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' closed by PlatformRequestClose\n", window->Name);
7491 *p_open = false;
7492 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.
7493 }
7494
7495 // Title bar
7496 if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
7497 RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open);
7498
7499 // Clear hit test shape every frame
7500 window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
7501
7502 // Pressing CTRL+C while holding on a window copy its content to the clipboard
7503 // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
7504 // Maybe we can support CTRL+C on every element?
7505 /*
7506 //if (g.NavWindow == window && g.ActiveId == 0)
7507 if (g.ActiveId == window->MoveId)
7508 if (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_C))
7509 LogToClipboard();
7510 */
7511
7512 if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)
7513 {
7514 // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source.
7515 // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it.
7516 if (g.MovingWindow == window && (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoDocking) == 0)
7517 BeginDockableDragDropSource(window);
7518
7519 // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead.
7520 if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking))
7521 if (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != window)
7522 if ((window == window->RootWindowDockTree) && !(window->Flags & ImGuiWindowFlags_DockNodeHost))
7523 BeginDockableDragDropTarget(window);
7524 }
7525
7526 // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
7527 // This is useful to allow creating context menus on title bar only, etc.
7528 if (window->DockIsActive)
7529 SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DockTabItemStatusFlags, window->DockTabItemRect);
7530 else
7531 SetLastItemData(window->MoveId, g.CurrentItemFlags, IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, title_bar_rect);
7532
7533 // [DEBUG]
7534#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7535 if (g.DebugLocateId != 0 && (window->ID == g.DebugLocateId || window->MoveId == g.DebugLocateId))
7536 DebugLocateItemResolveWithLastItem();
7537#endif
7538
7539 // [Test Engine] Register title bar / tab with MoveId.
7540#ifdef IMGUI_ENABLE_TEST_ENGINE
7541 if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
7542 IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.ID, g.LastItemData.Rect, &g.LastItemData);
7543#endif
7544 }
7545 else
7546 {
7547 // Append
7548 SetCurrentViewport(window, window->Viewport);
7549 SetCurrentWindow(window);
7550 }
7551
7552 if (!(flags & ImGuiWindowFlags_DockNodeHost))
7553 PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
7554
7555 // 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)
7556 window->WriteAccessed = false;
7557 window->BeginCount++;
7558 g.NextWindowData.ClearFlags();
7559
7560 // Update visibility
7561 if (first_begin_of_the_frame)
7562 {
7563 // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems.
7564 // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents.
7565 // This is analogous to regular windows being hidden from one frame.
7566 // 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.
7567 if (window->DockIsActive && !window->DockTabIsVisible)
7568 {
7569 if (window->LastFrameJustFocused == g.FrameCount)
7570 window->HiddenFramesCannotSkipItems = 1;
7571 else
7572 window->HiddenFramesCanSkipItems = 1;
7573 }
7574
7575 if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ChildMenu))
7576 {
7577 // Child window can be out of sight and have "negative" clip windows.
7578 // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
7579 IM_ASSERT((flags& ImGuiWindowFlags_NoTitleBar) != 0 || window->DockIsActive);
7580 const bool nav_request = (flags & ImGuiWindowFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
7581 if (!g.LogEnabled && !nav_request)
7582 if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
7583 {
7584 if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7585 window->HiddenFramesCannotSkipItems = 1;
7586 else
7587 window->HiddenFramesCanSkipItems = 1;
7588 }
7589
7590 // Hide along with parent or if parent is collapsed
7591 if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
7592 window->HiddenFramesCanSkipItems = 1;
7593 if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
7594 window->HiddenFramesCannotSkipItems = 1;
7595 }
7596
7597 // 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)
7598 if (style.Alpha <= 0.0f)
7599 window->HiddenFramesCanSkipItems = 1;
7600
7601 // Update the Hidden flag
7602 bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
7603 window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
7604
7605 // Disable inputs for requested number of frames
7606 if (window->DisableInputsFrames > 0)
7607 {
7608 window->DisableInputsFrames--;
7609 window->Flags |= ImGuiWindowFlags_NoInputs;
7610 }
7611
7612 // Update the SkipItems flag, used to early out of all items functions (no layout required)
7613 bool skip_items = false;
7614 if (window->Collapsed || !window->Active || hidden_regular)
7615 if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
7616 skip_items = true;
7617 window->SkipItems = skip_items;
7618
7619 // Restore NavLayersActiveMaskNext to previous value when not visible, so a CTRL+Tab back can use a safe value.
7620 if (window->SkipItems)
7621 window->DC.NavLayersActiveMaskNext = window->DC.NavLayersActiveMask;
7622
7623 // Sanity check: there are two spots which can set Appearing = true
7624 // - when 'window_just_activated_by_user' is set -> HiddenFramesCannotSkipItems is set -> SkipItems always false
7625 // - in BeginDocked() path when DockNodeIsVisible == DockTabIsVisible == true -> hidden _should_ be all zero // FIXME: Not formally proven, hence the assert.
7626 if (window->SkipItems && !window->Appearing)
7627 IM_ASSERT(window->Appearing == false); // Please report on GitHub if this triggers: https://github.com/ocornut/imgui/issues/4177
7628 }
7629
7630 // [DEBUG] io.ConfigDebugBeginReturnValue override return value to test Begin/End and BeginChild/EndChild behaviors.
7631 // (The implicit fallback window is NOT automatically ended allowing it to always be able to receive commands without crashing)
7632#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7633 if (!window->IsFallbackWindow)
7634 if ((g.IO.ConfigDebugBeginReturnValueOnce && window_just_created) || (g.IO.ConfigDebugBeginReturnValueLoop && g.DebugBeginReturnValueCullDepth == g.CurrentWindowStack.Size))
7635 {
7636 if (window->AutoFitFramesX > 0) { window->AutoFitFramesX++; }
7637 if (window->AutoFitFramesY > 0) { window->AutoFitFramesY++; }
7638 return false;
7639 }
7640#endif
7641
7642 return !window->SkipItems;
7643}
7644
7645void ImGui::End()
7646{
7647 ImGuiContext& g = *GImGui;
7648 ImGuiWindow* window = g.CurrentWindow;
7649
7650 // Error checking: verify that user hasn't called End() too many times!
7651 if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
7652 {
7653 IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
7654 return;
7655 }
7656 IM_ASSERT(g.CurrentWindowStack.Size > 0);
7657
7658 // Error checking: verify that user doesn't directly call End() on a child window.
7659 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive)
7660 IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
7661
7662 // Close anything that is open
7663 if (window->DC.CurrentColumns)
7664 EndColumns();
7665 if (!(window->Flags & ImGuiWindowFlags_DockNodeHost)) // Pop inner window clip rectangle
7666 PopClipRect();
7667 PopFocusScope();
7668
7669 // Stop logging
7670 if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging
7671 LogFinish();
7672
7673 if (window->DC.IsSetPos)
7674 ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
7675
7676 // Docking: report contents sizes to parent to allow for auto-resize
7677 if (window->DockNode && window->DockTabIsVisible)
7678 if (ImGuiWindow* host_window = window->DockNode->HostWindow) // FIXME-DOCK
7679 host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding;
7680
7681 // Pop from window stack
7682 g.LastItemData = g.CurrentWindowStack.back().ParentLastItemDataBackup;
7683 if (window->Flags & ImGuiWindowFlags_ChildMenu)
7684 g.BeginMenuDepth--;
7685 if (window->Flags & ImGuiWindowFlags_Popup)
7686 g.BeginPopupStack.pop_back();
7687 g.CurrentWindowStack.back().StackSizesOnBegin.CompareWithContextState(&g);
7688 g.CurrentWindowStack.pop_back();
7689 SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
7690 if (g.CurrentWindow)
7691 SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport);
7692}
7693
7694void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
7695{
7696 ImGuiContext& g = *GImGui;
7697 IM_ASSERT(window == window->RootWindow);
7698
7699 const int cur_order = window->FocusOrder;
7700 IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
7701 if (g.WindowsFocusOrder.back() == window)
7702 return;
7703
7704 const int new_order = g.WindowsFocusOrder.Size - 1;
7705 for (int n = cur_order; n < new_order; n++)
7706 {
7707 g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
7708 g.WindowsFocusOrder[n]->FocusOrder--;
7709 IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
7710 }
7711 g.WindowsFocusOrder[new_order] = window;
7712 window->FocusOrder = (short)new_order;
7713}
7714
7715void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
7716{
7717 ImGuiContext& g = *GImGui;
7718 ImGuiWindow* current_front_window = g.Windows.back();
7719 if (current_front_window == window || current_front_window->RootWindowDockTree == window) // Cheap early out (could be better)
7720 return;
7721 for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
7722 if (g.Windows[i] == window)
7723 {
7724 memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
7725 g.Windows[g.Windows.Size - 1] = window;
7726 break;
7727 }
7728}
7729
7730void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
7731{
7732 ImGuiContext& g = *GImGui;
7733 if (g.Windows[0] == window)
7734 return;
7735 for (int i = 0; i < g.Windows.Size; i++)
7736 if (g.Windows[i] == window)
7737 {
7738 memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
7739 g.Windows[0] = window;
7740 break;
7741 }
7742}
7743
7744void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
7745{
7746 IM_ASSERT(window != NULL && behind_window != NULL);
7747 ImGuiContext& g = *GImGui;
7748 window = window->RootWindow;
7749 behind_window = behind_window->RootWindow;
7750 int pos_wnd = FindWindowDisplayIndex(window);
7751 int pos_beh = FindWindowDisplayIndex(behind_window);
7752 if (pos_wnd < pos_beh)
7753 {
7754 size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
7755 memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes);
7756 g.Windows[pos_beh - 1] = window;
7757 }
7758 else
7759 {
7760 size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
7761 memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes);
7762 g.Windows[pos_beh] = window;
7763 }
7764}
7765
7766int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
7767{
7768 ImGuiContext& g = *GImGui;
7769 return g.Windows.index_from_ptr(g.Windows.find(window));
7770}
7771
7772// Moving window to front of display and set focus (which happens to be back of our sorted list)
7773void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags)
7774{
7775 ImGuiContext& g = *GImGui;
7776
7777 // Modal check?
7778 if ((flags & ImGuiFocusRequestFlags_UnlessBelowModal) && (g.NavWindow != window)) // Early out in common case.
7779 if (ImGuiWindow* blocking_modal = FindBlockingModal(window))
7780 {
7781 IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".\n", window ? window->Name : "<NULL>", blocking_modal->Name);
7782 if (window && window == window->RootWindow && (window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7783 BringWindowToDisplayBehind(window, blocking_modal); // Still bring to right below modal.
7784 return;
7785 }
7786
7787 // Find last focused child (if any) and focus it instead.
7788 if ((flags & ImGuiFocusRequestFlags_RestoreFocusedChild) && window != NULL)
7789 window = NavRestoreLastChildNavWindow(window);
7790
7791 // Apply focus
7792 if (g.NavWindow != window)
7793 {
7794 SetNavWindow(window);
7795 if (window && g.NavDisableMouseHover)
7796 g.NavMousePosDirty = true;
7797 g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
7798 g.NavLayer = ImGuiNavLayer_Main;
7799 SetNavFocusScope(window ? window->NavRootFocusScopeId : 0);
7800 g.NavIdIsAlive = false;
7801 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
7802
7803 // Close popups if any
7804 ClosePopupsOverWindow(window, false);
7805 }
7806
7807 // Move the root window to the top of the pile
7808 IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL);
7809 ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL;
7810 ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL;
7811 ImGuiDockNode* dock_node = window ? window->DockNode : NULL;
7812 bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow);
7813
7814 // Steal active widgets. Some of the cases it triggers includes:
7815 // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
7816 // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
7817 // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window.
7818 if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
7819 if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host)
7820 ClearActiveID();
7821
7822 // Passing NULL allow to disable keyboard focus
7823 if (!window)
7824 return;
7825 window->LastFrameJustFocused = g.FrameCount;
7826
7827 // Select in dock node
7828 // For #2304 we avoid applying focus immediately before the tabbar is visible.
7829 //if (dock_node && dock_node->TabBar)
7830 // dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId;
7831
7832 // Bring to front
7833 BringWindowToFocusFront(focus_front_window);
7834 if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7835 BringWindowToDisplayFront(display_front_window);
7836}
7837
7838void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags)
7839{
7840 ImGuiContext& g = *GImGui;
7841 int start_idx = g.WindowsFocusOrder.Size - 1;
7842 if (under_this_window != NULL)
7843 {
7844 // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
7845 int offset = -1;
7846 while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
7847 {
7848 under_this_window = under_this_window->ParentWindow;
7849 offset = 0;
7850 }
7851 start_idx = FindWindowFocusIndex(under_this_window) + offset;
7852 }
7853 for (int i = start_idx; i >= 0; i--)
7854 {
7855 // 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.
7856 ImGuiWindow* window = g.WindowsFocusOrder[i];
7857 if (window == ignore_window || !window->WasActive)
7858 continue;
7859 if (filter_viewport != NULL && window->Viewport != filter_viewport)
7860 continue;
7861 if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
7862 {
7863 // FIXME-DOCK: When ImGuiFocusRequestFlags_RestoreFocusedChild is set...
7864 // This is failing (lagging by one frame) for docked windows.
7865 // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B.
7866 // 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)
7867 // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself?
7868 FocusWindow(window, flags);
7869 return;
7870 }
7871 }
7872 FocusWindow(NULL, flags);
7873}
7874
7875// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.
7876void ImGui::SetCurrentFont(ImFont* font)
7877{
7878 ImGuiContext& g = *GImGui;
7879 IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
7880 IM_ASSERT(font->Scale > 0.0f);
7881 g.Font = font;
7882 g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
7883 g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
7884
7885 ImFontAtlas* atlas = g.Font->ContainerAtlas;
7886 g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
7887 g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
7888 g.DrawListSharedData.Font = g.Font;
7889 g.DrawListSharedData.FontSize = g.FontSize;
7890}
7891
7892void ImGui::PushFont(ImFont* font)
7893{
7894 ImGuiContext& g = *GImGui;
7895 if (!font)
7896 font = GetDefaultFont();
7897 SetCurrentFont(font);
7898 g.FontStack.push_back(font);
7899 g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
7900}
7901
7902void ImGui::PopFont()
7903{
7904 ImGuiContext& g = *GImGui;
7905 g.CurrentWindow->DrawList->PopTextureID();
7906 g.FontStack.pop_back();
7907 SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
7908}
7909
7910void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
7911{
7912 ImGuiContext& g = *GImGui;
7913 ImGuiItemFlags item_flags = g.CurrentItemFlags;
7914 IM_ASSERT(item_flags == g.ItemFlagsStack.back());
7915 if (enabled)
7916 item_flags |= option;
7917 else
7918 item_flags &= ~option;
7919 g.CurrentItemFlags = item_flags;
7920 g.ItemFlagsStack.push_back(item_flags);
7921}
7922
7923void ImGui::PopItemFlag()
7924{
7925 ImGuiContext& g = *GImGui;
7926 IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.
7927 g.ItemFlagsStack.pop_back();
7928 g.CurrentItemFlags = g.ItemFlagsStack.back();
7929}
7930
7931// BeginDisabled()/EndDisabled()
7932// - 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)
7933// - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
7934// - Feedback welcome at https://github.com/ocornut/imgui/issues/211
7935// - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it.
7936// - Optimized shortcuts instead of PushStyleVar() + PushItemFlag()
7937void ImGui::BeginDisabled(bool disabled)
7938{
7939 ImGuiContext& g = *GImGui;
7940 bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7941 if (!was_disabled && disabled)
7942 {
7943 g.DisabledAlphaBackup = g.Style.Alpha;
7944 g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
7945 }
7946 if (was_disabled || disabled)
7947 g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
7948 g.ItemFlagsStack.push_back(g.CurrentItemFlags);
7949 g.DisabledStackSize++;
7950}
7951
7952void ImGui::EndDisabled()
7953{
7954 ImGuiContext& g = *GImGui;
7955 IM_ASSERT(g.DisabledStackSize > 0);
7956 g.DisabledStackSize--;
7957 bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7958 //PopItemFlag();
7959 g.ItemFlagsStack.pop_back();
7960 g.CurrentItemFlags = g.ItemFlagsStack.back();
7961 if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
7962 g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
7963}
7964
7965void ImGui::PushTabStop(bool tab_stop)
7966{
7967 PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop);
7968}
7969
7970void ImGui::PopTabStop()
7971{
7972 PopItemFlag();
7973}
7974
7975void ImGui::PushButtonRepeat(bool repeat)
7976{
7977 PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
7978}
7979
7980void ImGui::PopButtonRepeat()
7981{
7982 PopItemFlag();
7983}
7984
7985void ImGui::PushTextWrapPos(float wrap_pos_x)
7986{
7987 ImGuiWindow* window = GetCurrentWindow();
7988 window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
7989 window->DC.TextWrapPos = wrap_pos_x;
7990}
7991
7992void ImGui::PopTextWrapPos()
7993{
7994 ImGuiWindow* window = GetCurrentWindow();
7995 window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
7996 window->DC.TextWrapPosStack.pop_back();
7997}
7998
7999static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy, bool dock_hierarchy)
8000{
8001 ImGuiWindow* last_window = NULL;
8002 while (last_window != window)
8003 {
8004 last_window = window;
8005 window = window->RootWindow;
8006 if (popup_hierarchy)
8007 window = window->RootWindowPopupTree;
8008 if (dock_hierarchy)
8009 window = window->RootWindowDockTree;
8010 }
8011 return window;
8012}
8013
8014bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy, bool dock_hierarchy)
8015{
8016 ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy);
8017 if (window_root == potential_parent)
8018 return true;
8019 while (window != NULL)
8020 {
8021 if (window == potential_parent)
8022 return true;
8023 if (window == window_root) // end of chain
8024 return false;
8025 window = window->ParentWindow;
8026 }
8027 return false;
8028}
8029
8030bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
8031{
8032 if (window->RootWindow == potential_parent)
8033 return true;
8034 while (window != NULL)
8035 {
8036 if (window == potential_parent)
8037 return true;
8038 window = window->ParentWindowInBeginStack;
8039 }
8040 return false;
8041}
8042
8043bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
8044{
8045 ImGuiContext& g = *GImGui;
8046
8047 // 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
8048 const int display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below);
8049 if (display_layer_delta != 0)
8050 return display_layer_delta > 0;
8051
8052 for (int i = g.Windows.Size - 1; i >= 0; i--)
8053 {
8054 ImGuiWindow* candidate_window = g.Windows[i];
8055 if (candidate_window == potential_above)
8056 return true;
8057 if (candidate_window == potential_below)
8058 return false;
8059 }
8060 return false;
8061}
8062
8063// Is current window hovered and hoverable (e.g. not blocked by a popup/modal)? See ImGuiHoveredFlags_ for options.
8064// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
8065// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
8066// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
8067bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
8068{
8069 IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsWindowHovered) == 0 && "Invalid flags for IsWindowHovered()!");
8070
8071 ImGuiContext& g = *GImGui;
8072 ImGuiWindow* ref_window = g.HoveredWindow;
8073 ImGuiWindow* cur_window = g.CurrentWindow;
8074 if (ref_window == NULL)
8075 return false;
8076
8077 if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
8078 {
8079 IM_ASSERT(cur_window); // Not inside a Begin()/End()
8080 const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
8081 const bool dock_hierarchy = (flags & ImGuiHoveredFlags_DockHierarchy) != 0;
8082 if (flags & ImGuiHoveredFlags_RootWindow)
8083 cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
8084
8085 bool result;
8086 if (flags & ImGuiHoveredFlags_ChildWindows)
8087 result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
8088 else
8089 result = (ref_window == cur_window);
8090 if (!result)
8091 return false;
8092 }
8093
8094 if (!IsWindowContentHoverable(ref_window, flags))
8095 return false;
8096 if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
8097 if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
8098 return false;
8099
8100 // When changing hovered window we requires a bit of stationary delay before activating hover timer.
8101 // FIXME: We don't support delay other than stationary one for now, other delay would need a way
8102 // to fullfill the possibility that multiple IsWindowHovered() with varying flag could return true
8103 // for different windows of the hierarchy. Possibly need a Hash(Current+Flags) ==> (Timer) cache.
8104 // We can implement this for _Stationary because the data is linked to HoveredWindow rather than CurrentWindow.
8105 if (flags & ImGuiHoveredFlags_ForTooltip)
8106 flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
8107 if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverWindowUnlockedStationaryId != ref_window->ID)
8108 return false;
8109
8110 return true;
8111}
8112
8113bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
8114{
8115 ImGuiContext& g = *GImGui;
8116 ImGuiWindow* ref_window = g.NavWindow;
8117 ImGuiWindow* cur_window = g.CurrentWindow;
8118
8119 if (ref_window == NULL)
8120 return false;
8121 if (flags & ImGuiFocusedFlags_AnyWindow)
8122 return true;
8123
8124 IM_ASSERT(cur_window); // Not inside a Begin()/End()
8125 const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
8126 const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0;
8127 if (flags & ImGuiHoveredFlags_RootWindow)
8128 cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
8129
8130 if (flags & ImGuiHoveredFlags_ChildWindows)
8131 return IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
8132 else
8133 return (ref_window == cur_window);
8134}
8135
8136ImGuiID ImGui::GetWindowDockID()
8137{
8138 ImGuiContext& g = *GImGui;
8139 return g.CurrentWindow->DockId;
8140}
8141
8142bool ImGui::IsWindowDocked()
8143{
8144 ImGuiContext& g = *GImGui;
8145 return g.CurrentWindow->DockIsActive;
8146}
8147
8148// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
8149// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
8150// If you want a window to never be focused, you may use the e.g. NoInputs flag.
8151bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
8152{
8153 return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
8154}
8155
8156float ImGui::GetWindowWidth()
8157{
8158 ImGuiWindow* window = GImGui->CurrentWindow;
8159 return window->Size.x;
8160}
8161
8162float ImGui::GetWindowHeight()
8163{
8164 ImGuiWindow* window = GImGui->CurrentWindow;
8165 return window->Size.y;
8166}
8167
8168ImVec2 ImGui::GetWindowPos()
8169{
8170 ImGuiContext& g = *GImGui;
8171 ImGuiWindow* window = g.CurrentWindow;
8172 return window->Pos;
8173}
8174
8175void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
8176{
8177 // Test condition (NB: bit 0 is always true) and clear flags for next time
8178 if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
8179 return;
8180
8181 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8182 window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8183 window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
8184
8185 // Set
8186 const ImVec2 old_pos = window->Pos;
8187 window->Pos = ImTrunc(pos);
8188 ImVec2 offset = window->Pos - old_pos;
8189 if (offset.x == 0.0f && offset.y == 0.0f)
8190 return;
8191 MarkIniSettingsDirty(window);
8192 // FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here.
8193 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
8194 window->DC.CursorMaxPos += offset; // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
8195 window->DC.IdealMaxPos += offset;
8196 window->DC.CursorStartPos += offset;
8197}
8198
8199void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
8200{
8201 ImGuiWindow* window = GetCurrentWindowRead();
8202 SetWindowPos(window, pos, cond);
8203}
8204
8205void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
8206{
8207 if (ImGuiWindow* window = FindWindowByName(name))
8208 SetWindowPos(window, pos, cond);
8209}
8210
8211ImVec2 ImGui::GetWindowSize()
8212{
8213 ImGuiWindow* window = GetCurrentWindowRead();
8214 return window->Size;
8215}
8216
8217void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
8218{
8219 // Test condition (NB: bit 0 is always true) and clear flags for next time
8220 if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
8221 return;
8222
8223 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8224 window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8225
8226 // Enable auto-fit (not done in BeginChild() path unless appearing or combined with ImGuiChildFlags_AlwaysAutoResize)
8227 if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8228 window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0;
8229 if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8230 window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0;
8231
8232 // Set
8233 ImVec2 old_size = window->SizeFull;
8234 if (size.x <= 0.0f)
8235 window->AutoFitOnlyGrows = false;
8236 else
8237 window->SizeFull.x = IM_TRUNC(size.x);
8238 if (size.y <= 0.0f)
8239 window->AutoFitOnlyGrows = false;
8240 else
8241 window->SizeFull.y = IM_TRUNC(size.y);
8242 if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
8243 MarkIniSettingsDirty(window);
8244}
8245
8246void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
8247{
8248 SetWindowSize(GImGui->CurrentWindow, size, cond);
8249}
8250
8251void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
8252{
8253 if (ImGuiWindow* window = FindWindowByName(name))
8254 SetWindowSize(window, size, cond);
8255}
8256
8257void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
8258{
8259 // Test condition (NB: bit 0 is always true) and clear flags for next time
8260 if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
8261 return;
8262 window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8263
8264 // Set
8265 window->Collapsed = collapsed;
8266}
8267
8268void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
8269{
8270 IM_ASSERT(window->HitTestHoleSize.x == 0); // We don't support multiple holes/hit test filters
8271 window->HitTestHoleSize = ImVec2ih(size);
8272 window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
8273}
8274
8275void ImGui::SetWindowHiddenAndSkipItemsForCurrentFrame(ImGuiWindow* window)
8276{
8277 window->Hidden = window->SkipItems = true;
8278 window->HiddenFramesCanSkipItems = 1;
8279}
8280
8281void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
8282{
8283 SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
8284}
8285
8286bool ImGui::IsWindowCollapsed()
8287{
8288 ImGuiWindow* window = GetCurrentWindowRead();
8289 return window->Collapsed;
8290}
8291
8292bool ImGui::IsWindowAppearing()
8293{
8294 ImGuiWindow* window = GetCurrentWindowRead();
8295 return window->Appearing;
8296}
8297
8298void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
8299{
8300 if (ImGuiWindow* window = FindWindowByName(name))
8301 SetWindowCollapsed(window, collapsed, cond);
8302}
8303
8304void ImGui::SetWindowFocus()
8305{
8306 FocusWindow(GImGui->CurrentWindow);
8307}
8308
8309void ImGui::SetWindowFocus(const char* name)
8310{
8311 if (name)
8312 {
8313 if (ImGuiWindow* window = FindWindowByName(name))
8314 FocusWindow(window);
8315 }
8316 else
8317 {
8318 FocusWindow(NULL);
8319 }
8320}
8321
8322void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
8323{
8324 ImGuiContext& g = *GImGui;
8325 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8326 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
8327 g.NextWindowData.PosVal = pos;
8328 g.NextWindowData.PosPivotVal = pivot;
8329 g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
8330 g.NextWindowData.PosUndock = true;
8331}
8332
8333void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
8334{
8335 ImGuiContext& g = *GImGui;
8336 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8337 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
8338 g.NextWindowData.SizeVal = size;
8339 g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
8340}
8341
8342// For each axis:
8343// - 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.
8344// - Use -1 for both min and max of same axis to preserve current size which itself is a constraint.
8345// - See "Demo->Examples->Constrained-resizing window" for examples.
8346void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
8347{
8348 ImGuiContext& g = *GImGui;
8349 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
8350 g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
8351 g.NextWindowData.SizeCallback = custom_callback;
8352 g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
8353}
8354
8355// Content size = inner scrollable rectangle, padded with WindowPadding.
8356// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
8357void ImGui::SetNextWindowContentSize(const ImVec2& size)
8358{
8359 ImGuiContext& g = *GImGui;
8360 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
8361 g.NextWindowData.ContentSizeVal = ImTrunc(size);
8362}
8363
8364void ImGui::SetNextWindowScroll(const ImVec2& scroll)
8365{
8366 ImGuiContext& g = *GImGui;
8367 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
8368 g.NextWindowData.ScrollVal = scroll;
8369}
8370
8371void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
8372{
8373 ImGuiContext& g = *GImGui;
8374 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8375 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
8376 g.NextWindowData.CollapsedVal = collapsed;
8377 g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
8378}
8379
8380void ImGui::SetNextWindowFocus()
8381{
8382 ImGuiContext& g = *GImGui;
8383 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
8384}
8385
8386void ImGui::SetNextWindowBgAlpha(float alpha)
8387{
8388 ImGuiContext& g = *GImGui;
8389 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
8390 g.NextWindowData.BgAlphaVal = alpha;
8391}
8392
8393void ImGui::SetNextWindowViewport(ImGuiID id)
8394{
8395 ImGuiContext& g = *GImGui;
8396 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasViewport;
8397 g.NextWindowData.ViewportId = id;
8398}
8399
8400void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
8401{
8402 ImGuiContext& g = *GImGui;
8403 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasDock;
8404 g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
8405 g.NextWindowData.DockId = id;
8406}
8407
8408void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
8409{
8410 ImGuiContext& g = *GImGui;
8411 IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit
8412 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasWindowClass;
8413 g.NextWindowData.WindowClass = *window_class;
8414}
8415
8416ImDrawList* ImGui::GetWindowDrawList()
8417{
8418 ImGuiWindow* window = GetCurrentWindow();
8419 return window->DrawList;
8420}
8421
8422float ImGui::GetWindowDpiScale()
8423{
8424 ImGuiContext& g = *GImGui;
8425 return g.CurrentDpiScale;
8426}
8427
8428ImGuiViewport* ImGui::GetWindowViewport()
8429{
8430 ImGuiContext& g = *GImGui;
8431 IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport);
8432 return g.CurrentViewport;
8433}
8434
8435ImFont* ImGui::GetFont()
8436{
8437 return GImGui->Font;
8438}
8439
8440float ImGui::GetFontSize()
8441{
8442 return GImGui->FontSize;
8443}
8444
8445ImVec2 ImGui::GetFontTexUvWhitePixel()
8446{
8447 return GImGui->DrawListSharedData.TexUvWhitePixel;
8448}
8449
8450void ImGui::SetWindowFontScale(float scale)
8451{
8452 IM_ASSERT(scale > 0.0f);
8453 ImGuiContext& g = *GImGui;
8454 ImGuiWindow* window = GetCurrentWindow();
8455 window->FontWindowScale = scale;
8456 g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
8457}
8458
8459void ImGui::PushFocusScope(ImGuiID id)
8460{
8461 ImGuiContext& g = *GImGui;
8462 ImGuiFocusScopeData data;
8463 data.ID = id;
8464 data.WindowID = g.CurrentWindow->ID;
8465 g.FocusScopeStack.push_back(data);
8466 g.CurrentFocusScopeId = id;
8467}
8468
8469void ImGui::PopFocusScope()
8470{
8471 ImGuiContext& g = *GImGui;
8472 if (g.FocusScopeStack.Size == 0)
8473 {
8474 IM_ASSERT_USER_ERROR(g.FocusScopeStack.Size > 0, "Calling PopFocusScope() too many times!");
8475 return;
8476 }
8477 g.FocusScopeStack.pop_back();
8478 g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back().ID : 0;
8479}
8480
8481void ImGui::SetNavFocusScope(ImGuiID focus_scope_id)
8482{
8483 ImGuiContext& g = *GImGui;
8484 g.NavFocusScopeId = focus_scope_id;
8485 g.NavFocusRoute.resize(0); // Invalidate
8486 if (focus_scope_id == 0)
8487 return;
8488 IM_ASSERT(g.NavWindow != NULL);
8489
8490 // Store current path (in reverse order)
8491 if (focus_scope_id == g.CurrentFocusScopeId)
8492 {
8493 // Top of focus stack contains local focus scopes inside current window
8494 for (int n = g.FocusScopeStack.Size - 1; n >= 0 && g.FocusScopeStack.Data[n].WindowID == g.CurrentWindow->ID; n--)
8495 g.NavFocusRoute.push_back(g.FocusScopeStack.Data[n]);
8496 }
8497 else if (focus_scope_id == g.NavWindow->NavRootFocusScopeId)
8498 g.NavFocusRoute.push_back({ focus_scope_id, g.NavWindow->ID });
8499 else
8500 return;
8501
8502 // Then follow on manually set ParentWindowForFocusRoute field (#6798)
8503 for (ImGuiWindow* window = g.NavWindow->ParentWindowForFocusRoute; window != NULL; window = window->ParentWindowForFocusRoute)
8504 g.NavFocusRoute.push_back({ window->NavRootFocusScopeId, window->ID });
8505 IM_ASSERT(g.NavFocusRoute.Size < 100); // Maximum depth is technically 251 as per CalcRoutingScore(): 254 - 3
8506}
8507
8508// Focus = move navigation cursor, set scrolling, set focus window.
8509void ImGui::FocusItem()
8510{
8511 ImGuiContext& g = *GImGui;
8512 ImGuiWindow* window = g.CurrentWindow;
8513 IMGUI_DEBUG_LOG_FOCUS("FocusItem(0x%08x) in window \"%s\"\n", g.LastItemData.ID, window->Name);
8514 if (g.DragDropActive || g.MovingWindow != NULL) // FIXME: Opt-in flags for this?
8515 {
8516 IMGUI_DEBUG_LOG_FOCUS("FocusItem() ignored while DragDropActive!\n");
8517 return;
8518 }
8519
8520 ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight | ImGuiNavMoveFlags_NoSelect;
8521 ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8522 SetNavWindow(window);
8523 NavMoveRequestSubmit(ImGuiDir_None, ImGuiDir_Up, move_flags, scroll_flags);
8524 NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8525}
8526
8527void ImGui::ActivateItemByID(ImGuiID id)
8528{
8529 ImGuiContext& g = *GImGui;
8530 g.NavNextActivateId = id;
8531 g.NavNextActivateFlags = ImGuiActivateFlags_None;
8532}
8533
8534// Note: this will likely be called ActivateItem() once we rework our Focus/Activation system!
8535// But ActivateItem() should function without altering scroll/focus?
8536void ImGui::SetKeyboardFocusHere(int offset)
8537{
8538 ImGuiContext& g = *GImGui;
8539 ImGuiWindow* window = g.CurrentWindow;
8540 IM_ASSERT(offset >= -1); // -1 is allowed but not below
8541 IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name);
8542
8543 // It makes sense in the vast majority of cases to never interrupt a drag and drop.
8544 // When we refactor this function into ActivateItem() we may want to make this an option.
8545 // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but
8546 // is also automatically dropped in the event g.ActiveId is stolen.
8547 if (g.DragDropActive || g.MovingWindow != NULL)
8548 {
8549 IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere() ignored while DragDropActive!\n");
8550 return;
8551 }
8552
8553 SetNavWindow(window);
8554
8555 ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight;
8556 ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8557 NavMoveRequestSubmit(ImGuiDir_None, offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
8558 if (offset == -1)
8559 {
8560 NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8561 }
8562 else
8563 {
8564 g.NavTabbingDir = 1;
8565 g.NavTabbingCounter = offset + 1;
8566 }
8567}
8568
8569void ImGui::SetItemDefaultFocus()
8570{
8571 ImGuiContext& g = *GImGui;
8572 ImGuiWindow* window = g.CurrentWindow;
8573 if (!window->Appearing)
8574 return;
8575 if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResult.ID == 0) || g.NavLayer != window->DC.NavLayerCurrent)
8576 return;
8577
8578 g.NavInitRequest = false;
8579 NavApplyItemToResult(&g.NavInitResult);
8580 NavUpdateAnyRequestFlag();
8581
8582 // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll)
8583 if (!window->ClipRect.Contains(g.LastItemData.Rect))
8584 ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None);
8585}
8586
8587void ImGui::SetStateStorage(ImGuiStorage* tree)
8588{
8589 ImGuiWindow* window = GImGui->CurrentWindow;
8590 window->DC.StateStorage = tree ? tree : &window->StateStorage;
8591}
8592
8593ImGuiStorage* ImGui::GetStateStorage()
8594{
8595 ImGuiWindow* window = GImGui->CurrentWindow;
8596 return window->DC.StateStorage;
8597}
8598
8599void ImGui::PushID(const char* str_id)
8600{
8601 ImGuiContext& g = *GImGui;
8602 ImGuiWindow* window = g.CurrentWindow;
8603 ImGuiID id = window->GetID(str_id);
8604 window->IDStack.push_back(id);
8605}
8606
8607void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
8608{
8609 ImGuiContext& g = *GImGui;
8610 ImGuiWindow* window = g.CurrentWindow;
8611 ImGuiID id = window->GetID(str_id_begin, str_id_end);
8612 window->IDStack.push_back(id);
8613}
8614
8615void ImGui::PushID(const void* ptr_id)
8616{
8617 ImGuiContext& g = *GImGui;
8618 ImGuiWindow* window = g.CurrentWindow;
8619 ImGuiID id = window->GetID(ptr_id);
8620 window->IDStack.push_back(id);
8621}
8622
8623void ImGui::PushID(int int_id)
8624{
8625 ImGuiContext& g = *GImGui;
8626 ImGuiWindow* window = g.CurrentWindow;
8627 ImGuiID id = window->GetID(int_id);
8628 window->IDStack.push_back(id);
8629}
8630
8631// Push a given id value ignoring the ID stack as a seed.
8632void ImGui::PushOverrideID(ImGuiID id)
8633{
8634 ImGuiContext& g = *GImGui;
8635 ImGuiWindow* window = g.CurrentWindow;
8636 if (g.DebugHookIdInfo == id)
8637 DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL);
8638 window->IDStack.push_back(id);
8639}
8640
8641// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
8642// (note that when using this pattern, ID Stack Tool will tend to not display the intermediate stack level.
8643// for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
8644ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
8645{
8646 ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
8647 ImGuiContext& g = *GImGui;
8648 if (g.DebugHookIdInfo == id)
8649 DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
8650 return id;
8651}
8652
8653ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed)
8654{
8655 ImGuiID id = ImHashData(&n, sizeof(n), seed);
8656 ImGuiContext& g = *GImGui;
8657 if (g.DebugHookIdInfo == id)
8658 DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
8659 return id;
8660}
8661
8662void ImGui::PopID()
8663{
8664 ImGuiWindow* window = GImGui->CurrentWindow;
8665 IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?
8666 window->IDStack.pop_back();
8667}
8668
8669ImGuiID ImGui::GetID(const char* str_id)
8670{
8671 ImGuiWindow* window = GImGui->CurrentWindow;
8672 return window->GetID(str_id);
8673}
8674
8675ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
8676{
8677 ImGuiWindow* window = GImGui->CurrentWindow;
8678 return window->GetID(str_id_begin, str_id_end);
8679}
8680
8681ImGuiID ImGui::GetID(const void* ptr_id)
8682{
8683 ImGuiWindow* window = GImGui->CurrentWindow;
8684 return window->GetID(ptr_id);
8685}
8686
8687bool ImGui::IsRectVisible(const ImVec2& size)
8688{
8689 ImGuiWindow* window = GImGui->CurrentWindow;
8690 return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
8691}
8692
8693bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
8694{
8695 ImGuiWindow* window = GImGui->CurrentWindow;
8696 return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
8697}
8698
8699
8700//-----------------------------------------------------------------------------
8701// [SECTION] INPUTS
8702//-----------------------------------------------------------------------------
8703// - GetKeyData() [Internal]
8704// - GetKeyIndex() [Internal]
8705// - GetKeyName()
8706// - GetKeyChordName() [Internal]
8707// - CalcTypematicRepeatAmount() [Internal]
8708// - GetTypematicRepeatRate() [Internal]
8709// - GetKeyPressedAmount() [Internal]
8710// - GetKeyMagnitude2d() [Internal]
8711//-----------------------------------------------------------------------------
8712// - UpdateKeyRoutingTable() [Internal]
8713// - GetRoutingIdFromOwnerId() [Internal]
8714// - GetShortcutRoutingData() [Internal]
8715// - CalcRoutingScore() [Internal]
8716// - SetShortcutRouting() [Internal]
8717// - TestShortcutRouting() [Internal]
8718//-----------------------------------------------------------------------------
8719// - IsKeyDown()
8720// - IsKeyPressed()
8721// - IsKeyReleased()
8722//-----------------------------------------------------------------------------
8723// - IsMouseDown()
8724// - IsMouseClicked()
8725// - IsMouseReleased()
8726// - IsMouseDoubleClicked()
8727// - GetMouseClickedCount()
8728// - IsMouseHoveringRect() [Internal]
8729// - IsMouseDragPastThreshold() [Internal]
8730// - IsMouseDragging()
8731// - GetMousePos()
8732// - SetMousePos() [Internal]
8733// - GetMousePosOnOpeningCurrentPopup()
8734// - IsMousePosValid()
8735// - IsAnyMouseDown()
8736// - GetMouseDragDelta()
8737// - ResetMouseDragDelta()
8738// - GetMouseCursor()
8739// - SetMouseCursor()
8740//-----------------------------------------------------------------------------
8741// - UpdateAliasKey()
8742// - GetMergedModsFromKeys()
8743// - UpdateKeyboardInputs()
8744// - UpdateMouseInputs()
8745//-----------------------------------------------------------------------------
8746// - LockWheelingWindow [Internal]
8747// - FindBestWheelingWindow [Internal]
8748// - UpdateMouseWheel() [Internal]
8749//-----------------------------------------------------------------------------
8750// - SetNextFrameWantCaptureKeyboard()
8751// - SetNextFrameWantCaptureMouse()
8752//-----------------------------------------------------------------------------
8753// - GetInputSourceName() [Internal]
8754// - DebugPrintInputEvent() [Internal]
8755// - UpdateInputEvents() [Internal]
8756//-----------------------------------------------------------------------------
8757// - GetKeyOwner() [Internal]
8758// - TestKeyOwner() [Internal]
8759// - SetKeyOwner() [Internal]
8760// - SetItemKeyOwner() [Internal]
8761// - Shortcut() [Internal]
8762//-----------------------------------------------------------------------------
8763
8764ImGuiKeyChord ImGui::FixupKeyChord(ImGuiContext* ctx, ImGuiKeyChord key_chord)
8765{
8766 // Convert ImGuiMod_Shortcut and add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
8767 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
8768 if (IsModKey(key))
8769 {
8770 if (key == ImGuiKey_LeftCtrl || key == ImGuiKey_RightCtrl)
8771 key_chord |= ImGuiMod_Ctrl;
8772 if (key == ImGuiKey_LeftShift || key == ImGuiKey_RightShift)
8773 key_chord |= ImGuiMod_Shift;
8774 if (key == ImGuiKey_LeftAlt || key == ImGuiKey_RightAlt)
8775 key_chord |= ImGuiMod_Alt;
8776 if (key == ImGuiKey_LeftSuper || key == ImGuiKey_RightSuper)
8777 key_chord |= ImGuiMod_Super;
8778 }
8779 if (key_chord & ImGuiMod_Shortcut)
8780 return (key_chord & ~ImGuiMod_Shortcut) | (ctx->IO.ConfigMacOSXBehaviors ? ImGuiMod_Super : ImGuiMod_Ctrl);
8781 return key_chord;
8782}
8783
8784ImGuiKeyData* ImGui::GetKeyData(ImGuiContext* ctx, ImGuiKey key)
8785{
8786 ImGuiContext& g = *ctx;
8787
8788 // Special storage location for mods
8789 if (key & ImGuiMod_Mask_)
8790 key = ConvertSingleModFlagToKey(ctx, key);
8791
8792#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8793 IM_ASSERT(key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_NamedKey_END);
8794 if (IsLegacyKey(key) && g.IO.KeyMap[key] != -1)
8795 key = (ImGuiKey)g.IO.KeyMap[key]; // Remap native->imgui or imgui->native
8796#else
8797 IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
8798#endif
8799 return &g.IO.KeysData[key - ImGuiKey_KeysData_OFFSET];
8800}
8801
8802#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8803ImGuiKey ImGui::GetKeyIndex(ImGuiKey key)
8804{
8805 ImGuiContext& g = *GImGui;
8806 IM_ASSERT(IsNamedKey(key));
8807 const ImGuiKeyData* key_data = GetKeyData(key);
8808 return (ImGuiKey)(key_data - g.IO.KeysData);
8809}
8810#endif
8811
8812// Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
8813static const char* const GKeyNames[] =
8814{
8815 "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
8816 "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
8817 "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu",
8818 "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
8819 "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
8820 "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
8821 "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22", "F23", "F24",
8822 "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
8823 "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
8824 "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
8825 "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
8826 "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
8827 "AppBack", "AppForward",
8828 "GamepadStart", "GamepadBack",
8829 "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
8830 "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
8831 "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3",
8832 "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown",
8833 "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown",
8834 "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY",
8835 "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names.
8836};
8837IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));
8838
8839const char* ImGui::GetKeyName(ImGuiKey key)
8840{
8841 ImGuiContext& g = *GImGui;
8842#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
8843 IM_ASSERT((IsNamedKeyOrModKey(key) || key == ImGuiKey_None) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
8844#else
8845 if (IsLegacyKey(key))
8846 {
8847 if (g.IO.KeyMap[key] == -1)
8848 return "N/A";
8849 IM_ASSERT(IsNamedKey((ImGuiKey)g.IO.KeyMap[key]));
8850 key = (ImGuiKey)g.IO.KeyMap[key];
8851 }
8852#endif
8853 if (key == ImGuiKey_None)
8854 return "None";
8855 if (key & ImGuiMod_Mask_)
8856 key = ConvertSingleModFlagToKey(&g, key);
8857 if (!IsNamedKey(key))
8858 return "Unknown";
8859
8860 return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
8861}
8862
8863// ImGuiMod_Shortcut is translated to either Ctrl or Super.
8864const char* ImGui::GetKeyChordName(ImGuiKeyChord key_chord)
8865{
8866 ImGuiContext& g = *GImGui;
8867 key_chord = FixupKeyChord(&g, key_chord);
8868 ImFormatString(g.TempKeychordName, IM_ARRAYSIZE(g.TempKeychordName), "%s%s%s%s%s",
8869 (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "",
8870 (key_chord & ImGuiMod_Shift) ? "Shift+" : "",
8871 (key_chord & ImGuiMod_Alt) ? "Alt+" : "",
8872 (key_chord & ImGuiMod_Super) ? (g.IO.ConfigMacOSXBehaviors ? "Cmd+" : "Super+") : "",
8873 GetKeyName((ImGuiKey)(key_chord & ~ImGuiMod_Mask_)));
8874 return g.TempKeychordName;
8875}
8876
8877// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
8878// t1 = current time (e.g.: g.Time)
8879// An event is triggered at:
8880// t = 0.0f t = repeat_delay, t = repeat_delay + repeat_rate*N
8881int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
8882{
8883 if (t1 == 0.0f)
8884 return 1;
8885 if (t0 >= t1)
8886 return 0;
8887 if (repeat_rate <= 0.0f)
8888 return (t0 < repeat_delay) && (t1 >= repeat_delay);
8889 const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
8890 const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
8891 const int count = count_t1 - count_t0;
8892 return count;
8893}
8894
8895void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate)
8896{
8897 ImGuiContext& g = *GImGui;
8898 switch (flags & ImGuiInputFlags_RepeatRateMask_)
8899 {
8900 case ImGuiInputFlags_RepeatRateNavMove: *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return;
8901 case ImGuiInputFlags_RepeatRateNavTweak: *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return;
8902 case ImGuiInputFlags_RepeatRateDefault: default: *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return;
8903 }
8904}
8905
8906// Return value representing the number of presses in the last time period, for the given repeat rate
8907// (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate)
8908int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
8909{
8910 ImGuiContext& g = *GImGui;
8911 const ImGuiKeyData* key_data = GetKeyData(key);
8912 if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8913 return 0;
8914 const float t = key_data->DownDuration;
8915 return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
8916}
8917
8918// Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values).
8919ImVec2 ImGui::GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down)
8920{
8921 return ImVec2(
8922 GetKeyData(key_right)->AnalogValue - GetKeyData(key_left)->AnalogValue,
8923 GetKeyData(key_down)->AnalogValue - GetKeyData(key_up)->AnalogValue);
8924}
8925
8926// Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data.
8927// Entries D,A,B,B,A,C,B --> A,A,B,B,B,C,D
8928// Index A:1 B:2 C:5 D:0 --> A:0 B:2 C:5 D:6
8929// See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation.
8930static void ImGui::UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt)
8931{
8932 ImGuiContext& g = *GImGui;
8933 rt->EntriesNext.resize(0);
8934 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
8935 {
8936 const int new_routing_start_idx = rt->EntriesNext.Size;
8937 ImGuiKeyRoutingData* routing_entry;
8938 for (int old_routing_idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; old_routing_idx != -1; old_routing_idx = routing_entry->NextEntryIndex)
8939 {
8940 routing_entry = &rt->Entries[old_routing_idx];
8941 routing_entry->RoutingCurrScore = routing_entry->RoutingNextScore;
8942 routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry
8943 routing_entry->RoutingNext = ImGuiKeyOwner_None;
8944 routing_entry->RoutingNextScore = 255;
8945 if (routing_entry->RoutingCurr == ImGuiKeyOwner_None)
8946 continue;
8947 rt->EntriesNext.push_back(*routing_entry); // Write alive ones into new buffer
8948
8949 // Apply routing to owner if there's no owner already (RoutingCurr == None at this point)
8950 // This is the result of previous frame's SetShortcutRouting() call.
8951 if (routing_entry->Mods == g.IO.KeyMods)
8952 {
8953 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
8954 if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
8955 {
8956 owner_data->OwnerCurr = routing_entry->RoutingCurr;
8957 //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X) via Routing\n", GetKeyName(key), routing_entry->RoutingCurr);
8958 }
8959 }
8960 }
8961
8962 // Rewrite linked-list
8963 rt->Index[key - ImGuiKey_NamedKey_BEGIN] = (ImGuiKeyRoutingIndex)(new_routing_start_idx < rt->EntriesNext.Size ? new_routing_start_idx : -1);
8964 for (int n = new_routing_start_idx; n < rt->EntriesNext.Size; n++)
8965 rt->EntriesNext[n].NextEntryIndex = (ImGuiKeyRoutingIndex)((n + 1 < rt->EntriesNext.Size) ? n + 1 : -1);
8966 }
8967 rt->Entries.swap(rt->EntriesNext); // Swap new and old indexes
8968}
8969
8970// owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope().
8971static inline ImGuiID GetRoutingIdFromOwnerId(ImGuiID owner_id)
8972{
8973 ImGuiContext& g = *GImGui;
8974 return (owner_id != ImGuiKeyOwner_None && owner_id != ImGuiKeyOwner_Any) ? owner_id : g.CurrentFocusScopeId;
8975}
8976
8977ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord)
8978{
8979 // Majority of shortcuts will be Key + any number of Mods
8980 // We accept _Single_ mod with ImGuiKey_None.
8981 // - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl); // Legal
8982 // - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl | ImGuiMod_Shift); // Legal
8983 // - Shortcut(ImGuiMod_Ctrl); // Legal
8984 // - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift); // Not legal
8985 ImGuiContext& g = *GImGui;
8986 ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
8987 ImGuiKeyRoutingData* routing_data;
8988 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
8989 ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
8990 if (key == ImGuiKey_None)
8991 key = ConvertSingleModFlagToKey(&g, mods);
8992 IM_ASSERT(IsNamedKey(key) && (key_chord & ImGuiMod_Shortcut) == 0); // Please call ConvertShortcutMod() in calling function.
8993
8994 // Get (in the majority of case, the linked list will have one element so this should be 2 reads.
8995 // Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame).
8996 for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; idx = routing_data->NextEntryIndex)
8997 {
8998 routing_data = &rt->Entries[idx];
8999 if (routing_data->Mods == mods)
9000 return routing_data;
9001 }
9002
9003 // Add to linked-list
9004 ImGuiKeyRoutingIndex routing_data_idx = (ImGuiKeyRoutingIndex)rt->Entries.Size;
9005 rt->Entries.push_back(ImGuiKeyRoutingData());
9006 routing_data = &rt->Entries[routing_data_idx];
9007 routing_data->Mods = (ImU16)mods;
9008 routing_data->NextEntryIndex = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; // Setup linked list
9009 rt->Index[key - ImGuiKey_NamedKey_BEGIN] = routing_data_idx;
9010 return routing_data;
9011}
9012
9013// Current score encoding (lower is highest priority):
9014// - 0: ImGuiInputFlags_RouteGlobalHigh
9015// - 1: ImGuiInputFlags_RouteFocused (if item active)
9016// - 2: ImGuiInputFlags_RouteGlobal
9017// - 3+: ImGuiInputFlags_RouteFocused (if window in focus-stack)
9018// - 254: ImGuiInputFlags_RouteGlobalLow
9019// - 255: never route
9020// 'flags' should include an explicit routing policy
9021static int CalcRoutingScore(ImGuiID focus_scope_id, ImGuiID owner_id, ImGuiInputFlags flags)
9022{
9023 if (flags & ImGuiInputFlags_RouteFocused)
9024 {
9025 ImGuiContext& g = *GImGui;
9026
9027 // ActiveID gets top priority
9028 // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it)
9029 if (owner_id != 0 && g.ActiveId == owner_id)
9030 return 1;
9031
9032 // Score based on distance to focused window (lower is better)
9033 // Assuming both windows are submitting a routing request,
9034 // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match)
9035 // - When Window/ChildB is focused -> Window scores 4, Window/ChildB scores 3 (best)
9036 // Assuming only WindowA is submitting a routing request,
9037 // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score.
9038 // This essentially follow the window->ParentWindowForFocusRoute chain.
9039 if (focus_scope_id == 0)
9040 return 255;
9041 for (int index_in_focus_path = 0; index_in_focus_path < g.NavFocusRoute.Size; index_in_focus_path++)
9042 if (g.NavFocusRoute.Data[index_in_focus_path].ID == focus_scope_id)
9043 return 3 + index_in_focus_path;
9044
9045 return 255;
9046 }
9047
9048 // ImGuiInputFlags_RouteGlobalHigh is default, so calls without flags are not conditional
9049 if (flags & ImGuiInputFlags_RouteGlobal)
9050 return 2;
9051 if (flags & ImGuiInputFlags_RouteGlobalLow)
9052 return 254;
9053 return 0;
9054}
9055
9056// We need this to filter some Shortcut() routes when an item e.g. an InputText() is active
9057// e.g. ImGuiKey_G won't be considered a shortcut when item is active, but ImGuiMod|ImGuiKey_G can be.
9058static bool IsKeyChordPotentiallyCharInput(ImGuiKeyChord key_chord)
9059{
9060 // Mimic 'ignore_char_inputs' logic in InputText()
9061 ImGuiContext& g = *GImGui;
9062
9063 // When the right mods are pressed it cannot be a char input so we won't filter the shortcut out.
9064 ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9065 const bool ignore_char_inputs = ((mods & ImGuiMod_Ctrl) && !(mods & ImGuiMod_Alt)) || (g.IO.ConfigMacOSXBehaviors && (mods & ImGuiMod_Super));
9066 if (ignore_char_inputs)
9067 return false;
9068
9069 // Return true for A-Z, 0-9 and other keys associated to char inputs. Other keys such as F1-F12 won't be filtered.
9070 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9071 return g.KeysMayBeCharInput.TestBit(key);
9072}
9073
9074// Request a desired route for an input chord (key + mods).
9075// Return true if the route is available this frame.
9076// - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state.
9077// (Conceptually this does a "Submit for next frame" + "Test for current frame".
9078// As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.)
9079bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
9080{
9081 ImGuiContext& g = *GImGui;
9082 if ((flags & ImGuiInputFlags_RouteMask_) == 0)
9083 flags |= ImGuiInputFlags_RouteGlobalHigh; // IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut()
9084 else
9085 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteMask_)); // Check that only 1 routing flag is used
9086 IM_ASSERT(owner_id != ImGuiKeyOwner_Any && owner_id != ImGuiKeyOwner_None);
9087
9088 // Convert ImGuiMod_Shortcut and add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
9089 key_chord = FixupKeyChord(&g, key_chord);
9090
9091 // [DEBUG] Debug break requested by user
9092 if (g.DebugBreakInShortcutRouting == key_chord)
9093 IM_DEBUG_BREAK();
9094
9095 if (flags & ImGuiInputFlags_RouteUnlessBgFocused)
9096 if (g.NavWindow == NULL)
9097 return false;
9098
9099 // Note how ImGuiInputFlags_RouteAlways won't set routing and thus won't set owner. May want to rework this?
9100 if (flags & ImGuiInputFlags_RouteAlways)
9101 {
9102 IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, owner_id=0x%08X, flags=%04X) -> always\n", GetKeyChordName(key_chord), owner_id, flags);
9103 return true;
9104 }
9105
9106 // Specific culling when there's an active.
9107 if (g.ActiveId != 0 && g.ActiveId != owner_id)
9108 {
9109 // Cull shortcuts with no modifiers when it could generate a character.
9110 // e.g. Shortcut(ImGuiKey_G) also generates 'g' character, should not trigger when InputText() is active.
9111 // but Shortcut(Ctrl+G) should generally trigger when InputText() is active.
9112 // TL;DR: lettered shortcut with no mods or with only Alt mod will not trigger while an item reading text input is active.
9113 // (We cannot filter based on io.InputQueueCharacters[] contents because of trickling and key<>chars submission order are undefined)
9114 if ((flags & ImGuiInputFlags_RouteFocused) && g.IO.WantTextInput && IsKeyChordPotentiallyCharInput(key_chord))
9115 {
9116 IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, owner_id=0x%08X, flags=%04X) -> filtered as potential char input\n", GetKeyChordName(key_chord), owner_id, flags);
9117 return false;
9118 }
9119
9120 // ActiveIdUsingAllKeyboardKeys trumps all for ActiveId
9121 if ((flags & ImGuiInputFlags_RouteGlobalHigh) == 0 && g.ActiveIdUsingAllKeyboardKeys)
9122 {
9123 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9124 if (key == ImGuiKey_None)
9125 key = ConvertSingleModFlagToKey(&g, (ImGuiKey)(key_chord & ImGuiMod_Mask_));
9126 if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9127 return false;
9128 }
9129 }
9130
9131 // FIXME-SHORTCUT: A way to configure the location/focus-scope to test would render this more flexible.
9132 const int score = CalcRoutingScore(g.CurrentFocusScopeId, owner_id, flags);
9133 IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, owner_id=0x%08X, flags=%04X) -> score %d\n", GetKeyChordName(key_chord), owner_id, flags, score);
9134 if (score == 255)
9135 return false;
9136
9137 // Submit routing for NEXT frame (assuming score is sufficient)
9138 // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using <= instead of <).
9139 ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord);
9140 //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score <= routing_data->RoutingNextScore) : (score < routing_data->RoutingNextScore);
9141 if (score < routing_data->RoutingNextScore)
9142 {
9143 routing_data->RoutingNext = owner_id;
9144 routing_data->RoutingNextScore = (ImU8)score;
9145 }
9146
9147 // Return routing state for CURRENT frame
9148 if (routing_data->RoutingCurr == owner_id)
9149 IMGUI_DEBUG_LOG_INPUTROUTING("--> granting current route\n");
9150 return routing_data->RoutingCurr == owner_id;
9151}
9152
9153// Currently unused by core (but used by tests)
9154// Note: this cannot be turned into GetShortcutRouting() because we do the owner_id->routing_id translation, name would be more misleading.
9155bool ImGui::TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id)
9156{
9157 ImGuiContext& g = *GImGui;
9158 const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
9159 key_chord = FixupKeyChord(&g, key_chord);
9160 ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); // FIXME: Could avoid creating entry.
9161 return routing_data->RoutingCurr == routing_id;
9162}
9163
9164// Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
9165// Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
9166bool ImGui::IsKeyDown(ImGuiKey key)
9167{
9168 return IsKeyDown(key, ImGuiKeyOwner_Any);
9169}
9170
9171bool ImGui::IsKeyDown(ImGuiKey key, ImGuiID owner_id)
9172{
9173 const ImGuiKeyData* key_data = GetKeyData(key);
9174 if (!key_data->Down)
9175 return false;
9176 if (!TestKeyOwner(key, owner_id))
9177 return false;
9178 return true;
9179}
9180
9181bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
9182{
9183 return IsKeyPressed(key, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
9184}
9185
9186// Important: unless legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
9187bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
9188{
9189 const ImGuiKeyData* key_data = GetKeyData(key);
9190 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)
9191 return false;
9192 const float t = key_data->DownDuration;
9193 if (t < 0.0f)
9194 return false;
9195 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
9196 if (flags & (ImGuiInputFlags_RepeatRateMask_ | ImGuiInputFlags_RepeatUntilMask_)) // Setting any _RepeatXXX option enables _Repeat
9197 flags |= ImGuiInputFlags_Repeat;
9198
9199 bool pressed = (t == 0.0f);
9200 if (!pressed && (flags & ImGuiInputFlags_Repeat) != 0)
9201 {
9202 float repeat_delay, repeat_rate;
9203 GetTypematicRepeatRate(flags, &repeat_delay, &repeat_rate);
9204 pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0;
9205 if (pressed && (flags & ImGuiInputFlags_RepeatUntilMask_))
9206 {
9207 // Slightly bias 'key_pressed_time' as DownDuration is an accumulation of DeltaTime which we compare to an absolute time value.
9208 // Ideally we'd replace DownDuration with KeyPressedTime but it would break user's code.
9209 ImGuiContext& g = *GImGui;
9210 double key_pressed_time = g.Time - t + 0.00001f;
9211 if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChange) && (g.LastKeyModsChangeTime > key_pressed_time))
9212 pressed = false;
9213 if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChangeFromNone) && (g.LastKeyModsChangeFromNoneTime > key_pressed_time))
9214 pressed = false;
9215 if ((flags & ImGuiInputFlags_RepeatUntilOtherKeyPress) && (g.LastKeyboardKeyPressTime > key_pressed_time))
9216 pressed = false;
9217 }
9218 }
9219 if (!pressed)
9220 return false;
9221 if (!TestKeyOwner(key, owner_id))
9222 return false;
9223 return true;
9224}
9225
9226bool ImGui::IsKeyReleased(ImGuiKey key)
9227{
9228 return IsKeyReleased(key, ImGuiKeyOwner_Any);
9229}
9230
9231bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id)
9232{
9233 const ImGuiKeyData* key_data = GetKeyData(key);
9234 if (key_data->DownDurationPrev < 0.0f || key_data->Down)
9235 return false;
9236 if (!TestKeyOwner(key, owner_id))
9237 return false;
9238 return true;
9239}
9240
9241bool ImGui::IsMouseDown(ImGuiMouseButton button)
9242{
9243 ImGuiContext& g = *GImGui;
9244 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9245 return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // should be same as IsKeyDown(MouseButtonToKey(button), ImGuiKeyOwner_Any), but this allows legacy code hijacking the io.Mousedown[] array.
9246}
9247
9248bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id)
9249{
9250 ImGuiContext& g = *GImGui;
9251 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9252 return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array.
9253}
9254
9255bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
9256{
9257 return IsMouseClicked(button, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
9258}
9259
9260bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags)
9261{
9262 ImGuiContext& g = *GImGui;
9263 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9264 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)
9265 return false;
9266 const float t = g.IO.MouseDownDuration[button];
9267 if (t < 0.0f)
9268 return false;
9269 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsMouseClicked) == 0); // Passing flags not supported by this function! // FIXME: Could support RepeatRate and RepeatUntil flags here.
9270
9271 const bool repeat = (flags & ImGuiInputFlags_Repeat) != 0;
9272 const bool pressed = (t == 0.0f) || (repeat && t > g.IO.KeyRepeatDelay && CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0);
9273 if (!pressed)
9274 return false;
9275
9276 if (!TestKeyOwner(MouseButtonToKey(button), owner_id))
9277 return false;
9278
9279 return true;
9280}
9281
9282bool ImGui::IsMouseReleased(ImGuiMouseButton button)
9283{
9284 ImGuiContext& g = *GImGui;
9285 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9286 return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any)
9287}
9288
9289bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id)
9290{
9291 ImGuiContext& g = *GImGui;
9292 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9293 return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id)
9294}
9295
9296bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
9297{
9298 ImGuiContext& g = *GImGui;
9299 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9300 return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any);
9301}
9302
9303bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button, ImGuiID owner_id)
9304{
9305 ImGuiContext& g = *GImGui;
9306 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9307 return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), owner_id);
9308}
9309
9310int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
9311{
9312 ImGuiContext& g = *GImGui;
9313 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9314 return g.IO.MouseClickedCount[button];
9315}
9316
9317// Test if mouse cursor is hovering given rectangle
9318// NB- Rectangle is clipped by our current clip setting
9319// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
9320bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
9321{
9322 ImGuiContext& g = *GImGui;
9323
9324 // Clip
9325 ImRect rect_clipped(r_min, r_max);
9326 if (clip)
9327 rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
9328
9329 // Hit testing, expanded for touch input
9330 if (!rect_clipped.ContainsWithPad(g.IO.MousePos, g.Style.TouchExtraPadding))
9331 return false;
9332 if (!g.MouseViewport->GetMainRect().Overlaps(rect_clipped))
9333 return false;
9334 return true;
9335}
9336
9337// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
9338// [Internal] This doesn't test if the button is pressed
9339bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
9340{
9341 ImGuiContext& g = *GImGui;
9342 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9343 if (lock_threshold < 0.0f)
9344 lock_threshold = g.IO.MouseDragThreshold;
9345 return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
9346}
9347
9348bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
9349{
9350 ImGuiContext& g = *GImGui;
9351 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9352 if (!g.IO.MouseDown[button])
9353 return false;
9354 return IsMouseDragPastThreshold(button, lock_threshold);
9355}
9356
9357ImVec2 ImGui::GetMousePos()
9358{
9359 ImGuiContext& g = *GImGui;
9360 return g.IO.MousePos;
9361}
9362
9363// This is called TeleportMousePos() and not SetMousePos() to emphasis that setting MousePosPrev will effectively clear mouse delta as well.
9364// It is expected you only call this if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) is set and supported by backend.
9365void ImGui::TeleportMousePos(const ImVec2& pos)
9366{
9367 ImGuiContext& g = *GImGui;
9368 g.IO.MousePos = g.IO.MousePosPrev = pos;
9369 g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
9370 g.IO.WantSetMousePos = true;
9371 //IMGUI_DEBUG_LOG_IO("TeleportMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
9372}
9373
9374// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
9375ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
9376{
9377 ImGuiContext& g = *GImGui;
9378 if (g.BeginPopupStack.Size > 0)
9379 return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
9380 return g.IO.MousePos;
9381}
9382
9383// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
9384bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
9385{
9386 // The assert is only to silence a false-positive in XCode Static Analysis.
9387 // 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).
9388 IM_ASSERT(GImGui != NULL);
9389 const float MOUSE_INVALID = -256000.0f;
9390 ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
9391 return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
9392}
9393
9394// [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.
9395bool ImGui::IsAnyMouseDown()
9396{
9397 ImGuiContext& g = *GImGui;
9398 for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
9399 if (g.IO.MouseDown[n])
9400 return true;
9401 return false;
9402}
9403
9404// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
9405// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
9406// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
9407ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
9408{
9409 ImGuiContext& g = *GImGui;
9410 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9411 if (lock_threshold < 0.0f)
9412 lock_threshold = g.IO.MouseDragThreshold;
9413 if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
9414 if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
9415 if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
9416 return g.IO.MousePos - g.IO.MouseClickedPos[button];
9417 return ImVec2(0.0f, 0.0f);
9418}
9419
9420void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
9421{
9422 ImGuiContext& g = *GImGui;
9423 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9424 // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
9425 g.IO.MouseClickedPos[button] = g.IO.MousePos;
9426}
9427
9428// Get desired mouse cursor shape.
9429// Important: this is meant to be used by a platform backend, it is reset in ImGui::NewFrame(),
9430// updated during the frame, and locked in EndFrame()/Render().
9431// If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you
9432ImGuiMouseCursor ImGui::GetMouseCursor()
9433{
9434 ImGuiContext& g = *GImGui;
9435 return g.MouseCursor;
9436}
9437
9438void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
9439{
9440 ImGuiContext& g = *GImGui;
9441 g.MouseCursor = cursor_type;
9442}
9443
9444static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value)
9445{
9446 IM_ASSERT(ImGui::IsAliasKey(key));
9447 ImGuiKeyData* key_data = ImGui::GetKeyData(key);
9448 key_data->Down = v;
9449 key_data->AnalogValue = analog_value;
9450}
9451
9452// [Internal] Do not use directly
9453static ImGuiKeyChord GetMergedModsFromKeys()
9454{
9455 ImGuiKeyChord mods = 0;
9456 if (ImGui::IsKeyDown(ImGuiMod_Ctrl)) { mods |= ImGuiMod_Ctrl; }
9457 if (ImGui::IsKeyDown(ImGuiMod_Shift)) { mods |= ImGuiMod_Shift; }
9458 if (ImGui::IsKeyDown(ImGuiMod_Alt)) { mods |= ImGuiMod_Alt; }
9459 if (ImGui::IsKeyDown(ImGuiMod_Super)) { mods |= ImGuiMod_Super; }
9460 return mods;
9461}
9462
9463static void ImGui::UpdateKeyboardInputs()
9464{
9465 ImGuiContext& g = *GImGui;
9466 ImGuiIO& io = g.IO;
9467
9468 // Import legacy keys or verify they are not used
9469#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9470 if (io.BackendUsingLegacyKeyArrays == 0)
9471 {
9472 // Backend used new io.AddKeyEvent() API: Good! Verify that old arrays are never written to externally.
9473 for (int n = 0; n < ImGuiKey_LegacyNativeKey_END; n++)
9474 IM_ASSERT((io.KeysDown[n] == false || IsKeyDown((ImGuiKey)n)) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
9475 }
9476 else
9477 {
9478 if (g.FrameCount == 0)
9479 for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9480 IM_ASSERT(g.IO.KeyMap[n] == -1 && "Backend is not allowed to write to io.KeyMap[0..511]!");
9481
9482 // Build reverse KeyMap (Named -> Legacy)
9483 for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
9484 if (io.KeyMap[n] != -1)
9485 {
9486 IM_ASSERT(IsLegacyKey((ImGuiKey)io.KeyMap[n]));
9487 io.KeyMap[io.KeyMap[n]] = n;
9488 }
9489
9490 // Import legacy keys into new ones
9491 for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9492 if (io.KeysDown[n] || io.BackendUsingLegacyKeyArrays == 1)
9493 {
9494 const ImGuiKey key = (ImGuiKey)(io.KeyMap[n] != -1 ? io.KeyMap[n] : n);
9495 IM_ASSERT(io.KeyMap[n] == -1 || IsNamedKey(key));
9496 io.KeysData[key].Down = io.KeysDown[n];
9497 if (key != n)
9498 io.KeysDown[key] = io.KeysDown[n]; // Allow legacy code using io.KeysDown[GetKeyIndex()] with old backends
9499 io.BackendUsingLegacyKeyArrays = 1;
9500 }
9501 if (io.BackendUsingLegacyKeyArrays == 1)
9502 {
9503 GetKeyData(ImGuiMod_Ctrl)->Down = io.KeyCtrl;
9504 GetKeyData(ImGuiMod_Shift)->Down = io.KeyShift;
9505 GetKeyData(ImGuiMod_Alt)->Down = io.KeyAlt;
9506 GetKeyData(ImGuiMod_Super)->Down = io.KeySuper;
9507 }
9508 }
9509#endif
9510
9511 // Import legacy ImGuiNavInput_ io inputs and convert to gamepad keys
9512#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9513 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
9514 if (io.BackendUsingLegacyNavInputArray && nav_gamepad_active)
9515 {
9516 #define MAP_LEGACY_NAV_INPUT_TO_KEY1(_KEY, _NAV1) do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f); io.KeysData[_KEY].AnalogValue = io.NavInputs[_NAV1]; } while (0)
9517 #define MAP_LEGACY_NAV_INPUT_TO_KEY2(_KEY, _NAV1, _NAV2) do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f) || (io.NavInputs[_NAV2] > 0.0f); io.KeysData[_KEY].AnalogValue = ImMax(io.NavInputs[_NAV1], io.NavInputs[_NAV2]); } while (0)
9518 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceDown, ImGuiNavInput_Activate);
9519 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceRight, ImGuiNavInput_Cancel);
9520 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceLeft, ImGuiNavInput_Menu);
9521 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceUp, ImGuiNavInput_Input);
9522 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadLeft, ImGuiNavInput_DpadLeft);
9523 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadRight, ImGuiNavInput_DpadRight);
9524 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadUp, ImGuiNavInput_DpadUp);
9525 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadDown, ImGuiNavInput_DpadDown);
9526 MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadL1, ImGuiNavInput_FocusPrev, ImGuiNavInput_TweakSlow);
9527 MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadR1, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakFast);
9528 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickLeft, ImGuiNavInput_LStickLeft);
9529 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickRight, ImGuiNavInput_LStickRight);
9530 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickUp, ImGuiNavInput_LStickUp);
9531 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickDown, ImGuiNavInput_LStickDown);
9532 #undef NAV_MAP_KEY
9533 }
9534#endif
9535
9536 // Update aliases
9537 for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
9538 UpdateAliasKey(MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] ? 1.0f : 0.0f);
9539 UpdateAliasKey(ImGuiKey_MouseWheelX, io.MouseWheelH != 0.0f, io.MouseWheelH);
9540 UpdateAliasKey(ImGuiKey_MouseWheelY, io.MouseWheel != 0.0f, io.MouseWheel);
9541
9542 // Synchronize io.KeyMods and io.KeyCtrl/io.KeyShift/etc. values.
9543 // - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) -> -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9544 // - Legacy backends: set io.KeyXXX bools -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9545 // So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing.
9546 const ImGuiKeyChord prev_key_mods = io.KeyMods;
9547 io.KeyMods = GetMergedModsFromKeys();
9548 io.KeyCtrl = (io.KeyMods & ImGuiMod_Ctrl) != 0;
9549 io.KeyShift = (io.KeyMods & ImGuiMod_Shift) != 0;
9550 io.KeyAlt = (io.KeyMods & ImGuiMod_Alt) != 0;
9551 io.KeySuper = (io.KeyMods & ImGuiMod_Super) != 0;
9552 if (prev_key_mods != io.KeyMods)
9553 g.LastKeyModsChangeTime = g.Time;
9554 if (prev_key_mods != io.KeyMods && prev_key_mods == 0)
9555 g.LastKeyModsChangeFromNoneTime = g.Time;
9556
9557 // Clear gamepad data if disabled
9558 if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
9559 for (int i = ImGuiKey_Gamepad_BEGIN; i < ImGuiKey_Gamepad_END; i++)
9560 {
9561 io.KeysData[i - ImGuiKey_KeysData_OFFSET].Down = false;
9562 io.KeysData[i - ImGuiKey_KeysData_OFFSET].AnalogValue = 0.0f;
9563 }
9564
9565 // Update keys
9566 for (int i = 0; i < ImGuiKey_KeysData_SIZE; i++)
9567 {
9568 ImGuiKeyData* key_data = &io.KeysData[i];
9569 key_data->DownDurationPrev = key_data->DownDuration;
9570 key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
9571 if (key_data->DownDuration == 0.0f)
9572 {
9573 ImGuiKey key = (ImGuiKey)(ImGuiKey_KeysData_OFFSET + i);
9574 if (IsKeyboardKey(key))
9575 g.LastKeyboardKeyPressTime = g.Time;
9576 else if (key == ImGuiKey_ReservedForModCtrl || key == ImGuiKey_ReservedForModShift || key == ImGuiKey_ReservedForModAlt || key == ImGuiKey_ReservedForModSuper)
9577 g.LastKeyboardKeyPressTime = g.Time;
9578 }
9579 }
9580
9581 // Update keys/input owner (named keys only): one entry per key
9582 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
9583 {
9584 ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_KeysData_OFFSET];
9585 ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
9586 owner_data->OwnerCurr = owner_data->OwnerNext;
9587 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.
9588 owner_data->OwnerNext = ImGuiKeyOwner_None;
9589 owner_data->LockThisFrame = owner_data->LockUntilRelease = owner_data->LockUntilRelease && key_data->Down; // Clear LockUntilRelease when key is not Down anymore
9590 }
9591
9592 // Update key routing (for e.g. shortcuts)
9593 UpdateKeyRoutingTable(&g.KeysRoutingTable);
9594}
9595
9596static void ImGui::UpdateMouseInputs()
9597{
9598 ImGuiContext& g = *GImGui;
9599 ImGuiIO& io = g.IO;
9600
9601 // Mouse Wheel swapping flag
9602 // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
9603 // - We avoid doing it on OSX as it the OS input layer handles this already.
9604 // - FIXME: However this means when running on OSX over Emscripten, Shift+WheelY will incur two swapping (1 in OS, 1 here), canceling the feature.
9605 // - FIXME: When we can distinguish e.g. touchpad scroll events from mouse ones, we'll set this accordingly based on input source.
9606 io.MouseWheelRequestAxisSwap = io.KeyShift && !io.ConfigMacOSXBehaviors;
9607
9608 // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
9609 if (IsMousePosValid(&io.MousePos))
9610 io.MousePos = g.MouseLastValidPos = ImFloor(io.MousePos);
9611
9612 // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
9613 if (IsMousePosValid(&io.MousePos) && IsMousePosValid(&io.MousePosPrev))
9614 io.MouseDelta = io.MousePos - io.MousePosPrev;
9615 else
9616 io.MouseDelta = ImVec2(0.0f, 0.0f);
9617
9618 // Update stationary timer.
9619 // FIXME: May need to rework again to have some tolerance for occasional small movement, while being functional on high-framerates.
9620 const float mouse_stationary_threshold = (io.MouseSource == ImGuiMouseSource_Mouse) ? 2.0f : 3.0f; // Slightly higher threshold for ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen, may need rework.
9621 const bool mouse_stationary = (ImLengthSqr(io.MouseDelta) <= mouse_stationary_threshold * mouse_stationary_threshold);
9622 g.MouseStationaryTimer = mouse_stationary ? (g.MouseStationaryTimer + io.DeltaTime) : 0.0f;
9623 //IMGUI_DEBUG_LOG("%.4f\n", g.MouseStationaryTimer);
9624
9625 // If mouse moved we re-enable mouse hovering in case it was disabled by gamepad/keyboard. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true.
9626 if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
9627 g.NavDisableMouseHover = false;
9628
9629 for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
9630 {
9631 io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
9632 io.MouseClickedCount[i] = 0; // Will be filled below
9633 io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
9634 io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
9635 io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
9636 if (io.MouseClicked[i])
9637 {
9638 bool is_repeated_click = false;
9639 if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
9640 {
9641 ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9642 if (ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
9643 is_repeated_click = true;
9644 }
9645 if (is_repeated_click)
9646 io.MouseClickedLastCount[i]++;
9647 else
9648 io.MouseClickedLastCount[i] = 1;
9649 io.MouseClickedTime[i] = g.Time;
9650 io.MouseClickedPos[i] = io.MousePos;
9651 io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
9652 io.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
9653 io.MouseDragMaxDistanceSqr[i] = 0.0f;
9654 }
9655 else if (io.MouseDown[i])
9656 {
9657 // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
9658 ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9659 io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
9660 io.MouseDragMaxDistanceAbs[i].x = ImMax(io.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
9661 io.MouseDragMaxDistanceAbs[i].y = ImMax(io.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
9662 }
9663
9664 // We provide io.MouseDoubleClicked[] as a legacy service
9665 io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
9666
9667 // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
9668 if (io.MouseClicked[i])
9669 g.NavDisableMouseHover = false;
9670 }
9671}
9672
9673static void LockWheelingWindow(ImGuiWindow* window, float wheel_amount)
9674{
9675 ImGuiContext& g = *GImGui;
9676 if (window)
9677 g.WheelingWindowReleaseTimer = ImMin(g.WheelingWindowReleaseTimer + ImAbs(wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER);
9678 else
9679 g.WheelingWindowReleaseTimer = 0.0f;
9680 if (g.WheelingWindow == window)
9681 return;
9682 IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL");
9683 g.WheelingWindow = window;
9684 g.WheelingWindowRefMousePos = g.IO.MousePos;
9685 if (window == NULL)
9686 {
9687 g.WheelingWindowStartFrame = -1;
9688 g.WheelingAxisAvg = ImVec2(0.0f, 0.0f);
9689 }
9690}
9691
9692static ImGuiWindow* FindBestWheelingWindow(const ImVec2& wheel)
9693{
9694 // For each axis, find window in the hierarchy that may want to use scrolling
9695 ImGuiContext& g = *GImGui;
9696 ImGuiWindow* windows[2] = { NULL, NULL };
9697 for (int axis = 0; axis < 2; axis++)
9698 if (wheel[axis] != 0.0f)
9699 for (ImGuiWindow* window = windows[axis] = g.HoveredWindow; window->Flags & ImGuiWindowFlags_ChildWindow; window = windows[axis] = window->ParentWindow)
9700 {
9701 // Bubble up into parent window if:
9702 // - a child window doesn't allow any scrolling.
9703 // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag.
9705 const bool has_scrolling = (window->ScrollMax[axis] != 0.0f);
9706 const bool inputs_disabled = (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs);
9707 //const bool scrolling_past_limits = (wheel_v < 0.0f) ? (window->Scroll[axis] <= 0.0f) : (window->Scroll[axis] >= window->ScrollMax[axis]);
9708 if (has_scrolling && !inputs_disabled) // && !scrolling_past_limits)
9709 break; // select this window
9710 }
9711 if (windows[0] == NULL && windows[1] == NULL)
9712 return NULL;
9713
9714 // If there's only one window or only one axis then there's no ambiguity
9715 if (windows[0] == windows[1] || windows[0] == NULL || windows[1] == NULL)
9716 return windows[1] ? windows[1] : windows[0];
9717
9718 // If candidate are different windows we need to decide which one to prioritize
9719 // - First frame: only find a winner if one axis is zero.
9720 // - Subsequent frames: only find a winner when one is more than the other.
9721 if (g.WheelingWindowStartFrame == -1)
9722 g.WheelingWindowStartFrame = g.FrameCount;
9723 if ((g.WheelingWindowStartFrame == g.FrameCount && wheel.x != 0.0f && wheel.y != 0.0f) || (g.WheelingAxisAvg.x == g.WheelingAxisAvg.y))
9724 {
9725 g.WheelingWindowWheelRemainder = wheel;
9726 return NULL;
9727 }
9728 return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? windows[0] : windows[1];
9729}
9730
9731// Called by NewFrame()
9732void ImGui::UpdateMouseWheel()
9733{
9734 // Reset the locked window if we move the mouse or after the timer elapses.
9735 // 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)
9736 ImGuiContext& g = *GImGui;
9737 if (g.WheelingWindow != NULL)
9738 {
9739 g.WheelingWindowReleaseTimer -= g.IO.DeltaTime;
9740 if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
9741 g.WheelingWindowReleaseTimer = 0.0f;
9742 if (g.WheelingWindowReleaseTimer <= 0.0f)
9743 LockWheelingWindow(NULL, 0.0f);
9744 }
9745
9746 ImVec2 wheel;
9747 wheel.x = TestKeyOwner(ImGuiKey_MouseWheelX, ImGuiKeyOwner_None) ? g.IO.MouseWheelH : 0.0f;
9748 wheel.y = TestKeyOwner(ImGuiKey_MouseWheelY, ImGuiKeyOwner_None) ? g.IO.MouseWheel : 0.0f;
9749
9750 //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y);
9751 ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
9752 if (!mouse_window || mouse_window->Collapsed)
9753 return;
9754
9755 // Zoom / Scale window
9756 // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
9757 if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
9758 {
9759 LockWheelingWindow(mouse_window, wheel.y);
9760 ImGuiWindow* window = mouse_window;
9761 const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
9762 const float scale = new_font_scale / window->FontWindowScale;
9763 window->FontWindowScale = new_font_scale;
9764 if (window == window->RootWindow)
9765 {
9766 const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
9767 SetWindowPos(window, window->Pos + offset, 0);
9768 window->Size = ImTrunc(window->Size * scale);
9769 window->SizeFull = ImTrunc(window->SizeFull * scale);
9770 }
9771 return;
9772 }
9773 if (g.IO.KeyCtrl)
9774 return;
9775
9776 // Mouse wheel scrolling
9777 // Read about io.MouseWheelRequestAxisSwap and its issue on Mac+Emscripten in UpdateMouseInputs()
9778 if (g.IO.MouseWheelRequestAxisSwap)
9779 wheel = ImVec2(wheel.y, 0.0f);
9780
9781 // Maintain a rough average of moving magnitude on both axises
9782 // FIXME: should by based on wall clock time rather than frame-counter
9783 g.WheelingAxisAvg.x = ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30);
9784 g.WheelingAxisAvg.y = ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30);
9785
9786 // In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now.
9787 wheel += g.WheelingWindowWheelRemainder;
9788 g.WheelingWindowWheelRemainder = ImVec2(0.0f, 0.0f);
9789 if (wheel.x == 0.0f && wheel.y == 0.0f)
9790 return;
9791
9792 // Mouse wheel scrolling: find target and apply
9793 // - don't renew lock if axis doesn't apply on the window.
9794 // - select a main axis when both axises are being moved.
9795 if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel)))
9796 if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
9797 {
9798 bool do_scroll[2] = { wheel.x != 0.0f && window->ScrollMax.x != 0.0f, wheel.y != 0.0f && window->ScrollMax.y != 0.0f };
9799 if (do_scroll[ImGuiAxis_X] && do_scroll[ImGuiAxis_Y])
9800 do_scroll[(g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? ImGuiAxis_Y : ImGuiAxis_X] = false;
9801 if (do_scroll[ImGuiAxis_X])
9802 {
9803 LockWheelingWindow(window, wheel.x);
9804 float max_step = window->InnerRect.GetWidth() * 0.67f;
9805 float scroll_step = ImTrunc(ImMin(2 * window->CalcFontSize(), max_step));
9806 SetScrollX(window, window->Scroll.x - wheel.x * scroll_step);
9807 g.WheelingWindowScrolledFrame = g.FrameCount;
9808 }
9809 if (do_scroll[ImGuiAxis_Y])
9810 {
9811 LockWheelingWindow(window, wheel.y);
9812 float max_step = window->InnerRect.GetHeight() * 0.67f;
9813 float scroll_step = ImTrunc(ImMin(5 * window->CalcFontSize(), max_step));
9814 SetScrollY(window, window->Scroll.y - wheel.y * scroll_step);
9815 g.WheelingWindowScrolledFrame = g.FrameCount;
9816 }
9817 }
9818}
9819
9820void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard)
9821{
9822 ImGuiContext& g = *GImGui;
9823 g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0;
9824}
9825
9826void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
9827{
9828 ImGuiContext& g = *GImGui;
9829 g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0;
9830}
9831
9832#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9833static const char* GetInputSourceName(ImGuiInputSource source)
9834{
9835 const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad", "Clipboard" };
9836 IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT && source >= 0 && source < ImGuiInputSource_COUNT);
9837 return input_source_names[source];
9838}
9839static const char* GetMouseSourceName(ImGuiMouseSource source)
9840{
9841 const char* mouse_source_names[] = { "Mouse", "TouchScreen", "Pen" };
9842 IM_ASSERT(IM_ARRAYSIZE(mouse_source_names) == ImGuiMouseSource_COUNT && source >= 0 && source < ImGuiMouseSource_COUNT);
9843 return mouse_source_names[source];
9844}
9845static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
9846{
9847 ImGuiContext& g = *GImGui;
9848 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; }
9849 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; }
9850 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; }
9851 if (e->Type == ImGuiInputEventType_MouseViewport){IMGUI_DEBUG_LOG_IO("[io] %s: MouseViewport (0x%08X)\n", prefix, e->MouseViewport.HoveredViewportID); return; }
9852 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; }
9853 if (e->Type == ImGuiInputEventType_Text) { IMGUI_DEBUG_LOG_IO("[io] %s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; }
9854 if (e->Type == ImGuiInputEventType_Focus) { IMGUI_DEBUG_LOG_IO("[io] %s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; }
9855}
9856#endif
9857
9858// Process input queue
9859// We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'.
9860// - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)
9861// - 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)
9862void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
9863{
9864 ImGuiContext& g = *GImGui;
9865 ImGuiIO& io = g.IO;
9866
9867 // Only trickle chars<>key when working with InputText()
9868 // FIXME: InputText() could parse event trail?
9869 // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters)
9870 const bool trickle_interleaved_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1);
9871
9872 bool mouse_moved = false, mouse_wheeled = false, key_changed = false, text_inputted = false;
9873 int mouse_button_changed = 0x00;
9874 ImBitArray<ImGuiKey_KeysData_SIZE> key_changed_mask;
9875
9876 int event_n = 0;
9877 for (; event_n < g.InputEventsQueue.Size; event_n++)
9878 {
9879 ImGuiInputEvent* e = &g.InputEventsQueue[event_n];
9880 if (e->Type == ImGuiInputEventType_MousePos)
9881 {
9882 if (g.IO.WantSetMousePos)
9883 continue;
9884 // Trickling Rule: Stop processing queued events if we already handled a mouse button change
9885 ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);
9886 if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted))
9887 break;
9888 io.MousePos = event_pos;
9889 io.MouseSource = e->MousePos.MouseSource;
9890 mouse_moved = true;
9891 }
9892 else if (e->Type == ImGuiInputEventType_MouseButton)
9893 {
9894 // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9895 const ImGuiMouseButton button = e->MouseButton.Button;
9896 IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);
9897 if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))
9898 break;
9899 if (trickle_fast_inputs && e->MouseButton.MouseSource == ImGuiMouseSource_TouchScreen && mouse_moved) // #2702: TouchScreen have no initial hover.
9900 break;
9901 io.MouseDown[button] = e->MouseButton.Down;
9902 io.MouseSource = e->MouseButton.MouseSource;
9903 mouse_button_changed |= (1 << button);
9904 }
9905 else if (e->Type == ImGuiInputEventType_MouseWheel)
9906 {
9907 // Trickling Rule: Stop processing queued events if we got multiple action on the event
9908 if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0))
9909 break;
9910 io.MouseWheelH += e->MouseWheel.WheelX;
9911 io.MouseWheel += e->MouseWheel.WheelY;
9912 io.MouseSource = e->MouseWheel.MouseSource;
9913 mouse_wheeled = true;
9914 }
9915 else if (e->Type == ImGuiInputEventType_MouseViewport)
9916 {
9917 io.MouseHoveredViewport = e->MouseViewport.HoveredViewportID;
9918 }
9919 else if (e->Type == ImGuiInputEventType_Key)
9920 {
9921 // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9922 ImGuiKey key = e->Key.Key;
9923 IM_ASSERT(key != ImGuiKey_None);
9924 ImGuiKeyData* key_data = GetKeyData(key);
9925 const int key_data_index = (int)(key_data - g.IO.KeysData);
9926 if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(key_data_index) || text_inputted || mouse_button_changed != 0))
9927 break;
9928 key_data->Down = e->Key.Down;
9929 key_data->AnalogValue = e->Key.AnalogValue;
9930 key_changed = true;
9931 key_changed_mask.SetBit(key_data_index);
9932
9933 // Allow legacy code using io.KeysDown[GetKeyIndex()] with new backends
9934#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9935 io.KeysDown[key_data_index] = key_data->Down;
9936 if (io.KeyMap[key_data_index] != -1)
9937 io.KeysDown[io.KeyMap[key_data_index]] = key_data->Down;
9938#endif
9939 }
9940 else if (e->Type == ImGuiInputEventType_Text)
9941 {
9942 // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with
9943 if (trickle_fast_inputs && ((key_changed && trickle_interleaved_keys_and_text) || mouse_button_changed != 0 || mouse_moved || mouse_wheeled))
9944 break;
9945 unsigned int c = e->Text.Char;
9946 io.InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
9947 if (trickle_interleaved_keys_and_text)
9948 text_inputted = true;
9949 }
9950 else if (e->Type == ImGuiInputEventType_Focus)
9951 {
9952 // We intentionally overwrite this and process in NewFrame(), in order to give a chance
9953 // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.
9954 const bool focus_lost = !e->AppFocused.Focused;
9955 io.AppFocusLost = focus_lost;
9956 }
9957 else
9958 {
9959 IM_ASSERT(0 && "Unknown event!");
9960 }
9961 }
9962
9963 // Record trail (for domain-specific applications wanting to access a precise trail)
9964 //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n);
9965 for (int n = 0; n < event_n; n++)
9966 g.InputEventsTrail.push_back(g.InputEventsQueue[n]);
9967
9968 // [DEBUG]
9969#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9970 if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO))
9971 for (int n = 0; n < g.InputEventsQueue.Size; n++)
9972 DebugPrintInputEvent(n < event_n ? "Processed" : "Remaining", &g.InputEventsQueue[n]);
9973#endif
9974
9975 // Remaining events will be processed on the next frame
9976 if (event_n == g.InputEventsQueue.Size)
9977 g.InputEventsQueue.resize(0);
9978 else
9979 g.InputEventsQueue.erase(g.InputEventsQueue.Data, g.InputEventsQueue.Data + event_n);
9980
9981 // Clear buttons state when focus is lost
9982 // - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle.
9983 // - we clear in EndFrame() and not now in order allow application/user code polling this flag
9984 // (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event).
9985 if (g.IO.AppFocusLost)
9986 g.IO.ClearInputKeys();
9987}
9988
9989ImGuiID ImGui::GetKeyOwner(ImGuiKey key)
9990{
9991 if (!IsNamedKeyOrModKey(key))
9992 return ImGuiKeyOwner_None;
9993
9994 ImGuiContext& g = *GImGui;
9995 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9996 ImGuiID owner_id = owner_data->OwnerCurr;
9997
9998 if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
9999 if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
10000 return ImGuiKeyOwner_None;
10001
10002 return owner_id;
10003}
10004
10005// TestKeyOwner(..., ID) : (owner == None || owner == ID)
10006// TestKeyOwner(..., None) : (owner == None)
10007// TestKeyOwner(..., Any) : no owner test
10008// All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags_LockXXX flags.
10009bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id)
10010{
10011 if (!IsNamedKeyOrModKey(key))
10012 return true;
10013
10014 ImGuiContext& g = *GImGui;
10015 if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
10016 if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
10017 return false;
10018
10019 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10020 if (owner_id == ImGuiKeyOwner_Any)
10021 return (owner_data->LockThisFrame == false);
10022
10023 // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId
10024 // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things.
10025 // Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions.
10026 if (owner_data->OwnerCurr != owner_id)
10027 {
10028 if (owner_data->LockThisFrame)
10029 return false;
10030 if (owner_data->OwnerCurr != ImGuiKeyOwner_None)
10031 return false;
10032 }
10033
10034 return true;
10035}
10036
10037// _LockXXX flags are useful to lock keys away from code which is not input-owner aware.
10038// When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone.
10039// - SetKeyOwner(..., None) : clears owner
10040// - SetKeyOwner(..., Any, !Lock) : illegal (assert)
10041// - SetKeyOwner(..., Any or None, Lock) : set lock
10042void ImGui::SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
10043{
10044 ImGuiContext& g = *GImGui;
10045 IM_ASSERT(IsNamedKeyOrModKey(key) && (owner_id != ImGuiKeyOwner_Any || (flags & (ImGuiInputFlags_LockThisFrame | ImGuiInputFlags_LockUntilRelease)))); // Can only use _Any with _LockXXX flags (to eat a key away without an ID to retrieve it)
10046 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetKeyOwner) == 0); // Passing flags not supported by this function!
10047 //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X, flags=%08X)\n", GetKeyName(key), owner_id, flags);
10048
10049 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10050 owner_data->OwnerCurr = owner_data->OwnerNext = owner_id;
10051
10052 // We cannot lock by default as it would likely break lots of legacy code.
10053 // In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data->Down test)
10054 owner_data->LockUntilRelease = (flags & ImGuiInputFlags_LockUntilRelease) != 0;
10055 owner_data->LockThisFrame = (flags & ImGuiInputFlags_LockThisFrame) != 0 || (owner_data->LockUntilRelease);
10056}
10057
10058// Rarely used helper
10059void ImGui::SetKeyOwnersForKeyChord(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
10060{
10061 if (key_chord & ImGuiMod_Ctrl) { SetKeyOwner(ImGuiMod_Ctrl, owner_id, flags); }
10062 if (key_chord & ImGuiMod_Shift) { SetKeyOwner(ImGuiMod_Shift, owner_id, flags); }
10063 if (key_chord & ImGuiMod_Alt) { SetKeyOwner(ImGuiMod_Alt, owner_id, flags); }
10064 if (key_chord & ImGuiMod_Super) { SetKeyOwner(ImGuiMod_Super, owner_id, flags); }
10065 if (key_chord & ImGuiMod_Shortcut) { SetKeyOwner(ImGuiMod_Shortcut, owner_id, flags); }
10066 if (key_chord & ~ImGuiMod_Mask_) { SetKeyOwner((ImGuiKey)(key_chord & ~ImGuiMod_Mask_), owner_id, flags); }
10067}
10068
10069// This is more or less equivalent to:
10070// if (IsItemHovered() || IsItemActive())
10071// SetKeyOwner(key, GetItemID());
10072// 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.
10073// More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition.
10074// 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.
10075void ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags)
10076{
10077 ImGuiContext& g = *GImGui;
10078 ImGuiID id = g.LastItemData.ID;
10079 if (id == 0 || (g.HoveredId != id && g.ActiveId != id))
10080 return;
10081 if ((flags & ImGuiInputFlags_CondMask_) == 0)
10082 flags |= ImGuiInputFlags_CondDefault_;
10083 if ((g.HoveredId == id && (flags & ImGuiInputFlags_CondHovered)) || (g.ActiveId == id && (flags & ImGuiInputFlags_CondActive)))
10084 {
10085 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetItemKeyOwner) == 0); // Passing flags not supported by this function!
10086 SetKeyOwner(key, id, flags & ~ImGuiInputFlags_CondMask_);
10087 }
10088}
10089
10090// This is the only public API until we expose owner_id versions of the API as replacements.
10091bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord)
10092{
10093 return IsKeyChordPressed(key_chord, 0, ImGuiInputFlags_None);
10094}
10095
10096// This is equivalent to comparing KeyMods + doing a IsKeyPressed()
10097bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
10098{
10099 ImGuiContext& g = *GImGui;
10100 key_chord = FixupKeyChord(&g, key_chord);
10101 ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
10102 if (g.IO.KeyMods != mods)
10103 return false;
10104
10105 // Special storage location for mods
10106 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
10107 if (key == ImGuiKey_None)
10108 key = ConvertSingleModFlagToKey(&g, mods);
10109 if (!IsKeyPressed(key, owner_id, (flags & ImGuiInputFlags_RepeatMask_)))
10110 return false;
10111 return true;
10112}
10113
10114void ImGui::SetNextItemShortcut(ImGuiKeyChord key_chord)
10115{
10116 ImGuiContext& g = *GImGui;
10117 g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasShortcut;
10118 g.NextItemData.Shortcut = key_chord;
10119}
10120
10121bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
10122{
10123 //ImGuiContext& g = *GImGui;
10124 //IMGUI_DEBUG_LOG("Shortcut(%s, owner_id=0x%08X, flags=%X)\n", GetKeyChordName(key_chord, g.TempBuffer.Data, g.TempBuffer.Size), owner_id, flags);
10125
10126 // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any.
10127 if ((flags & ImGuiInputFlags_RouteMask_) == 0)
10128 flags |= ImGuiInputFlags_RouteFocused;
10129
10130 // Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default)
10131 // Effectively makes Shortcut() always input-owner aware.
10132 if (owner_id == ImGuiKeyOwner_Any || owner_id == ImGuiKeyOwner_None)
10133 owner_id = GetRoutingIdFromOwnerId(owner_id);
10134
10135 // Submit route
10136 if (!SetShortcutRouting(key_chord, owner_id, flags))
10137 return false;
10138
10139 // Default repeat behavior for Shortcut()
10140 // So e.g. pressing Ctrl+W and releasing Ctrl while holding W will not trigger the W shortcut.
10141 if ((flags & ImGuiInputFlags_Repeat) != 0 && (flags & ImGuiInputFlags_RepeatUntilMask_) == 0)
10142 flags |= ImGuiInputFlags_RepeatUntilKeyModsChange;
10143
10144 if (!IsKeyChordPressed(key_chord, owner_id, flags))
10145 return false;
10146 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByShortcut) == 0); // Passing flags not supported by this function!
10147 return true;
10148}
10149
10150
10151//-----------------------------------------------------------------------------
10152// [SECTION] ERROR CHECKING
10153//-----------------------------------------------------------------------------
10154
10155// Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
10156// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
10157// If this triggers you have an issue:
10158// - Most commonly: mismatched headers and compiled code version.
10159// - Or: mismatched configuration #define, compilation settings, packing pragma etc.
10160// The configuration settings mentioned in imconfig.h must be set for all compilation units involved with Dear ImGui,
10161// which is way it is required you put them in your imconfig file (and not just before including imgui.h).
10162// Otherwise it is possible that different compilation units would see different structure layout
10163bool 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)
10164{
10165 bool error = false;
10166 if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
10167 if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
10168 if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
10169 if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
10170 if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
10171 if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
10172 if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
10173 return !error;
10174}
10175
10176// Until 1.89 (IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos() to extend the boundary of a parent (e.g. window or table cell)
10177// This is causing issues and ambiguity and we need to retire that.
10178// See https://github.com/ocornut/imgui/issues/5548 for more details.
10179// [Scenario 1]
10180// Previously this would make the window content size ~200x200:
10181// Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End(); // NOT OK
10182// Instead, please submit an item:
10183// Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
10184// Alternative:
10185// Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
10186// [Scenario 2]
10187// For reference this is one of the issue what we aim to fix with this change:
10188// BeginGroup() + SomeItem("foobar") + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup()
10189// The previous logic made SetCursorScreenPos(GetCursorScreenPos()) have a side-effect! It would erroneously incorporate ItemSpacing.y after the item into content size, making the group taller!
10190// While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect. Using vertical alignment patterns could trigger this issue.
10191void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
10192{
10193 ImGuiContext& g = *GImGui;
10194 ImGuiWindow* window = g.CurrentWindow;
10195 IM_ASSERT(window->DC.IsSetPos);
10196 window->DC.IsSetPos = false;
10197#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
10198 if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
10199 return;
10200 if (window->SkipItems)
10201 return;
10202 IM_ASSERT(0 && "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries. Please submit an item e.g. Dummy() to validate extent.");
10203#else
10204 window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10205#endif
10206}
10207
10208static void ImGui::ErrorCheckNewFrameSanityChecks()
10209{
10210 ImGuiContext& g = *GImGui;
10211
10212 // Check user IM_ASSERT macro
10213 // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
10214 // If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
10215 // This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
10216 // #define IM_ASSERT(EXPR) if (SomeCode(EXPR)) SomeMoreCode(); // Wrong!
10217 // #define IM_ASSERT(EXPR) do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0) // Correct!
10218 if (true) IM_ASSERT(1); else IM_ASSERT(0);
10219
10220 // Emscripten backends are often imprecise in their submission of DeltaTime. (#6114, #3644)
10221 // Ideally the Emscripten app/backend should aim to fix or smooth this value and avoid feeding zero, but we tolerate it.
10222#ifdef __EMSCRIPTEN__
10223 if (g.IO.DeltaTime <= 0.0f && g.FrameCount > 0)
10224 g.IO.DeltaTime = 0.00001f;
10225#endif
10226
10227 // Check user data
10228 // (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)
10229 IM_ASSERT(g.Initialized);
10230 IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!");
10231 IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
10232 IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!");
10233 IM_ASSERT(g.IO.Fonts->IsBuilt() && "Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()");
10234 IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!");
10235 IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f && "Invalid style setting!");
10236 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
10237 IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
10238 IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
10239 IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
10240#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
10241 for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_COUNT; n++)
10242 IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < ImGuiKey_LegacyNativeKey_END && "io.KeyMap[] contains an out of bound value (need to be 0..511, or -1 for unmapped key)");
10243
10244 // Check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only added in 1.60 WIP)
10245 if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && g.IO.BackendUsingLegacyKeyArrays == 1)
10246 IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
10247#endif
10248
10249 // Check: the io.ConfigWindowsResizeFromEdges option requires backend to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
10250 if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
10251 g.IO.ConfigWindowsResizeFromEdges = false;
10252
10253 // 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.
10254 if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0)
10255 IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
10256 if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0)
10257 IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
10258
10259 // Perform simple checks: multi-viewport and platform windows support
10260 if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
10261 {
10262 if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports))
10263 {
10264 IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference.");
10265 IM_ASSERT(g.PlatformIO.Platform_CreateWindow != NULL && "Platform init didn't install handlers?");
10266 IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
10267 IM_ASSERT(g.PlatformIO.Platform_GetWindowPos != NULL && "Platform init didn't install handlers?");
10268 IM_ASSERT(g.PlatformIO.Platform_SetWindowPos != NULL && "Platform init didn't install handlers?");
10269 IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?");
10270 IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?");
10271 IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?");
10272 IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport.");
10273 if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
10274 IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!");
10275 }
10276 else
10277 {
10278 // Disable feature, our backends do not support it
10279 g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
10280 }
10281
10282 // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs
10283 for (ImGuiPlatformMonitor& mon : g.PlatformIO.Monitors)
10284 {
10285 IM_UNUSED(mon);
10286 IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly.");
10287 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.");
10288 IM_ASSERT(mon.DpiScale != 0.0f);
10289 }
10290 }
10291}
10292
10293static void ImGui::ErrorCheckEndFrameSanityChecks()
10294{
10295 ImGuiContext& g = *GImGui;
10296
10297 // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
10298 // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
10299 // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
10300 // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
10301 // We silently accommodate for this case by ignoring the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
10302 // while still correctly asserting on mid-frame key press events.
10303 const ImGuiKeyChord key_mods = GetMergedModsFromKeys();
10304 IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
10305 IM_UNUSED(key_mods);
10306
10307 // [EXPERIMENTAL] Recover from errors: You may call this yourself before EndFrame().
10308 //ErrorCheckEndFrameRecover();
10309
10310 // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
10311 // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
10312 if (g.CurrentWindowStack.Size != 1)
10313 {
10314 if (g.CurrentWindowStack.Size > 1)
10315 {
10316 ImGuiWindow* window = g.CurrentWindowStack.back().Window; // <-- This window was not Ended!
10317 IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
10318 IM_UNUSED(window);
10319 while (g.CurrentWindowStack.Size > 1)
10320 End();
10321 }
10322 else
10323 {
10324 IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
10325 }
10326 }
10327
10328 IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
10329}
10330
10331// Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
10332// Must be called during or before EndFrame().
10333// This is generally flawed as we are not necessarily End/Popping things in the right order.
10334// FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
10335// FIXME: Can't recover from interleaved BeginTabBar/Begin
10336void ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
10337{
10338 // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
10339 ImGuiContext& g = *GImGui;
10340 while (g.CurrentWindowStack.Size > 0) //-V1044
10341 {
10342 ErrorCheckEndWindowRecover(log_callback, user_data);
10343 ImGuiWindow* window = g.CurrentWindow;
10344 if (g.CurrentWindowStack.Size == 1)
10345 {
10346 IM_ASSERT(window->IsFallbackWindow);
10347 break;
10348 }
10349 if (window->Flags & ImGuiWindowFlags_ChildWindow)
10350 {
10351 if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name);
10352 EndChild();
10353 }
10354 else
10355 {
10356 if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name);
10357 End();
10358 }
10359 }
10360}
10361
10362// Must be called before End()/EndChild()
10363void ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data)
10364{
10365 ImGuiContext& g = *GImGui;
10366 while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
10367 {
10368 if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name);
10369 EndTable();
10370 }
10371
10372 ImGuiWindow* window = g.CurrentWindow;
10373 ImGuiStackSizes* stack_sizes = &g.CurrentWindowStack.back().StackSizesOnBegin;
10374 IM_ASSERT(window != NULL);
10375 while (g.CurrentTabBar != NULL) //-V1044
10376 {
10377 if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name);
10378 EndTabBar();
10379 }
10380 while (window->DC.TreeDepth > 0)
10381 {
10382 if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name);
10383 TreePop();
10384 }
10385 while (g.GroupStack.Size > stack_sizes->SizeOfGroupStack) //-V1044
10386 {
10387 if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name);
10388 EndGroup();
10389 }
10390 while (window->IDStack.Size > 1)
10391 {
10392 if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name);
10393 PopID();
10394 }
10395 while (g.DisabledStackSize > stack_sizes->SizeOfDisabledStack) //-V1044
10396 {
10397 if (log_callback) log_callback(user_data, "Recovered from missing EndDisabled() in '%s'", window->Name);
10398 EndDisabled();
10399 }
10400 while (g.ColorStack.Size > stack_sizes->SizeOfColorStack)
10401 {
10402 if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col));
10403 PopStyleColor();
10404 }
10405 while (g.ItemFlagsStack.Size > stack_sizes->SizeOfItemFlagsStack) //-V1044
10406 {
10407 if (log_callback) log_callback(user_data, "Recovered from missing PopItemFlag() in '%s'", window->Name);
10408 PopItemFlag();
10409 }
10410 while (g.StyleVarStack.Size > stack_sizes->SizeOfStyleVarStack) //-V1044
10411 {
10412 if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name);
10413 PopStyleVar();
10414 }
10415 while (g.FontStack.Size > stack_sizes->SizeOfFontStack) //-V1044
10416 {
10417 if (log_callback) log_callback(user_data, "Recovered from missing PopFont() in '%s'", window->Name);
10418 PopFont();
10419 }
10420 while (g.FocusScopeStack.Size > stack_sizes->SizeOfFocusScopeStack + 1) //-V1044
10421 {
10422 if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name);
10423 PopFocusScope();
10424 }
10425}
10426
10427// Save current stack sizes for later compare
10428void ImGuiStackSizes::SetToContextState(ImGuiContext* ctx)
10429{
10430 ImGuiContext& g = *ctx;
10431 ImGuiWindow* window = g.CurrentWindow;
10432 SizeOfIDStack = (short)window->IDStack.Size;
10433 SizeOfColorStack = (short)g.ColorStack.Size;
10434 SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
10435 SizeOfFontStack = (short)g.FontStack.Size;
10436 SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
10437 SizeOfGroupStack = (short)g.GroupStack.Size;
10438 SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
10439 SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
10440 SizeOfDisabledStack = (short)g.DisabledStackSize;
10441}
10442
10443// Compare to detect usage errors
10444void ImGuiStackSizes::CompareWithContextState(ImGuiContext* ctx)
10445{
10446 ImGuiContext& g = *ctx;
10447 ImGuiWindow* window = g.CurrentWindow;
10448 IM_UNUSED(window);
10449
10450 // Window stacks
10451 // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
10452 IM_ASSERT(SizeOfIDStack == window->IDStack.Size && "PushID/PopID or TreeNode/TreePop Mismatch!");
10453
10454 // Global stacks
10455 // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
10456 IM_ASSERT(SizeOfGroupStack == g.GroupStack.Size && "BeginGroup/EndGroup Mismatch!");
10457 IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!");
10458 IM_ASSERT(SizeOfDisabledStack == g.DisabledStackSize && "BeginDisabled/EndDisabled Mismatch!");
10459 IM_ASSERT(SizeOfItemFlagsStack >= g.ItemFlagsStack.Size && "PushItemFlag/PopItemFlag Mismatch!");
10460 IM_ASSERT(SizeOfColorStack >= g.ColorStack.Size && "PushStyleColor/PopStyleColor Mismatch!");
10461 IM_ASSERT(SizeOfStyleVarStack >= g.StyleVarStack.Size && "PushStyleVar/PopStyleVar Mismatch!");
10462 IM_ASSERT(SizeOfFontStack >= g.FontStack.Size && "PushFont/PopFont Mismatch!");
10463 IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size && "PushFocusScope/PopFocusScope Mismatch!");
10464}
10465
10466//-----------------------------------------------------------------------------
10467// [SECTION] ITEM SUBMISSION
10468//-----------------------------------------------------------------------------
10469// - KeepAliveID()
10470// - ItemHandleShortcut() [Internal]
10471// - ItemAdd()
10472//-----------------------------------------------------------------------------
10473
10474// 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().
10475void ImGui::KeepAliveID(ImGuiID id)
10476{
10477 ImGuiContext& g = *GImGui;
10478 if (g.ActiveId == id)
10479 g.ActiveIdIsAlive = id;
10480 if (g.ActiveIdPreviousFrame == id)
10481 g.ActiveIdPreviousFrameIsAlive = true;
10482}
10483
10484static void ItemHandleShortcut(ImGuiID id)
10485{
10486 // FIXME: Generalize Activation queue?
10487 ImGuiContext& g = *GImGui;
10488 if (ImGui::Shortcut(g.NextItemData.Shortcut, id, ImGuiInputFlags_None) && g.NavActivateId == 0)
10489 {
10490 g.NavActivateId = id; // Will effectively disable clipping.
10491 g.NavActivateFlags = ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_FromShortcut;
10492 if (g.ActiveId == 0 || g.ActiveId == id)
10493 g.NavActivateDownId = g.NavActivatePressedId = id;
10494 ImGui::NavHighlightActivated(id);
10495 }
10496}
10497
10498// Declare item bounding box for clipping and interaction.
10499// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
10500// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
10501// THIS IS IN THE PERFORMANCE CRITICAL PATH (UNTIL THE CLIPPING TEST AND EARLY-RETURN)
10502bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
10503{
10504 ImGuiContext& g = *GImGui;
10505 ImGuiWindow* window = g.CurrentWindow;
10506
10507 // Set item data
10508 // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
10509 g.LastItemData.ID = id;
10510 g.LastItemData.Rect = bb;
10511 g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
10512 g.LastItemData.InFlags = g.CurrentItemFlags | g.NextItemData.ItemFlags | extra_flags;
10513 g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
10514 // Note: we don't copy 'g.NextItemData.SelectionUserData' to an hypothetical g.LastItemData.SelectionUserData: since the former is not cleared.
10515
10516 if (id != 0)
10517 {
10518 KeepAliveID(id);
10519
10520 // Directional navigation processing
10521 // Runs prior to clipping early-out
10522 // (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
10523 // (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
10524 // unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
10525 // thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
10526 // We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
10527 // to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
10528 // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
10529 // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
10530 if (!(g.LastItemData.InFlags & ImGuiItemFlags_NoNav))
10531 {
10532 // FIMXE-NAV: investigate changing the window tests into a simple 'if (g.NavFocusScopeId == g.CurrentFocusScopeId)' test.
10533 window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
10534 if (g.NavId == id || g.NavAnyRequest)
10535 if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
10536 if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
10537 NavProcessItem();
10538 }
10539
10540 if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasShortcut)
10541 ItemHandleShortcut(id);
10542 }
10543
10544 // Lightweight clear of SetNextItemXXX data.
10545 g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
10546 g.NextItemData.ItemFlags = ImGuiItemFlags_None;
10547
10548#ifdef IMGUI_ENABLE_TEST_ENGINE
10549 if (id != 0)
10550 IMGUI_TEST_ENGINE_ITEM_ADD(id, g.LastItemData.NavRect, &g.LastItemData);
10551#endif
10552
10553 // Clipping test
10554 // (this is a modified copy of IsClippedEx() so we can reuse the is_rect_visible value)
10555 //const bool is_clipped = IsClippedEx(bb, id);
10556 //if (is_clipped)
10557 // return false;
10558 // g.NavActivateId is not necessarily == g.NavId, in the case of remote activation (e.g. shortcuts)
10559 const bool is_rect_visible = bb.Overlaps(window->ClipRect);
10560 if (!is_rect_visible)
10561 if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
10562 if (!g.LogEnabled)
10563 return false;
10564
10565 // [DEBUG]
10566#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10567 if (id != 0)
10568 {
10569 if (id == g.DebugLocateId)
10570 DebugLocateItemResolveWithLastItem();
10571
10572 // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
10573 // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
10574 // READ THE FAQ: https://dearimgui.com/faq
10575 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!");
10576 }
10577 //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
10578 //if ((g.LastItemData.InFlags & ImGuiItemFlags_NoNav) == 0)
10579 // window->DrawList->AddRect(g.LastItemData.NavRect.Min, g.LastItemData.NavRect.Max, IM_COL32(255,255,0,255)); // [DEBUG]
10580#endif
10581
10582 // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
10583 if (is_rect_visible)
10584 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
10585 if (IsMouseHoveringRect(bb.Min, bb.Max))
10586 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
10587 return true;
10588}
10589
10590
10591//-----------------------------------------------------------------------------
10592// [SECTION] LAYOUT
10593//-----------------------------------------------------------------------------
10594// - ItemSize()
10595// - SameLine()
10596// - GetCursorScreenPos()
10597// - SetCursorScreenPos()
10598// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
10599// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
10600// - GetCursorStartPos()
10601// - Indent()
10602// - Unindent()
10603// - SetNextItemWidth()
10604// - PushItemWidth()
10605// - PushMultiItemsWidths()
10606// - PopItemWidth()
10607// - CalcItemWidth()
10608// - CalcItemSize()
10609// - GetTextLineHeight()
10610// - GetTextLineHeightWithSpacing()
10611// - GetFrameHeight()
10612// - GetFrameHeightWithSpacing()
10613// - GetContentRegionMax()
10614// - GetContentRegionMaxAbs() [Internal]
10615// - GetContentRegionAvail(),
10616// - GetWindowContentRegionMin(), GetWindowContentRegionMax()
10617// - BeginGroup()
10618// - EndGroup()
10619// Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns.
10620//-----------------------------------------------------------------------------
10621
10622// Advance cursor given item size for layout.
10623// Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
10624// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
10625// THIS IS IN THE PERFORMANCE CRITICAL PATH.
10626void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
10627{
10628 ImGuiContext& g = *GImGui;
10629 ImGuiWindow* window = g.CurrentWindow;
10630 if (window->SkipItems)
10631 return;
10632
10633 // We increase the height in this function to accommodate for baseline offset.
10634 // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
10635 // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
10636 const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
10637
10638 const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y;
10639 const float line_height = ImMax(window->DC.CurrLineSize.y, /*ImMax(*/window->DC.CursorPos.y - line_y1/*, 0.0f)*/ + size.y + offset_to_match_baseline_y);
10640
10641 // Always align ourselves on pixel boundaries
10642 //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]
10643 window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
10644 window->DC.CursorPosPrevLine.y = line_y1;
10645 window->DC.CursorPos.x = IM_TRUNC(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); // Next line
10646 window->DC.CursorPos.y = IM_TRUNC(line_y1 + line_height + g.Style.ItemSpacing.y); // Next line
10647 window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
10648 window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
10649 //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
10650
10651 window->DC.PrevLineSize.y = line_height;
10652 window->DC.CurrLineSize.y = 0.0f;
10653 window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
10654 window->DC.CurrLineTextBaseOffset = 0.0f;
10655 window->DC.IsSameLine = window->DC.IsSetPos = false;
10656
10657 // Horizontal layout mode
10658 if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
10659 SameLine();
10660}
10661
10662// Gets back to previous line and continue with horizontal layout
10663// offset_from_start_x == 0 : follow right after previous item
10664// offset_from_start_x != 0 : align to specified x position (relative to window/group left)
10665// spacing_w < 0 : use default spacing if offset_from_start_x == 0, no spacing if offset_from_start_x != 0
10666// spacing_w >= 0 : enforce spacing amount
10667void ImGui::SameLine(float offset_from_start_x, float spacing_w)
10668{
10669 ImGuiContext& g = *GImGui;
10670 ImGuiWindow* window = g.CurrentWindow;
10671 if (window->SkipItems)
10672 return;
10673
10674 if (offset_from_start_x != 0.0f)
10675 {
10676 if (spacing_w < 0.0f)
10677 spacing_w = 0.0f;
10678 window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
10679 window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
10680 }
10681 else
10682 {
10683 if (spacing_w < 0.0f)
10684 spacing_w = g.Style.ItemSpacing.x;
10685 window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
10686 window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
10687 }
10688 window->DC.CurrLineSize = window->DC.PrevLineSize;
10689 window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
10690 window->DC.IsSameLine = true;
10691}
10692
10693ImVec2 ImGui::GetCursorScreenPos()
10694{
10695 ImGuiWindow* window = GetCurrentWindowRead();
10696 return window->DC.CursorPos;
10697}
10698
10699void ImGui::SetCursorScreenPos(const ImVec2& pos)
10700{
10701 ImGuiWindow* window = GetCurrentWindow();
10702 window->DC.CursorPos = pos;
10703 //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10704 window->DC.IsSetPos = true;
10705}
10706
10707// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
10708// 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'.
10709ImVec2 ImGui::GetCursorPos()
10710{
10711 ImGuiWindow* window = GetCurrentWindowRead();
10712 return window->DC.CursorPos - window->Pos + window->Scroll;
10713}
10714
10715float ImGui::GetCursorPosX()
10716{
10717 ImGuiWindow* window = GetCurrentWindowRead();
10718 return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
10719}
10720
10721float ImGui::GetCursorPosY()
10722{
10723 ImGuiWindow* window = GetCurrentWindowRead();
10724 return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
10725}
10726
10727void ImGui::SetCursorPos(const ImVec2& local_pos)
10728{
10729 ImGuiWindow* window = GetCurrentWindow();
10730 window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
10731 //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10732 window->DC.IsSetPos = true;
10733}
10734
10735void ImGui::SetCursorPosX(float x)
10736{
10737 ImGuiWindow* window = GetCurrentWindow();
10738 window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
10739 //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
10740 window->DC.IsSetPos = true;
10741}
10742
10743void ImGui::SetCursorPosY(float y)
10744{
10745 ImGuiWindow* window = GetCurrentWindow();
10746 window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
10747 //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
10748 window->DC.IsSetPos = true;
10749}
10750
10751ImVec2 ImGui::GetCursorStartPos()
10752{
10753 ImGuiWindow* window = GetCurrentWindowRead();
10754 return window->DC.CursorStartPos - window->Pos;
10755}
10756
10757void ImGui::Indent(float indent_w)
10758{
10759 ImGuiContext& g = *GImGui;
10760 ImGuiWindow* window = GetCurrentWindow();
10761 window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10762 window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10763}
10764
10765void ImGui::Unindent(float indent_w)
10766{
10767 ImGuiContext& g = *GImGui;
10768 ImGuiWindow* window = GetCurrentWindow();
10769 window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10770 window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10771}
10772
10773// Affect large frame+labels widgets only.
10774void ImGui::SetNextItemWidth(float item_width)
10775{
10776 ImGuiContext& g = *GImGui;
10777 g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
10778 g.NextItemData.Width = item_width;
10779}
10780
10781// FIXME: Remove the == 0.0f behavior?
10782void ImGui::PushItemWidth(float item_width)
10783{
10784 ImGuiContext& g = *GImGui;
10785 ImGuiWindow* window = g.CurrentWindow;
10786 window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
10787 window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
10788 g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10789}
10790
10791void ImGui::PushMultiItemsWidths(int components, float w_full)
10792{
10793 ImGuiContext& g = *GImGui;
10794 ImGuiWindow* window = g.CurrentWindow;
10795 IM_ASSERT(components > 0);
10796 const ImGuiStyle& style = g.Style;
10797 window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
10798 float w_items = w_full - style.ItemInnerSpacing.x * (components - 1);
10799 float prev_split = w_items;
10800 for (int i = components - 1; i > 0; i--)
10801 {
10802 float next_split = IM_TRUNC(w_items * i / components);
10803 window->DC.ItemWidthStack.push_back(ImMax(prev_split - next_split, 1.0f));
10804 prev_split = next_split;
10805 }
10806 window->DC.ItemWidth = ImMax(prev_split, 1.0f);
10807 g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10808}
10809
10810void ImGui::PopItemWidth()
10811{
10812 ImGuiWindow* window = GetCurrentWindow();
10813 window->DC.ItemWidth = window->DC.ItemWidthStack.back();
10814 window->DC.ItemWidthStack.pop_back();
10815}
10816
10817// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
10818// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
10819float ImGui::CalcItemWidth()
10820{
10821 ImGuiContext& g = *GImGui;
10822 ImGuiWindow* window = g.CurrentWindow;
10823 float w;
10824 if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
10825 w = g.NextItemData.Width;
10826 else
10827 w = window->DC.ItemWidth;
10828 if (w < 0.0f)
10829 {
10830 float region_max_x = GetContentRegionMaxAbs().x;
10831 w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
10832 }
10833 w = IM_TRUNC(w);
10834 return w;
10835}
10836
10837// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
10838// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
10839// Note that only CalcItemWidth() is publicly exposed.
10840// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
10841ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
10842{
10843 ImGuiContext& g = *GImGui;
10844 ImGuiWindow* window = g.CurrentWindow;
10845
10846 ImVec2 region_max;
10847 if (size.x < 0.0f || size.y < 0.0f)
10848 region_max = GetContentRegionMaxAbs();
10849
10850 if (size.x == 0.0f)
10851 size.x = default_w;
10852 else if (size.x < 0.0f)
10853 size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
10854
10855 if (size.y == 0.0f)
10856 size.y = default_h;
10857 else if (size.y < 0.0f)
10858 size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
10859
10860 return size;
10861}
10862
10863float ImGui::GetTextLineHeight()
10864{
10865 ImGuiContext& g = *GImGui;
10866 return g.FontSize;
10867}
10868
10869float ImGui::GetTextLineHeightWithSpacing()
10870{
10871 ImGuiContext& g = *GImGui;
10872 return g.FontSize + g.Style.ItemSpacing.y;
10873}
10874
10875float ImGui::GetFrameHeight()
10876{
10877 ImGuiContext& g = *GImGui;
10878 return g.FontSize + g.Style.FramePadding.y * 2.0f;
10879}
10880
10881float ImGui::GetFrameHeightWithSpacing()
10882{
10883 ImGuiContext& g = *GImGui;
10884 return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
10885}
10886
10887// FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW "WORK RECT" API. Thanks for your patience!
10888
10889// FIXME: This is in window space (not screen space!).
10890ImVec2 ImGui::GetContentRegionMax()
10891{
10892 ImGuiContext& g = *GImGui;
10893 ImGuiWindow* window = g.CurrentWindow;
10894 ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
10895 return mx - window->Pos;
10896}
10897
10898// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
10899ImVec2 ImGui::GetContentRegionMaxAbs()
10900{
10901 ImGuiContext& g = *GImGui;
10902 ImGuiWindow* window = g.CurrentWindow;
10903 ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
10904 return mx;
10905}
10906
10907ImVec2 ImGui::GetContentRegionAvail()
10908{
10909 ImGuiWindow* window = GImGui->CurrentWindow;
10910 return GetContentRegionMaxAbs() - window->DC.CursorPos;
10911}
10912
10913// In window space (not screen space!)
10914ImVec2 ImGui::GetWindowContentRegionMin()
10915{
10916 ImGuiWindow* window = GImGui->CurrentWindow;
10917 return window->ContentRegionRect.Min - window->Pos;
10918}
10919
10920ImVec2 ImGui::GetWindowContentRegionMax()
10921{
10922 ImGuiWindow* window = GImGui->CurrentWindow;
10923 return window->ContentRegionRect.Max - window->Pos;
10924}
10925
10926// 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.)
10927// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
10928// FIXME-OPT: Could we safely early out on ->SkipItems?
10929void ImGui::BeginGroup()
10930{
10931 ImGuiContext& g = *GImGui;
10932 ImGuiWindow* window = g.CurrentWindow;
10933
10934 g.GroupStack.resize(g.GroupStack.Size + 1);
10935 ImGuiGroupData& group_data = g.GroupStack.back();
10936 group_data.WindowID = window->ID;
10937 group_data.BackupCursorPos = window->DC.CursorPos;
10938 group_data.BackupCursorPosPrevLine = window->DC.CursorPosPrevLine;
10939 group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
10940 group_data.BackupIndent = window->DC.Indent;
10941 group_data.BackupGroupOffset = window->DC.GroupOffset;
10942 group_data.BackupCurrLineSize = window->DC.CurrLineSize;
10943 group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
10944 group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
10945 group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
10946 group_data.BackupIsSameLine = window->DC.IsSameLine;
10947 group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
10948 group_data.EmitItem = true;
10949
10950 window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
10951 window->DC.Indent = window->DC.GroupOffset;
10952 window->DC.CursorMaxPos = window->DC.CursorPos;
10953 window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
10954 if (g.LogEnabled)
10955 g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10956}
10957
10958void ImGui::EndGroup()
10959{
10960 ImGuiContext& g = *GImGui;
10961 ImGuiWindow* window = g.CurrentWindow;
10962 IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
10963
10964 ImGuiGroupData& group_data = g.GroupStack.back();
10965 IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
10966
10967 if (window->DC.IsSetPos)
10968 ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
10969
10970 ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
10971
10972 window->DC.CursorPos = group_data.BackupCursorPos;
10973 window->DC.CursorPosPrevLine = group_data.BackupCursorPosPrevLine;
10974 window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
10975 window->DC.Indent = group_data.BackupIndent;
10976 window->DC.GroupOffset = group_data.BackupGroupOffset;
10977 window->DC.CurrLineSize = group_data.BackupCurrLineSize;
10978 window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
10979 window->DC.IsSameLine = group_data.BackupIsSameLine;
10980 if (g.LogEnabled)
10981 g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10982
10983 if (!group_data.EmitItem)
10984 {
10985 g.GroupStack.pop_back();
10986 return;
10987 }
10988
10989 window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
10990 ItemSize(group_bb.GetSize());
10991 ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop);
10992
10993 // 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.
10994 // 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.
10995 // Also if you grep for LastItemId you'll notice it is only used in that context.
10996 // (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.)
10997 const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
10998 const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
10999 if (group_contains_curr_active_id)
11000 g.LastItemData.ID = g.ActiveId;
11001 else if (group_contains_prev_active_id)
11002 g.LastItemData.ID = g.ActiveIdPreviousFrame;
11003 g.LastItemData.Rect = group_bb;
11004
11005 // Forward Hovered flag
11006 const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
11007 if (group_contains_curr_hovered_id)
11008 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
11009
11010 // Forward Edited flag
11011 if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
11012 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
11013
11014 // Forward Deactivated flag
11015 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
11016 if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
11017 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
11018
11019 g.GroupStack.pop_back();
11020 if (g.DebugShowGroupRects)
11021 window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug]
11022}
11023
11024
11025//-----------------------------------------------------------------------------
11026// [SECTION] SCROLLING
11027//-----------------------------------------------------------------------------
11028
11029// Helper to snap on edges when aiming at an item very close to the edge,
11030// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
11031// When we refactor the scrolling API this may be configurable with a flag?
11032// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
11033static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
11034{
11035 if (target <= snap_min + snap_threshold)
11036 return ImLerp(snap_min, target, center_ratio);
11037 if (target >= snap_max - snap_threshold)
11038 return ImLerp(target, snap_max, center_ratio);
11039 return target;
11040}
11041
11042static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
11043{
11044 ImVec2 scroll = window->Scroll;
11045 ImVec2 decoration_size(window->DecoOuterSizeX1 + window->DecoInnerSizeX1 + window->DecoOuterSizeX2, window->DecoOuterSizeY1 + window->DecoInnerSizeY1 + window->DecoOuterSizeY2);
11046 for (int axis = 0; axis < 2; axis++)
11047 {
11048 if (window->ScrollTarget[axis] < FLT_MAX)
11049 {
11050 float center_ratio = window->ScrollTargetCenterRatio[axis];
11051 float scroll_target = window->ScrollTarget[axis];
11052 if (window->ScrollTargetEdgeSnapDist[axis] > 0.0f)
11053 {
11054 float snap_min = 0.0f;
11055 float snap_max = window->ScrollMax[axis] + window->SizeFull[axis] - decoration_size[axis];
11056 scroll_target = CalcScrollEdgeSnap(scroll_target, snap_min, snap_max, window->ScrollTargetEdgeSnapDist[axis], center_ratio);
11057 }
11058 scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]);
11059 }
11060 scroll[axis] = IM_ROUND(ImMax(scroll[axis], 0.0f));
11061 if (!window->Collapsed && !window->SkipItems)
11062 scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]);
11063 }
11064 return scroll;
11065}
11066
11067void ImGui::ScrollToItem(ImGuiScrollFlags flags)
11068{
11069 ImGuiContext& g = *GImGui;
11070 ImGuiWindow* window = g.CurrentWindow;
11071 ScrollToRectEx(window, g.LastItemData.NavRect, flags);
11072}
11073
11074void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
11075{
11076 ScrollToRectEx(window, item_rect, flags);
11077}
11078
11079// Scroll to keep newly navigated item fully into view
11080ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
11081{
11082 ImGuiContext& g = *GImGui;
11083 ImRect scroll_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
11084 scroll_rect.Min.x = ImMin(scroll_rect.Min.x + window->DecoInnerSizeX1, scroll_rect.Max.x);
11085 scroll_rect.Min.y = ImMin(scroll_rect.Min.y + window->DecoInnerSizeY1, scroll_rect.Max.y);
11086 //GetForegroundDrawList(window)->AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0f, 0, 5.0f); // [DEBUG]
11087 //GetForegroundDrawList(window)->AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE); // [DEBUG]
11088
11089 // Check that only one behavior is selected per axis
11090 IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
11091 IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
11092
11093 // Defaults
11094 ImGuiScrollFlags in_flags = flags;
11095 if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
11096 flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
11097 if ((flags & ImGuiScrollFlags_MaskY_) == 0)
11098 flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
11099
11100 const bool fully_visible_x = item_rect.Min.x >= scroll_rect.Min.x && item_rect.Max.x <= scroll_rect.Max.x;
11101 const bool fully_visible_y = item_rect.Min.y >= scroll_rect.Min.y && item_rect.Max.y <= scroll_rect.Max.y;
11102 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;
11103 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;
11104
11105 if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
11106 {
11107 if (item_rect.Min.x < scroll_rect.Min.x || !can_be_fully_visible_x)
11108 SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f);
11109 else if (item_rect.Max.x >= scroll_rect.Max.x)
11110 SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f);
11111 }
11112 else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
11113 {
11114 if (can_be_fully_visible_x)
11115 SetScrollFromPosX(window, ImTrunc((item_rect.Min.x + item_rect.Max.x) * 0.5f) - window->Pos.x, 0.5f);
11116 else
11117 SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x, 0.0f);
11118 }
11119
11120 if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
11121 {
11122 if (item_rect.Min.y < scroll_rect.Min.y || !can_be_fully_visible_y)
11123 SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f);
11124 else if (item_rect.Max.y >= scroll_rect.Max.y)
11125 SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f);
11126 }
11127 else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
11128 {
11129 if (can_be_fully_visible_y)
11130 SetScrollFromPosY(window, ImTrunc((item_rect.Min.y + item_rect.Max.y) * 0.5f) - window->Pos.y, 0.5f);
11131 else
11132 SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y, 0.0f);
11133 }
11134
11135 ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
11136 ImVec2 delta_scroll = next_scroll - window->Scroll;
11137
11138 // Also scroll parent window to keep us into view if necessary
11139 if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
11140 {
11141 // FIXME-SCROLL: May be an option?
11142 if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
11143 in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
11144 if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
11145 in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
11146 delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags);
11147 }
11148
11149 return delta_scroll;
11150}
11151
11152float ImGui::GetScrollX()
11153{
11154 ImGuiWindow* window = GImGui->CurrentWindow;
11155 return window->Scroll.x;
11156}
11157
11158float ImGui::GetScrollY()
11159{
11160 ImGuiWindow* window = GImGui->CurrentWindow;
11161 return window->Scroll.y;
11162}
11163
11164float ImGui::GetScrollMaxX()
11165{
11166 ImGuiWindow* window = GImGui->CurrentWindow;
11167 return window->ScrollMax.x;
11168}
11169
11170float ImGui::GetScrollMaxY()
11171{
11172 ImGuiWindow* window = GImGui->CurrentWindow;
11173 return window->ScrollMax.y;
11174}
11175
11176void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
11177{
11178 window->ScrollTarget.x = scroll_x;
11179 window->ScrollTargetCenterRatio.x = 0.0f;
11180 window->ScrollTargetEdgeSnapDist.x = 0.0f;
11181}
11182
11183void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
11184{
11185 window->ScrollTarget.y = scroll_y;
11186 window->ScrollTargetCenterRatio.y = 0.0f;
11187 window->ScrollTargetEdgeSnapDist.y = 0.0f;
11188}
11189
11190void ImGui::SetScrollX(float scroll_x)
11191{
11192 ImGuiContext& g = *GImGui;
11193 SetScrollX(g.CurrentWindow, scroll_x);
11194}
11195
11196void ImGui::SetScrollY(float scroll_y)
11197{
11198 ImGuiContext& g = *GImGui;
11199 SetScrollY(g.CurrentWindow, scroll_y);
11200}
11201
11202// Note that a local position will vary depending on initial scroll value,
11203// This is a little bit confusing so bear with us:
11204// - local_pos = (absolution_pos - window->Pos)
11205// - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
11206// and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
11207// - They mostly exist because of legacy API.
11208// Following the rules above, when trying to work with scrolling code, consider that:
11209// - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
11210// - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
11211// 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
11212void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
11213{
11214 IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
11215 window->ScrollTarget.x = IM_TRUNC(local_x - window->DecoOuterSizeX1 - window->DecoInnerSizeX1 + window->Scroll.x); // Convert local position to scroll offset
11216 window->ScrollTargetCenterRatio.x = center_x_ratio;
11217 window->ScrollTargetEdgeSnapDist.x = 0.0f;
11218}
11219
11220void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
11221{
11222 IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
11223 window->ScrollTarget.y = IM_TRUNC(local_y - window->DecoOuterSizeY1 - window->DecoInnerSizeY1 + window->Scroll.y); // Convert local position to scroll offset
11224 window->ScrollTargetCenterRatio.y = center_y_ratio;
11225 window->ScrollTargetEdgeSnapDist.y = 0.0f;
11226}
11227
11228void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
11229{
11230 ImGuiContext& g = *GImGui;
11231 SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
11232}
11233
11234void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
11235{
11236 ImGuiContext& g = *GImGui;
11237 SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
11238}
11239
11240// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
11241void ImGui::SetScrollHereX(float center_x_ratio)
11242{
11243 ImGuiContext& g = *GImGui;
11244 ImGuiWindow* window = g.CurrentWindow;
11245 float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);
11246 float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio);
11247 SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
11248
11249 // Tweak: snap on edges when aiming at an item very close to the edge
11250 window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
11251}
11252
11253// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
11254void ImGui::SetScrollHereY(float center_y_ratio)
11255{
11256 ImGuiContext& g = *GImGui;
11257 ImGuiWindow* window = g.CurrentWindow;
11258 float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);
11259 float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
11260 SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
11261
11262 // Tweak: snap on edges when aiming at an item very close to the edge
11263 window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
11264}
11265
11266//-----------------------------------------------------------------------------
11267// [SECTION] TOOLTIPS
11268//-----------------------------------------------------------------------------
11269
11270bool ImGui::BeginTooltip()
11271{
11272 return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
11273}
11274
11275bool ImGui::BeginItemTooltip()
11276{
11277 if (!IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11278 return false;
11279 return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
11280}
11281
11282bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
11283{
11284 ImGuiContext& g = *GImGui;
11285
11286 if (g.DragDropWithinSource || g.DragDropWithinTarget)
11287 {
11288 // Drag and Drop tooltips are positioning differently than other tooltips:
11289 // - offset visibility to increase visibility around mouse.
11290 // - never clamp within outer viewport boundary.
11291 // We call SetNextWindowPos() to enforce position and disable clamping.
11292 // See FindBestWindowPosForPopup() for positionning logic of other tooltips (not drag and drop ones).
11293 //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
11294 ImVec2 tooltip_pos = g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET * g.Style.MouseCursorScale;
11295 SetNextWindowPos(tooltip_pos);
11296 SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
11297 //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
11298 tooltip_flags |= ImGuiTooltipFlags_OverridePrevious;
11299 }
11300
11301 char window_name[16];
11302 ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
11303 if (tooltip_flags & ImGuiTooltipFlags_OverridePrevious)
11304 if (ImGuiWindow* window = FindWindowByName(window_name))
11305 if (window->Active)
11306 {
11307 // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
11308 SetWindowHiddenAndSkipItemsForCurrentFrame(window);
11309 ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
11310 }
11311 ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking;
11312 Begin(window_name, NULL, flags | extra_window_flags);
11313 // 2023-03-09: Added bool return value to the API, but currently always returning true.
11314 // If this ever returns false we need to update BeginDragDropSource() accordingly.
11315 //if (!ret)
11316 // End();
11317 //return ret;
11318 return true;
11319}
11320
11321void ImGui::EndTooltip()
11322{
11323 IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
11324 End();
11325}
11326
11327void ImGui::SetTooltip(const char* fmt, ...)
11328{
11329 va_list args;
11330 va_start(args, fmt);
11331 SetTooltipV(fmt, args);
11332 va_end(args);
11333}
11334
11335void ImGui::SetTooltipV(const char* fmt, va_list args)
11336{
11337 if (!BeginTooltipEx(ImGuiTooltipFlags_OverridePrevious, ImGuiWindowFlags_None))
11338 return;
11339 TextV(fmt, args);
11340 EndTooltip();
11341}
11342
11343// Shortcut to use 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav'.
11344// Defaults to == ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort when using the mouse.
11345void ImGui::SetItemTooltip(const char* fmt, ...)
11346{
11347 va_list args;
11348 va_start(args, fmt);
11349 if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11350 SetTooltipV(fmt, args);
11351 va_end(args);
11352}
11353
11354void ImGui::SetItemTooltipV(const char* fmt, va_list args)
11355{
11356 if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11357 SetTooltipV(fmt, args);
11358}
11359
11360
11361//-----------------------------------------------------------------------------
11362// [SECTION] POPUPS
11363//-----------------------------------------------------------------------------
11364
11365// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
11366bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
11367{
11368 ImGuiContext& g = *GImGui;
11369 if (popup_flags & ImGuiPopupFlags_AnyPopupId)
11370 {
11371 // Return true if any popup is open at the current BeginPopup() level of the popup stack
11372 // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
11373 IM_ASSERT(id == 0);
11374 if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
11375 return g.OpenPopupStack.Size > 0;
11376 else
11377 return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
11378 }
11379 else
11380 {
11381 if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
11382 {
11383 // Return true if the popup is open anywhere in the popup stack
11384 for (ImGuiPopupData& popup_data : g.OpenPopupStack)
11385 if (popup_data.PopupId == id)
11386 return true;
11387 return false;
11388 }
11389 else
11390 {
11391 // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
11392 return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
11393 }
11394 }
11395}
11396
11397bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
11398{
11399 ImGuiContext& g = *GImGui;
11400 ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
11401 if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
11402 IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
11403 return IsPopupOpen(id, popup_flags);
11404}
11405
11406// Also see FindBlockingModal(NULL)
11407ImGuiWindow* ImGui::GetTopMostPopupModal()
11408{
11409 ImGuiContext& g = *GImGui;
11410 for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11411 if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11412 if (popup->Flags & ImGuiWindowFlags_Modal)
11413 return popup;
11414 return NULL;
11415}
11416
11417// See Demo->Stacked Modal to confirm what this is for.
11418ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
11419{
11420 ImGuiContext& g = *GImGui;
11421 for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11422 if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11423 if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(popup))
11424 return popup;
11425 return NULL;
11426}
11427
11428void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
11429{
11430 ImGuiContext& g = *GImGui;
11431 ImGuiID id = g.CurrentWindow->GetID(str_id);
11432 IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X)\n", str_id, id);
11433 OpenPopupEx(id, popup_flags);
11434}
11435
11436void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
11437{
11438 OpenPopupEx(id, popup_flags);
11439}
11440
11441// Mark popup as open (toggle toward open state).
11442// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
11443// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
11444// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
11445void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
11446{
11447 ImGuiContext& g = *GImGui;
11448 ImGuiWindow* parent_window = g.CurrentWindow;
11449 const int current_stack_size = g.BeginPopupStack.Size;
11450
11451 if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
11452 if (IsPopupOpen((ImGuiID)0, ImGuiPopupFlags_AnyPopupId))
11453 return;
11454
11455 ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
11456 popup_ref.PopupId = id;
11457 popup_ref.Window = NULL;
11458 popup_ref.RestoreNavWindow = g.NavWindow; // When popup closes focus may be restored to NavWindow (depend on window type).
11459 popup_ref.OpenFrameCount = g.FrameCount;
11460 popup_ref.OpenParentId = parent_window->IDStack.back();
11461 popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
11462 popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
11463
11464 IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id);
11465 if (g.OpenPopupStack.Size < current_stack_size + 1)
11466 {
11467 g.OpenPopupStack.push_back(popup_ref);
11468 }
11469 else
11470 {
11471 // Gently handle the user mistakenly calling OpenPopup() every frames: it is likely a programming mistake!
11472 // However, if we were to run the regular code path, the ui would become completely unusable because the popup will always be
11473 // in hidden-while-calculating-size state _while_ claiming focus. Which is extremely confusing situation for the programmer.
11474 // Instead, for successive frames calls to OpenPopup(), we silently avoid reopening even if ImGuiPopupFlags_NoReopen is not specified.
11475 bool keep_existing = false;
11476 if (g.OpenPopupStack[current_stack_size].PopupId == id)
11477 if ((g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1) || (popup_flags & ImGuiPopupFlags_NoReopen))
11478 keep_existing = true;
11479 if (keep_existing)
11480 {
11481 // No reopen
11482 g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
11483 }
11484 else
11485 {
11486 // Reopen: close child popups if any, then flag popup for open/reopen (set position, focus, init navigation)
11487 ClosePopupToLevel(current_stack_size, true);
11488 g.OpenPopupStack.push_back(popup_ref);
11489 }
11490
11491 // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
11492 // This is equivalent to what ClosePopupToLevel() does.
11493 //if (g.OpenPopupStack[current_stack_size].PopupId == id)
11494 // FocusWindow(parent_window);
11495 }
11496}
11497
11498// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
11499// This function closes any popups that are over 'ref_window'.
11500void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
11501{
11502 ImGuiContext& g = *GImGui;
11503 if (g.OpenPopupStack.Size == 0)
11504 return;
11505
11506 // Don't close our own child popup windows.
11507 //IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\") restore_under=%d\n", ref_window ? ref_window->Name : "<NULL>", restore_focus_to_window_under_popup);
11508 int popup_count_to_keep = 0;
11509 if (ref_window)
11510 {
11511 // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
11512 for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
11513 {
11514 ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
11515 if (!popup.Window)
11516 continue;
11517 IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
11518
11519 // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
11520 // - Clicking/Focusing Window2 won't close Popup1:
11521 // Window -> Popup1 -> Window2(Ref)
11522 // - Clicking/focusing Popup1 will close Popup2 and Popup3:
11523 // Window -> Popup1(Ref) -> Popup2 -> Popup3
11524 // - Each popups may contain child windows, which is why we compare ->RootWindowDockTree!
11525 // Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
11526 // We step through every popup from bottom to top to validate their position relative to reference window.
11527 bool ref_window_is_descendent_of_popup = false;
11528 for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
11529 if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
11530 //if (popup_window->RootWindowDockTree == ref_window->RootWindowDockTree) // FIXME-MERGE
11531 if (IsWindowWithinBeginStackOf(ref_window, popup_window))
11532 {
11533 ref_window_is_descendent_of_popup = true;
11534 break;
11535 }
11536 if (!ref_window_is_descendent_of_popup)
11537 break;
11538 }
11539 }
11540 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
11541 {
11542 IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : "<NULL>");
11543 ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
11544 }
11545}
11546
11547void ImGui::ClosePopupsExceptModals()
11548{
11549 ImGuiContext& g = *GImGui;
11550
11551 int popup_count_to_keep;
11552 for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
11553 {
11554 ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
11555 if (!window || (window->Flags & ImGuiWindowFlags_Modal))
11556 break;
11557 }
11558 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
11559 ClosePopupToLevel(popup_count_to_keep, true);
11560}
11561
11562void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
11563{
11564 ImGuiContext& g = *GImGui;
11565 IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d\n", remaining, restore_focus_to_window_under_popup);
11566 IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
11567
11568 // Trim open popup stack
11569 ImGuiPopupData prev_popup = g.OpenPopupStack[remaining];
11570 g.OpenPopupStack.resize(remaining);
11571
11572 // 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)
11573 if (restore_focus_to_window_under_popup && prev_popup.Window)
11574 {
11575 ImGuiWindow* popup_window = prev_popup.Window;
11576 ImGuiWindow* focus_window = (popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : prev_popup.RestoreNavWindow;
11577 if (focus_window && !focus_window->WasActive)
11578 FocusTopMostWindowUnderOne(popup_window, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild); // Fallback
11579 else
11580 FocusWindow(focus_window, (g.NavLayer == ImGuiNavLayer_Main) ? ImGuiFocusRequestFlags_RestoreFocusedChild : ImGuiFocusRequestFlags_None);
11581 }
11582}
11583
11584// Close the popup we have begin-ed into.
11585void ImGui::CloseCurrentPopup()
11586{
11587 ImGuiContext& g = *GImGui;
11588 int popup_idx = g.BeginPopupStack.Size - 1;
11589 if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
11590 return;
11591
11592 // Closing a menu closes its top-most parent popup (unless a modal)
11593 while (popup_idx > 0)
11594 {
11595 ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
11596 ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
11597 bool close_parent = false;
11598 if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
11599 if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
11600 close_parent = true;
11601 if (!close_parent)
11602 break;
11603 popup_idx--;
11604 }
11605 IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
11606 ClosePopupToLevel(popup_idx, true);
11607
11608 // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
11609 // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
11610 // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
11611 if (ImGuiWindow* window = g.NavWindow)
11612 window->DC.NavHideHighlightOneFrame = true;
11613}
11614
11615// Attention! BeginPopup() adds default flags which BeginPopupEx()!
11616bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags)
11617{
11618 ImGuiContext& g = *GImGui;
11619 if (!IsPopupOpen(id, ImGuiPopupFlags_None))
11620 {
11621 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11622 return false;
11623 }
11624
11625 char name[20];
11626 if (flags & ImGuiWindowFlags_ChildMenu)
11627 ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginMenuDepth); // Recycle windows based on depth
11628 else
11629 ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
11630
11631 flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking;
11632 bool is_open = Begin(name, NULL, flags);
11633 if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
11634 EndPopup();
11635
11636 //g.CurrentWindow->FocusRouteParentWindow = g.CurrentWindow->ParentWindowInBeginStack;
11637
11638 return is_open;
11639}
11640
11641bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
11642{
11643 ImGuiContext& g = *GImGui;
11644 if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
11645 {
11646 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11647 return false;
11648 }
11649 flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
11650 ImGuiID id = g.CurrentWindow->GetID(str_id);
11651 return BeginPopupEx(id, flags);
11652}
11653
11654// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
11655// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup).
11656// - *p_open set back to false in BeginPopupModal() when popup is not open.
11657// - if you set *p_open to false before calling BeginPopupModal(), it will close the popup.
11658bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
11659{
11660 ImGuiContext& g = *GImGui;
11661 ImGuiWindow* window = g.CurrentWindow;
11662 const ImGuiID id = window->GetID(name);
11663 if (!IsPopupOpen(id, ImGuiPopupFlags_None))
11664 {
11665 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11666 if (p_open && *p_open)
11667 *p_open = false;
11668 return false;
11669 }
11670
11671 // Center modal windows by default for increased visibility
11672 // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
11673 // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
11674 if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
11675 {
11676 const ImGuiViewport* viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport?
11677 SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
11678 }
11679
11680 flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking;
11681 const bool is_open = Begin(name, p_open, flags);
11682 if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
11683 {
11684 EndPopup();
11685 if (is_open)
11686 ClosePopupToLevel(g.BeginPopupStack.Size, true);
11687 return false;
11688 }
11689 return is_open;
11690}
11691
11692void ImGui::EndPopup()
11693{
11694 ImGuiContext& g = *GImGui;
11695 ImGuiWindow* window = g.CurrentWindow;
11696 IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
11697 IM_ASSERT(g.BeginPopupStack.Size > 0);
11698
11699 // 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)
11700 if (g.NavWindow == window)
11701 NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
11702
11703 // Child-popups don't need to be laid out
11704 IM_ASSERT(g.WithinEndChild == false);
11705 if (window->Flags & ImGuiWindowFlags_ChildWindow)
11706 g.WithinEndChild = true;
11707 End();
11708 g.WithinEndChild = false;
11709}
11710
11711// Helper to open a popup if mouse button is released over the item
11712// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
11713void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
11714{
11715 ImGuiContext& g = *GImGui;
11716 ImGuiWindow* window = g.CurrentWindow;
11717 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11718 if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11719 {
11720 ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
11721 IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
11722 OpenPopupEx(id, popup_flags);
11723 }
11724}
11725
11726// This is a helper to handle the simplest case of associating one named popup to one given widget.
11727// - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
11728// - To create a popup with a specific identifier, pass it in str_id.
11729// - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
11730// - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
11731// - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
11732// This is essentially the same as:
11733// id = str_id ? GetID(str_id) : GetItemID();
11734// OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);
11735// return BeginPopup(id);
11736// Which is essentially the same as:
11737// id = str_id ? GetID(str_id) : GetItemID();
11738// if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
11739// OpenPopup(id);
11740// return BeginPopup(id);
11741// The main difference being that this is tweaked to avoid computing the ID twice.
11742bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
11743{
11744 ImGuiContext& g = *GImGui;
11745 ImGuiWindow* window = g.CurrentWindow;
11746 if (window->SkipItems)
11747 return false;
11748 ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
11749 IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
11750 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11751 if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11752 OpenPopupEx(id, popup_flags);
11753 return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11754}
11755
11756bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
11757{
11758 ImGuiContext& g = *GImGui;
11759 ImGuiWindow* window = g.CurrentWindow;
11760 if (!str_id)
11761 str_id = "window_context";
11762 ImGuiID id = window->GetID(str_id);
11763 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11764 if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11765 if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
11766 OpenPopupEx(id, popup_flags);
11767 return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11768}
11769
11770bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
11771{
11772 ImGuiContext& g = *GImGui;
11773 ImGuiWindow* window = g.CurrentWindow;
11774 if (!str_id)
11775 str_id = "void_context";
11776 ImGuiID id = window->GetID(str_id);
11777 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11778 if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
11779 if (GetTopMostPopupModal() == NULL)
11780 OpenPopupEx(id, popup_flags);
11781 return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11782}
11783
11784// 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.)
11785// 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.
11786// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
11787// information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
11788// this allows us to have tooltips/popups displayed out of the parent viewport.)
11789ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
11790{
11791 ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
11792 //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
11793 //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
11794
11795 // Combo Box policy (we want a connecting edge)
11796 if (policy == ImGuiPopupPositionPolicy_ComboBox)
11797 {
11798 const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
11799 for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
11800 {
11801 const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
11802 if (n != -1 && dir == *last_dir) // Already tried this direction?
11803 continue;
11804 ImVec2 pos;
11805 if (dir == ImGuiDir_Down) pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default)
11806 if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
11807 if (dir == ImGuiDir_Left) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
11808 if (dir == ImGuiDir_Up) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
11809 if (!r_outer.Contains(ImRect(pos, pos + size)))
11810 continue;
11811 *last_dir = dir;
11812 return pos;
11813 }
11814 }
11815
11816 // Tooltip and Default popup policy
11817 // (Always first try the direction we used on the last frame, if any)
11818 if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
11819 {
11820 const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
11821 for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
11822 {
11823 const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
11824 if (n != -1 && dir == *last_dir) // Already tried this direction?
11825 continue;
11826
11827 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);
11828 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);
11829
11830 // 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)
11831 if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
11832 continue;
11833 if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
11834 continue;
11835
11836 ImVec2 pos;
11837 pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
11838 pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
11839
11840 // Clamp top-left corner of popup
11841 pos.x = ImMax(pos.x, r_outer.Min.x);
11842 pos.y = ImMax(pos.y, r_outer.Min.y);
11843
11844 *last_dir = dir;
11845 return pos;
11846 }
11847 }
11848
11849 // Fallback when not enough room:
11850 *last_dir = ImGuiDir_None;
11851
11852 // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
11853 if (policy == ImGuiPopupPositionPolicy_Tooltip)
11854 return ref_pos + ImVec2(2, 2);
11855
11856 // Otherwise try to keep within display
11857 ImVec2 pos = ref_pos;
11858 pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
11859 pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
11860 return pos;
11861}
11862
11863// Note that this is used for popups, which can overlap the non work-area of individual viewports.
11864ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
11865{
11866 ImGuiContext& g = *GImGui;
11867 ImRect r_screen;
11868 if (window->ViewportAllowPlatformMonitorExtend >= 0)
11869 {
11870 // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
11871 const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend];
11872 r_screen.Min = monitor.WorkPos;
11873 r_screen.Max = monitor.WorkPos + monitor.WorkSize;
11874 }
11875 else
11876 {
11877 // Use the full viewport area (not work area) for popups
11878 r_screen = window->Viewport->GetMainRect();
11879 }
11880 ImVec2 padding = g.Style.DisplaySafeAreaPadding;
11881 r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
11882 return r_screen;
11883}
11884
11885ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
11886{
11887 ImGuiContext& g = *GImGui;
11888
11889 ImRect r_outer = GetPopupAllowedExtentRect(window);
11890 if (window->Flags & ImGuiWindowFlags_ChildMenu)
11891 {
11892 // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
11893 // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
11894 ImGuiWindow* parent_window = window->ParentWindow;
11895 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).
11896 ImRect r_avoid;
11897 if (parent_window->DC.MenuBarAppending)
11898 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
11899 else
11900 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);
11901 return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
11902 }
11903 if (window->Flags & ImGuiWindowFlags_Popup)
11904 {
11905 return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
11906 }
11907 if (window->Flags & ImGuiWindowFlags_Tooltip)
11908 {
11909 // Position tooltip (always follows mouse + clamp within outer boundaries)
11910 // Note that drag and drop tooltips are NOT using this path: BeginTooltipEx() manually sets their position.
11911 // In theory we could handle both cases in same location, but requires a bit of shuffling as drag and drop tooltips are calling SetWindowPos() leading to 'window_pos_set_by_api' being set in Begin()
11912 IM_ASSERT(g.CurrentWindow == window);
11913 const float scale = g.Style.MouseCursorScale;
11914 const ImVec2 ref_pos = NavCalcPreferredRefPos();
11915 const ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET * scale;
11916 ImRect r_avoid;
11917 if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
11918 r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
11919 else
11920 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.
11921 //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255, 0, 255, 255));
11922 return FindBestWindowPosForPopupEx(tooltip_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
11923 }
11924 IM_ASSERT(0);
11925 return window->Pos;
11926}
11927
11928//-----------------------------------------------------------------------------
11929// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
11930//-----------------------------------------------------------------------------
11931
11932// FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked.
11933// In our terminology those should be interchangeable, yet right now this is super confusing.
11934// Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
11935
11936void ImGui::SetNavWindow(ImGuiWindow* window)
11937{
11938 ImGuiContext& g = *GImGui;
11939 if (g.NavWindow != window)
11940 {
11941 IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : "<NULL>");
11942 g.NavWindow = window;
11943 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
11944 }
11945 g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11946 NavUpdateAnyRequestFlag();
11947}
11948
11949void ImGui::NavHighlightActivated(ImGuiID id)
11950{
11951 ImGuiContext& g = *GImGui;
11952 g.NavHighlightActivatedId = id;
11953 g.NavHighlightActivatedTimer = NAV_ACTIVATE_HIGHLIGHT_TIMER;
11954}
11955
11956void ImGui::NavClearPreferredPosForAxis(ImGuiAxis axis)
11957{
11958 ImGuiContext& g = *GImGui;
11959 g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer][axis] = FLT_MAX;
11960}
11961
11962void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
11963{
11964 ImGuiContext& g = *GImGui;
11965 IM_ASSERT(g.NavWindow != NULL);
11966 IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
11967 g.NavId = id;
11968 g.NavLayer = nav_layer;
11969 SetNavFocusScope(focus_scope_id);
11970 g.NavWindow->NavLastIds[nav_layer] = id;
11971 g.NavWindow->NavRectRel[nav_layer] = rect_rel;
11972
11973 // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
11974 NavClearPreferredPosForAxis(ImGuiAxis_X);
11975 NavClearPreferredPosForAxis(ImGuiAxis_Y);
11976}
11977
11978void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
11979{
11980 ImGuiContext& g = *GImGui;
11981 IM_ASSERT(id != 0);
11982
11983 if (g.NavWindow != window)
11984 SetNavWindow(window);
11985
11986 // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and g.CurrentFocusScopeId are valid.
11987 // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
11988 const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
11989 g.NavId = id;
11990 g.NavLayer = nav_layer;
11991 SetNavFocusScope(g.CurrentFocusScopeId);
11992 window->NavLastIds[nav_layer] = id;
11993 if (g.LastItemData.ID == id)
11994 window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect);
11995
11996 if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
11997 g.NavDisableMouseHover = true;
11998 else
11999 g.NavDisableHighlight = true;
12000
12001 // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
12002 NavClearPreferredPosForAxis(ImGuiAxis_X);
12003 NavClearPreferredPosForAxis(ImGuiAxis_Y);
12004}
12005
12006static ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
12007{
12008 if (ImFabs(dx) > ImFabs(dy))
12009 return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
12010 return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
12011}
12012
12013static float inline NavScoreItemDistInterval(float cand_min, float cand_max, float curr_min, float curr_max)
12014{
12015 if (cand_max < curr_min)
12016 return cand_max - curr_min;
12017 if (curr_max < cand_min)
12018 return cand_min - curr_max;
12019 return 0.0f;
12020}
12021
12022// Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
12023static bool ImGui::NavScoreItem(ImGuiNavItemData* result)
12024{
12025 ImGuiContext& g = *GImGui;
12026 ImGuiWindow* window = g.CurrentWindow;
12027 if (g.NavLayer != window->DC.NavLayerCurrent)
12028 return false;
12029
12030 // FIXME: Those are not good variables names
12031 ImRect cand = g.LastItemData.NavRect; // Current item nav rectangle
12032 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)
12033 g.NavScoringDebugCount++;
12034
12035 // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
12036 if (window->ParentWindow == g.NavWindow)
12037 {
12038 IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
12039 if (!window->ClipRect.Overlaps(cand))
12040 return false;
12041 cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
12042 }
12043
12044 // Compute distance between boxes
12045 // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
12046 float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
12047 float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
12048 if (dby != 0.0f && dbx != 0.0f)
12049 dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
12050 float dist_box = ImFabs(dbx) + ImFabs(dby);
12051
12052 // 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)
12053 float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
12054 float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
12055 float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
12056
12057 // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
12058 ImGuiDir quadrant;
12059 float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
12060 if (dbx != 0.0f || dby != 0.0f)
12061 {
12062 // For non-overlapping boxes, use distance between boxes
12063 dax = dbx;
12064 day = dby;
12065 dist_axial = dist_box;
12066 quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
12067 }
12068 else if (dcx != 0.0f || dcy != 0.0f)
12069 {
12070 // For overlapping boxes with different centers, use distance between centers
12071 dax = dcx;
12072 day = dcy;
12073 dist_axial = dist_center;
12074 quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
12075 }
12076 else
12077 {
12078 // 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)
12079 quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
12080 }
12081
12082 const ImGuiDir move_dir = g.NavMoveDir;
12083#if IMGUI_DEBUG_NAV_SCORING
12084 char buf[200];
12085 if (g.IO.KeyCtrl) // Hold CTRL to preview score in matching quadrant. CTRL+Arrow to rotate.
12086 {
12087 if (quadrant == move_dir)
12088 {
12089 ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
12090 ImDrawList* draw_list = GetForegroundDrawList(window);
12091 draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 80));
12092 draw_list->AddRectFilled(cand.Min, cand.Min + CalcTextSize(buf), IM_COL32(255, 0, 0, 200));
12093 draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
12094 }
12095 }
12096 const bool debug_hovering = IsMouseHoveringRect(cand.Min, cand.Max);
12097 const bool debug_tty = (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_Space));
12098 if (debug_hovering || debug_tty)
12099 {
12100 ImFormatString(buf, IM_ARRAYSIZE(buf),
12101 "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",
12102 dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "-WENS"[move_dir+1], "-WENS"[quadrant+1]);
12103 if (debug_hovering)
12104 {
12105 ImDrawList* draw_list = GetForegroundDrawList(window);
12106 draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255, 200, 0, 100));
12107 draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255, 255, 0, 200));
12108 draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40, 0, 0, 200));
12109 draw_list->AddText(cand.Max, ~0U, buf);
12110 }
12111 if (debug_tty) { IMGUI_DEBUG_LOG_NAV("id 0x%08X\n%s\n", g.LastItemData.ID, buf); }
12112 }
12113#endif
12114
12115 // Is it in the quadrant we're interested in moving to?
12116 bool new_best = false;
12117 if (quadrant == move_dir)
12118 {
12119 // Does it beat the current best candidate?
12120 if (dist_box < result->DistBox)
12121 {
12122 result->DistBox = dist_box;
12123 result->DistCenter = dist_center;
12124 return true;
12125 }
12126 if (dist_box == result->DistBox)
12127 {
12128 // Try using distance between center points to break ties
12129 if (dist_center < result->DistCenter)
12130 {
12131 result->DistCenter = dist_center;
12132 new_best = true;
12133 }
12134 else if (dist_center == result->DistCenter)
12135 {
12136 // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
12137 // (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),
12138 // 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.
12139 if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
12140 new_best = true;
12141 }
12142 }
12143 }
12144
12145 // 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
12146 // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
12147 // 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.
12148 // 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.
12149 // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
12150 if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial) // Check axial match
12151 if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
12152 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))
12153 {
12154 result->DistAxial = dist_axial;
12155 new_best = true;
12156 }
12157
12158 return new_best;
12159}
12160
12161static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
12162{
12163 ImGuiContext& g = *GImGui;
12164 ImGuiWindow* window = g.CurrentWindow;
12165 result->Window = window;
12166 result->ID = g.LastItemData.ID;
12167 result->FocusScopeId = g.CurrentFocusScopeId;
12168 result->InFlags = g.LastItemData.InFlags;
12169 result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect);
12170 if (result->InFlags & ImGuiItemFlags_HasSelectionUserData)
12171 {
12172 IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
12173 result->SelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
12174 }
12175}
12176
12177// True when current work location may be scrolled horizontally when moving left / right.
12178// This is generally always true UNLESS within a column. We don't have a vertical equivalent.
12179void ImGui::NavUpdateCurrentWindowIsScrollPushableX()
12180{
12181 ImGuiContext& g = *GImGui;
12182 ImGuiWindow* window = g.CurrentWindow;
12183 window->DC.NavIsScrollPushableX = (g.CurrentTable == NULL && window->DC.CurrentColumns == NULL);
12184}
12185
12186// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
12187// This is called after LastItemData is set, but NextItemData is also still valid.
12188static void ImGui::NavProcessItem()
12189{
12190 ImGuiContext& g = *GImGui;
12191 ImGuiWindow* window = g.CurrentWindow;
12192 const ImGuiID id = g.LastItemData.ID;
12193 const ImGuiItemFlags item_flags = g.LastItemData.InFlags;
12194
12195 // When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221)
12196 if (window->DC.NavIsScrollPushableX == false)
12197 {
12198 g.LastItemData.NavRect.Min.x = ImClamp(g.LastItemData.NavRect.Min.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
12199 g.LastItemData.NavRect.Max.x = ImClamp(g.LastItemData.NavRect.Max.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
12200 }
12201 const ImRect nav_bb = g.LastItemData.NavRect;
12202
12203 // Process Init Request
12204 if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
12205 {
12206 // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
12207 const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0;
12208 if (candidate_for_nav_default_focus || g.NavInitResult.ID == 0)
12209 {
12210 NavApplyItemToResult(&g.NavInitResult);
12211 }
12212 if (candidate_for_nav_default_focus)
12213 {
12214 g.NavInitRequest = false; // Found a match, clear request
12215 NavUpdateAnyRequestFlag();
12216 }
12217 }
12218
12219 // Process Move Request (scoring for navigation)
12220 // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
12221 if (g.NavMoveScoringItems && (item_flags & ImGuiItemFlags_Disabled) == 0)
12222 {
12223 if ((g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi) || (window->Flags & ImGuiWindowFlags_NoNavInputs) == 0)
12224 {
12225 const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
12226 if (is_tabbing)
12227 {
12228 NavProcessItemForTabbingRequest(id, item_flags, g.NavMoveFlags);
12229 }
12230 else if (g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId))
12231 {
12232 ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
12233 if (NavScoreItem(result))
12234 NavApplyItemToResult(result);
12235
12236 // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
12237 const float VISIBLE_RATIO = 0.70f;
12238 if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
12239 if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
12240 if (NavScoreItem(&g.NavMoveResultLocalVisible))
12241 NavApplyItemToResult(&g.NavMoveResultLocalVisible);
12242 }
12243 }
12244 }
12245
12246 // Update information for currently focused/navigated item
12247 if (g.NavId == id)
12248 {
12249 if (g.NavWindow != window)
12250 SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window.
12251 g.NavLayer = window->DC.NavLayerCurrent;
12252 SetNavFocusScope(g.CurrentFocusScopeId); // Will set g.NavFocusScopeId AND store g.NavFocusScopePath
12253 g.NavFocusScopeId = g.CurrentFocusScopeId;
12254 g.NavIdIsAlive = true;
12255 if (g.LastItemData.InFlags & ImGuiItemFlags_HasSelectionUserData)
12256 {
12257 IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
12258 g.NavLastValidSelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
12259 }
12260 window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, nav_bb); // Store item bounding box (relative to window position)
12261 }
12262}
12263
12264// Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
12265// Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
12266// - Case 1: no nav/active id: set result to first eligible item, stop storing.
12267// - Case 2: tab forward: on ref id set counter, on counter elapse store result
12268// - 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
12269// - Case 4: tab backward: store all results, on ref id pick prev, stop storing
12270// - 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
12271void ImGui::NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags)
12272{
12273 ImGuiContext& g = *GImGui;
12274
12275 if ((move_flags & ImGuiNavMoveFlags_FocusApi) == 0)
12276 {
12277 if (g.NavLayer != g.CurrentWindow->DC.NavLayerCurrent)
12278 return;
12279 if (g.NavFocusScopeId != g.CurrentFocusScopeId)
12280 return;
12281 }
12282
12283 // - Can always land on an item when using API call.
12284 // - Tabbing with _NavEnableKeyboard (space/enter/arrows): goes through every item.
12285 // - Tabbing without _NavEnableKeyboard: goes through inputable items only.
12286 bool can_stop;
12287 if (move_flags & ImGuiNavMoveFlags_FocusApi)
12288 can_stop = true;
12289 else
12290 can_stop = (item_flags & ImGuiItemFlags_NoTabStop) == 0 && ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) || (item_flags & ImGuiItemFlags_Inputable));
12291
12292 // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
12293 ImGuiNavItemData* result = &g.NavMoveResultLocal;
12294 if (g.NavTabbingDir == +1)
12295 {
12296 // Tab Forward or SetKeyboardFocusHere() with >= 0
12297 if (can_stop && g.NavTabbingResultFirst.ID == 0)
12298 NavApplyItemToResult(&g.NavTabbingResultFirst);
12299 if (can_stop && g.NavTabbingCounter > 0 && --g.NavTabbingCounter == 0)
12300 NavMoveRequestResolveWithLastItem(result);
12301 else if (g.NavId == id)
12302 g.NavTabbingCounter = 1;
12303 }
12304 else if (g.NavTabbingDir == -1)
12305 {
12306 // Tab Backward
12307 if (g.NavId == id)
12308 {
12309 if (result->ID)
12310 {
12311 g.NavMoveScoringItems = false;
12312 NavUpdateAnyRequestFlag();
12313 }
12314 }
12315 else if (can_stop)
12316 {
12317 // Keep applying until reaching NavId
12318 NavApplyItemToResult(result);
12319 }
12320 }
12321 else if (g.NavTabbingDir == 0)
12322 {
12323 if (can_stop && g.NavId == id)
12324 NavMoveRequestResolveWithLastItem(result);
12325 if (can_stop && g.NavTabbingResultFirst.ID == 0) // Tab init
12326 NavApplyItemToResult(&g.NavTabbingResultFirst);
12327 }
12328}
12329
12330bool ImGui::NavMoveRequestButNoResultYet()
12331{
12332 ImGuiContext& g = *GImGui;
12333 return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
12334}
12335
12336// FIXME: ScoringRect is not set
12337void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
12338{
12339 ImGuiContext& g = *GImGui;
12340 IM_ASSERT(g.NavWindow != NULL);
12341
12342 if (move_flags & ImGuiNavMoveFlags_IsTabbing)
12343 move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
12344
12345 g.NavMoveSubmitted = g.NavMoveScoringItems = true;
12346 g.NavMoveDir = move_dir;
12347 g.NavMoveDirForDebug = move_dir;
12348 g.NavMoveClipDir = clip_dir;
12349 g.NavMoveFlags = move_flags;
12350 g.NavMoveScrollFlags = scroll_flags;
12351 g.NavMoveForwardToNextFrame = false;
12352 g.NavMoveKeyMods = (move_flags & ImGuiNavMoveFlags_FocusApi) ? 0 : g.IO.KeyMods;
12353 g.NavMoveResultLocal.Clear();
12354 g.NavMoveResultLocalVisible.Clear();
12355 g.NavMoveResultOther.Clear();
12356 g.NavTabbingCounter = 0;
12357 g.NavTabbingResultFirst.Clear();
12358 NavUpdateAnyRequestFlag();
12359}
12360
12361void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
12362{
12363 ImGuiContext& g = *GImGui;
12364 g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
12365 NavApplyItemToResult(result);
12366 NavUpdateAnyRequestFlag();
12367}
12368
12369// Called by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsBackHere
12370void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, ImGuiNavTreeNodeData* tree_node_data)
12371{
12372 ImGuiContext& g = *GImGui;
12373 g.NavMoveScoringItems = false;
12374 g.LastItemData.ID = tree_node_data->ID;
12375 g.LastItemData.InFlags = tree_node_data->InFlags & ~ImGuiItemFlags_HasSelectionUserData; // Losing SelectionUserData, recovered next-frame (cheaper).
12376 g.LastItemData.NavRect = tree_node_data->NavRect;
12377 NavApplyItemToResult(result); // Result this instead of implementing a NavApplyPastTreeNodeToResult()
12378 NavClearPreferredPosForAxis(ImGuiAxis_Y);
12379 NavUpdateAnyRequestFlag();
12380}
12381
12382void ImGui::NavMoveRequestCancel()
12383{
12384 ImGuiContext& g = *GImGui;
12385 g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12386 NavUpdateAnyRequestFlag();
12387}
12388
12389// Forward will reuse the move request again on the next frame (generally with modifications done to it)
12390void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
12391{
12392 ImGuiContext& g = *GImGui;
12393 IM_ASSERT(g.NavMoveForwardToNextFrame == false);
12394 NavMoveRequestCancel();
12395 g.NavMoveForwardToNextFrame = true;
12396 g.NavMoveDir = move_dir;
12397 g.NavMoveClipDir = clip_dir;
12398 g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
12399 g.NavMoveScrollFlags = scroll_flags;
12400}
12401
12402// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
12403// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
12404void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
12405{
12406 ImGuiContext& g = *GImGui;
12407 IM_ASSERT((wrap_flags & ImGuiNavMoveFlags_WrapMask_ ) != 0 && (wrap_flags & ~ImGuiNavMoveFlags_WrapMask_) == 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
12408
12409 // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it:
12410 // as NavEndFrame() will do the same test. It will end up calling NavUpdateCreateWrappingRequest().
12411 if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
12412 g.NavMoveFlags = (g.NavMoveFlags & ~ImGuiNavMoveFlags_WrapMask_) | wrap_flags;
12413}
12414
12415// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
12416// This way we could find the last focused window among our children. It would be much less confusing this way?
12417static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
12418{
12419 ImGuiWindow* parent = nav_window;
12420 while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
12421 parent = parent->ParentWindow;
12422 if (parent && parent != nav_window)
12423 parent->NavLastChildNavWindow = nav_window;
12424}
12425
12426// Restore the last focused child.
12427// Call when we are expected to land on the Main Layer (0) after FocusWindow()
12428static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
12429{
12430 if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
12431 return window->NavLastChildNavWindow;
12432 if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar)
12433 if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar))
12434 return tab->Window;
12435 return window;
12436}
12437
12438void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
12439{
12440 ImGuiContext& g = *GImGui;
12441 if (layer == ImGuiNavLayer_Main)
12442 {
12443 ImGuiWindow* prev_nav_window = g.NavWindow;
12444 g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow); // FIXME-NAV: Should clear ongoing nav requests?
12445 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
12446 if (prev_nav_window)
12447 IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name);
12448 }
12449 ImGuiWindow* window = g.NavWindow;
12450 if (window->NavLastIds[layer] != 0)
12451 {
12452 SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
12453 }
12454 else
12455 {
12456 g.NavLayer = layer;
12457 NavInitWindow(window, true);
12458 }
12459}
12460
12461void ImGui::NavRestoreHighlightAfterMove()
12462{
12463 ImGuiContext& g = *GImGui;
12464 g.NavDisableHighlight = false;
12465 g.NavDisableMouseHover = g.NavMousePosDirty = true;
12466}
12467
12468static inline void ImGui::NavUpdateAnyRequestFlag()
12469{
12470 ImGuiContext& g = *GImGui;
12471 g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
12472 if (g.NavAnyRequest)
12473 IM_ASSERT(g.NavWindow != NULL);
12474}
12475
12476// This needs to be called before we submit any widget (aka in or before Begin)
12477void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
12478{
12479 // FIXME: ChildWindow test here is wrong for docking
12480 ImGuiContext& g = *GImGui;
12481 IM_ASSERT(window == g.NavWindow);
12482
12483 if (window->Flags & ImGuiWindowFlags_NoNavInputs)
12484 {
12485 g.NavId = 0;
12486 SetNavFocusScope(window->NavRootFocusScopeId);
12487 return;
12488 }
12489
12490 bool init_for_nav = false;
12491 if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
12492 init_for_nav = true;
12493 IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
12494 if (init_for_nav)
12495 {
12496 SetNavID(0, g.NavLayer, window->NavRootFocusScopeId, ImRect());
12497 g.NavInitRequest = true;
12498 g.NavInitRequestFromMove = false;
12499 g.NavInitResult.ID = 0;
12500 NavUpdateAnyRequestFlag();
12501 }
12502 else
12503 {
12504 g.NavId = window->NavLastIds[0];
12505 SetNavFocusScope(window->NavRootFocusScopeId);
12506 }
12507}
12508
12509static ImVec2 ImGui::NavCalcPreferredRefPos()
12510{
12511 ImGuiContext& g = *GImGui;
12512 ImGuiWindow* window = g.NavWindow;
12513 if (g.NavDisableHighlight || !g.NavDisableMouseHover || !window)
12514 {
12515 // Mouse (we need a fallback in case the mouse becomes invalid after being used)
12516 // 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.
12517 // In theory we could move that +1.0f offset in OpenPopupEx()
12518 ImVec2 p = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;
12519 return ImVec2(p.x + 1.0f, p.y);
12520 }
12521 else
12522 {
12523 // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
12524 // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
12525 ImRect rect_rel = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]);
12526 if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
12527 {
12528 ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
12529 rect_rel.Translate(window->Scroll - next_scroll);
12530 }
12531 ImVec2 pos = ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight()));
12532 ImGuiViewport* viewport = window->Viewport;
12533 return ImTrunc(ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size)); // ImTrunc() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
12534 }
12535}
12536
12537float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis)
12538{
12539 ImGuiContext& g = *GImGui;
12540 float repeat_delay, repeat_rate;
12541 GetTypematicRepeatRate(ImGuiInputFlags_RepeatRateNavTweak, &repeat_delay, &repeat_rate);
12542
12543 ImGuiKey key_less, key_more;
12544 if (g.NavInputSource == ImGuiInputSource_Gamepad)
12545 {
12546 key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp;
12547 key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown;
12548 }
12549 else
12550 {
12551 key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow;
12552 key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow;
12553 }
12554 float amount = (float)GetKeyPressedAmount(key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key_less, repeat_delay, repeat_rate);
12555 if (amount != 0.0f && IsKeyDown(key_less) && IsKeyDown(key_more)) // Cancel when opposite directions are held, regardless of repeat phase
12556 amount = 0.0f;
12557 return amount;
12558}
12559
12560static void ImGui::NavUpdate()
12561{
12562 ImGuiContext& g = *GImGui;
12563 ImGuiIO& io = g.IO;
12564
12565 io.WantSetMousePos = false;
12566 //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);
12567
12568 // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard)
12569 // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource?
12570 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12571 const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown };
12572 if (nav_gamepad_active)
12573 for (ImGuiKey key : nav_gamepad_keys_to_change_source)
12574 if (IsKeyDown(key))
12575 g.NavInputSource = ImGuiInputSource_Gamepad;
12576 const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12577 const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow };
12578 if (nav_keyboard_active)
12579 for (ImGuiKey key : nav_keyboard_keys_to_change_source)
12580 if (IsKeyDown(key))
12581 g.NavInputSource = ImGuiInputSource_Keyboard;
12582
12583 // Process navigation init request (select first/default focus)
12584 g.NavJustMovedToId = 0;
12585 if (g.NavInitResult.ID != 0)
12586 NavInitRequestApplyResult();
12587 g.NavInitRequest = false;
12588 g.NavInitRequestFromMove = false;
12589 g.NavInitResult.ID = 0;
12590
12591 // Process navigation move request
12592 if (g.NavMoveSubmitted)
12593 NavMoveRequestApplyResult();
12594 g.NavTabbingCounter = 0;
12595 g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12596
12597 // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
12598 bool set_mouse_pos = false;
12599 if (g.NavMousePosDirty && g.NavIdIsAlive)
12600 if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
12601 set_mouse_pos = true;
12602 g.NavMousePosDirty = false;
12603 IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
12604
12605 // 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
12606 if (g.NavWindow)
12607 NavSaveLastChildNavWindowIntoParent(g.NavWindow);
12608 if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
12609 g.NavWindow->NavLastChildNavWindow = NULL;
12610
12611 // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
12612 NavUpdateWindowing();
12613
12614 // Set output flags for user application
12615 io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
12616 io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
12617
12618 // Process NavCancel input (to close a popup, get back to parent, clear focus)
12619 NavUpdateCancelRequest();
12620
12621 // Process manual activation request
12622 g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = 0;
12623 g.NavActivateFlags = ImGuiActivateFlags_None;
12624 if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
12625 {
12626 const bool activate_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Space, ImGuiKeyOwner_None)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate, ImGuiKeyOwner_None));
12627 const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Space, ImGuiKeyOwner_None)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, ImGuiKeyOwner_None)));
12628 const bool input_down = (nav_keyboard_active && (IsKeyDown(ImGuiKey_Enter, ImGuiKeyOwner_None) || IsKeyDown(ImGuiKey_KeypadEnter, ImGuiKeyOwner_None))) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadInput, ImGuiKeyOwner_None));
12629 const bool input_pressed = input_down && ((nav_keyboard_active && (IsKeyPressed(ImGuiKey_Enter, ImGuiKeyOwner_None) || IsKeyPressed(ImGuiKey_KeypadEnter, ImGuiKeyOwner_None))) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadInput, ImGuiKeyOwner_None)));
12630 if (g.ActiveId == 0 && activate_pressed)
12631 {
12632 g.NavActivateId = g.NavId;
12633 g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
12634 }
12635 if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
12636 {
12637 g.NavActivateId = g.NavId;
12638 g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
12639 }
12640 if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_down || input_down))
12641 g.NavActivateDownId = g.NavId;
12642 if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_pressed || input_pressed))
12643 {
12644 g.NavActivatePressedId = g.NavId;
12645 NavHighlightActivated(g.NavId);
12646 }
12647 }
12648 if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
12649 g.NavDisableHighlight = true;
12650 if (g.NavActivateId != 0)
12651 IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
12652
12653 // Highlight
12654 if (g.NavHighlightActivatedTimer > 0.0f)
12655 g.NavHighlightActivatedTimer = ImMax(0.0f, g.NavHighlightActivatedTimer - io.DeltaTime);
12656 if (g.NavHighlightActivatedTimer == 0.0f)
12657 g.NavHighlightActivatedId = 0;
12658
12659 // Process programmatic activation request
12660 // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
12661 if (g.NavNextActivateId != 0)
12662 {
12663 g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
12664 g.NavActivateFlags = g.NavNextActivateFlags;
12665 }
12666 g.NavNextActivateId = 0;
12667
12668 // Process move requests
12669 NavUpdateCreateMoveRequest();
12670 if (g.NavMoveDir == ImGuiDir_None)
12671 NavUpdateCreateTabbingRequest();
12672 NavUpdateAnyRequestFlag();
12673 g.NavIdIsAlive = false;
12674
12675 // Scrolling
12676 if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
12677 {
12678 // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
12679 ImGuiWindow* window = g.NavWindow;
12680 const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
12681 const ImGuiDir move_dir = g.NavMoveDir;
12682 if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY && move_dir != ImGuiDir_None)
12683 {
12684 if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
12685 SetScrollX(window, ImTrunc(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
12686 if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
12687 SetScrollY(window, ImTrunc(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
12688 }
12689
12690 // *Normal* Manual scroll with LStick
12691 // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
12692 if (nav_gamepad_active)
12693 {
12694 const ImVec2 scroll_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
12695 const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f;
12696 if (scroll_dir.x != 0.0f && window->ScrollbarX)
12697 SetScrollX(window, ImTrunc(window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor));
12698 if (scroll_dir.y != 0.0f)
12699 SetScrollY(window, ImTrunc(window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor));
12700 }
12701 }
12702
12703 // Always prioritize mouse highlight if navigation is disabled
12704 if (!nav_keyboard_active && !nav_gamepad_active)
12705 {
12706 g.NavDisableHighlight = true;
12707 g.NavDisableMouseHover = set_mouse_pos = false;
12708 }
12709
12710 // Update mouse position if requested
12711 // (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)
12712 if (set_mouse_pos && (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
12713 TeleportMousePos(NavCalcPreferredRefPos());
12714
12715 // [DEBUG]
12716 g.NavScoringDebugCount = 0;
12717#if IMGUI_DEBUG_NAV_RECTS
12718 if (ImGuiWindow* debug_window = g.NavWindow)
12719 {
12720 ImDrawList* draw_list = GetForegroundDrawList(debug_window);
12721 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)); }
12722 //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); }
12723 }
12724#endif
12725}
12726
12727void ImGui::NavInitRequestApplyResult()
12728{
12729 // 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)
12730 ImGuiContext& g = *GImGui;
12731 if (!g.NavWindow)
12732 return;
12733
12734 ImGuiNavItemData* result = &g.NavInitResult;
12735 if (g.NavId != result->ID)
12736 {
12737 g.NavJustMovedToId = result->ID;
12738 g.NavJustMovedToFocusScopeId = result->FocusScopeId;
12739 g.NavJustMovedToKeyMods = 0;
12740 }
12741
12742 // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
12743 // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
12744 IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
12745 SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
12746 g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
12747 if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
12748 g.NavLastValidSelectionUserData = result->SelectionUserData;
12749 if (g.NavInitRequestFromMove)
12750 NavRestoreHighlightAfterMove();
12751}
12752
12753// Bias scoring rect ahead of scoring + update preferred pos (if missing) using source position
12754static void NavBiasScoringRect(ImRect& r, ImVec2& preferred_pos_rel, ImGuiDir move_dir, ImGuiNavMoveFlags move_flags)
12755{
12756 // Bias initial rect
12757 ImGuiContext& g = *GImGui;
12758 const ImVec2 rel_to_abs_offset = g.NavWindow->DC.CursorStartPos;
12759
12760 // Initialize bias on departure if we don't have any. So mouse-click + arrow will record bias.
12761 // - We default to L/U bias, so moving down from a large source item into several columns will land on left-most column.
12762 // - But each successful move sets new bias on one axis, only cleared when using mouse.
12763 if ((move_flags & ImGuiNavMoveFlags_Forwarded) == 0)
12764 {
12765 if (preferred_pos_rel.x == FLT_MAX)
12766 preferred_pos_rel.x = ImMin(r.Min.x + 1.0f, r.Max.x) - rel_to_abs_offset.x;
12767 if (preferred_pos_rel.y == FLT_MAX)
12768 preferred_pos_rel.y = r.GetCenter().y - rel_to_abs_offset.y;
12769 }
12770
12771 // Apply general bias on the other axis
12772 if ((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) && preferred_pos_rel.x != FLT_MAX)
12773 r.Min.x = r.Max.x = preferred_pos_rel.x + rel_to_abs_offset.x;
12774 else if ((move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right) && preferred_pos_rel.y != FLT_MAX)
12775 r.Min.y = r.Max.y = preferred_pos_rel.y + rel_to_abs_offset.y;
12776}
12777
12778void ImGui::NavUpdateCreateMoveRequest()
12779{
12780 ImGuiContext& g = *GImGui;
12781 ImGuiIO& io = g.IO;
12782 ImGuiWindow* window = g.NavWindow;
12783 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12784 const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12785
12786 if (g.NavMoveForwardToNextFrame && window != NULL)
12787 {
12788 // 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)
12789 // (preserve most state, which were already set by the NavMoveRequestForward() function)
12790 IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
12791 IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
12792 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
12793 }
12794 else
12795 {
12796 // Initiate directional inputs request
12797 g.NavMoveDir = ImGuiDir_None;
12798 g.NavMoveFlags = ImGuiNavMoveFlags_None;
12799 g.NavMoveScrollFlags = ImGuiScrollFlags_None;
12800 if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
12801 {
12802 const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | ImGuiInputFlags_RepeatRateNavMove;
12803 if (!IsActiveIdUsingNavDir(ImGuiDir_Left) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadLeft, ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_LeftArrow, ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Left; }
12804 if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadRight, ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_RightArrow, ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Right; }
12805 if (!IsActiveIdUsingNavDir(ImGuiDir_Up) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadUp, ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_UpArrow, ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Up; }
12806 if (!IsActiveIdUsingNavDir(ImGuiDir_Down) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadDown, ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_DownArrow, ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Down; }
12807 }
12808 g.NavMoveClipDir = g.NavMoveDir;
12809 g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
12810 }
12811
12812 // Update PageUp/PageDown/Home/End scroll
12813 // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
12814 float scoring_rect_offset_y = 0.0f;
12815 if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
12816 scoring_rect_offset_y = NavUpdatePageUpPageDown();
12817 if (scoring_rect_offset_y != 0.0f)
12818 {
12819 g.NavScoringNoClipRect = window->InnerRect;
12820 g.NavScoringNoClipRect.TranslateY(scoring_rect_offset_y);
12821 }
12822
12823 // [DEBUG] Always send a request when holding CTRL. Hold CTRL + Arrow change the direction.
12824#if IMGUI_DEBUG_NAV_SCORING
12825 //if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
12826 // g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
12827 if (io.KeyCtrl)
12828 {
12829 if (g.NavMoveDir == ImGuiDir_None)
12830 g.NavMoveDir = g.NavMoveDirForDebug;
12831 g.NavMoveClipDir = g.NavMoveDir;
12832 g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
12833 }
12834#endif
12835
12836 // Submit
12837 g.NavMoveForwardToNextFrame = false;
12838 if (g.NavMoveDir != ImGuiDir_None)
12839 NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags);
12840
12841 // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match)
12842 if (g.NavMoveSubmitted && g.NavId == 0)
12843 {
12844 IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "<NULL>", g.NavLayer);
12845 g.NavInitRequest = g.NavInitRequestFromMove = true;
12846 g.NavInitResult.ID = 0;
12847 g.NavDisableHighlight = false;
12848 }
12849
12850 // When using gamepad, we project the reference nav bounding box into window visible area.
12851 // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling,
12852 // since with gamepad all movements are relative (can't focus a visible object like we can with the mouse).
12853 if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))
12854 {
12855 bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;
12856 bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;
12857 ImRect inner_rect_rel = WindowRectAbsToRel(window, ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
12858
12859 // Take account of changing scroll to handle triggering a new move request on a scrolling frame. (#6171)
12860 // Otherwise 'inner_rect_rel' would be off on the move result frame.
12861 inner_rect_rel.Translate(CalcNextScrollFromScrollTargetAndClamp(window) - window->Scroll);
12862
12863 if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
12864 {
12865 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
12866 float pad_x = ImMin(inner_rect_rel.GetWidth(), window->CalcFontSize() * 0.5f);
12867 float pad_y = ImMin(inner_rect_rel.GetHeight(), window->CalcFontSize() * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item
12868 inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
12869 inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
12870 inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
12871 inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;
12872 window->NavRectRel[g.NavLayer].ClipWithFull(inner_rect_rel);
12873 g.NavId = 0;
12874 }
12875 }
12876
12877 // 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)
12878 ImRect scoring_rect;
12879 if (window != NULL)
12880 {
12881 ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
12882 scoring_rect = WindowRectRelToAbs(window, nav_rect_rel);
12883 scoring_rect.TranslateY(scoring_rect_offset_y);
12884 if (g.NavMoveSubmitted)
12885 NavBiasScoringRect(scoring_rect, window->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer], g.NavMoveDir, g.NavMoveFlags);
12886 IM_ASSERT(!scoring_rect.IsInverted()); // Ensure we have a non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem().
12887 //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
12888 //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
12889 }
12890 g.NavScoringRect = scoring_rect;
12891 g.NavScoringNoClipRect.Add(scoring_rect);
12892}
12893
12894void ImGui::NavUpdateCreateTabbingRequest()
12895{
12896 ImGuiContext& g = *GImGui;
12897 ImGuiWindow* window = g.NavWindow;
12898 IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
12899 if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))
12900 return;
12901
12902 const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
12903 if (!tab_pressed)
12904 return;
12905
12906 // Initiate tabbing request
12907 // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
12908 // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
12909 const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12910 if (nav_keyboard_active)
12911 g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.NavDisableHighlight == true && g.ActiveId == 0) ? 0 : +1;
12912 else
12913 g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
12914 ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate;
12915 ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
12916 ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
12917 NavMoveRequestSubmit(ImGuiDir_None, clip_dir, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
12918 g.NavTabbingCounter = -1;
12919}
12920
12921// Apply result from previous frame navigation directional move request. Always called from NavUpdate()
12922void ImGui::NavMoveRequestApplyResult()
12923{
12924 ImGuiContext& g = *GImGui;
12925#if IMGUI_DEBUG_NAV_SCORING
12926 if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
12927 return;
12928#endif
12929
12930 // Select which result to use
12931 ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
12932
12933 // Tabbing forward wrap
12934 if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && result == NULL)
12935 if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
12936 result = &g.NavTabbingResultFirst;
12937
12938 // 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)
12939 const ImGuiAxis axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
12940 if (result == NULL)
12941 {
12942 if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
12943 g.NavMoveFlags |= ImGuiNavMoveFlags_NoSetNavHighlight;
12944 if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
12945 NavRestoreHighlightAfterMove();
12946 NavClearPreferredPosForAxis(axis); // On a failed move, clear preferred pos for this axis.
12947 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n");
12948 return;
12949 }
12950
12951 // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
12952 if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
12953 if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
12954 result = &g.NavMoveResultLocalVisible;
12955
12956 // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
12957 if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
12958 if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
12959 result = &g.NavMoveResultOther;
12960 IM_ASSERT(g.NavWindow && result->Window);
12961
12962 // Scroll to keep newly navigated item fully into view.
12963 if (g.NavLayer == ImGuiNavLayer_Main)
12964 {
12965 ImRect rect_abs = WindowRectRelToAbs(result->Window, result->RectRel);
12966 ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags);
12967
12968 if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
12969 {
12970 // FIXME: Should remove this? Or make more precise: use ScrollToRectEx() with edge?
12971 float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
12972 SetScrollY(result->Window, scroll_target);
12973 }
12974 }
12975
12976 if (g.NavWindow != result->Window)
12977 {
12978 IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name);
12979 g.NavWindow = result->Window;
12980 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
12981 }
12982
12983 // FIXME: Could become optional e.g. ImGuiNavMoveFlags_NoClearActiveId if we later want to apply navigation requests without altering active input.
12984 if (g.ActiveId != result->ID)
12985 ClearActiveID();
12986
12987 // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
12988 // PageUp/PageDown however sets always set NavJustMovedTo (vs Home/End which doesn't) mimicking Windows behavior.
12989 if ((g.NavId != result->ID || (g.NavMoveFlags & ImGuiNavMoveFlags_IsPageMove)) && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSelect) == 0)
12990 {
12991 g.NavJustMovedToId = result->ID;
12992 g.NavJustMovedToFocusScopeId = result->FocusScopeId;
12993 g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
12994 }
12995
12996 // Apply new NavID/Focus
12997 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
12998 ImVec2 preferred_scoring_pos_rel = g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer];
12999 SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
13000 if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
13001 g.NavLastValidSelectionUserData = result->SelectionUserData;
13002
13003 // Restore last preferred position for current axis
13004 // (storing in RootWindowForNav-> as the info is desirable at the beginning of a Move Request. In theory all storage should use RootWindowForNav..)
13005 if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) == 0)
13006 {
13007 preferred_scoring_pos_rel[axis] = result->RectRel.GetCenter()[axis];
13008 g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer] = preferred_scoring_pos_rel;
13009 }
13010
13011 // Tabbing: Activates Inputable, otherwise only Focus
13012 if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && (result->InFlags & ImGuiItemFlags_Inputable) == 0)
13013 g.NavMoveFlags &= ~ImGuiNavMoveFlags_Activate;
13014
13015 // Activate
13016 if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
13017 {
13018 g.NavNextActivateId = result->ID;
13019 g.NavNextActivateFlags = ImGuiActivateFlags_None;
13020 if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
13021 g.NavNextActivateFlags |= ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState | ImGuiActivateFlags_FromTabbing;
13022 }
13023
13024 // Enable nav highlight
13025 if ((g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
13026 NavRestoreHighlightAfterMove();
13027}
13028
13029// Process NavCancel input (to close a popup, get back to parent, clear focus)
13030// FIXME: In order to support e.g. Escape to clear a selection we'll need:
13031// - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
13032// - 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
13033static void ImGui::NavUpdateCancelRequest()
13034{
13035 ImGuiContext& g = *GImGui;
13036 const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
13037 const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13038 if (!(nav_keyboard_active && IsKeyPressed(ImGuiKey_Escape, ImGuiKeyOwner_None)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, ImGuiKeyOwner_None)))
13039 return;
13040
13041 IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n");
13042 if (g.ActiveId != 0)
13043 {
13044 ClearActiveID();
13045 }
13046 else if (g.NavLayer != ImGuiNavLayer_Main)
13047 {
13048 // Leave the "menu" layer
13049 NavRestoreLayer(ImGuiNavLayer_Main);
13050 NavRestoreHighlightAfterMove();
13051 }
13052 else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->RootWindowForNav->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->RootWindowForNav->ParentWindow)
13053 {
13054 // Exit child window
13055 ImGuiWindow* child_window = g.NavWindow->RootWindowForNav;
13056 ImGuiWindow* parent_window = child_window->ParentWindow;
13057 IM_ASSERT(child_window->ChildId != 0);
13058 FocusWindow(parent_window);
13059 SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_window->Rect()));
13060 NavRestoreHighlightAfterMove();
13061 }
13062 else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
13063 {
13064 // Close open popup/menu
13065 ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
13066 }
13067 else
13068 {
13069 // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
13070 if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
13071 g.NavWindow->NavLastIds[0] = 0;
13072 g.NavId = 0;
13073 }
13074}
13075
13076// Handle PageUp/PageDown/Home/End keys
13077// Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
13078// FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
13079// FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
13080static float ImGui::NavUpdatePageUpPageDown()
13081{
13082 ImGuiContext& g = *GImGui;
13083 ImGuiWindow* window = g.NavWindow;
13084 if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
13085 return 0.0f;
13086
13087 const bool page_up_held = IsKeyDown(ImGuiKey_PageUp, ImGuiKeyOwner_None);
13088 const bool page_down_held = IsKeyDown(ImGuiKey_PageDown, ImGuiKeyOwner_None);
13089 const bool home_pressed = IsKeyPressed(ImGuiKey_Home, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
13090 const bool end_pressed = IsKeyPressed(ImGuiKey_End, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
13091 if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
13092 return 0.0f;
13093
13094 if (g.NavLayer != ImGuiNavLayer_Main)
13095 NavRestoreLayer(ImGuiNavLayer_Main);
13096
13097 if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY)
13098 {
13099 // Fallback manual-scroll when window has no navigable item
13100 if (IsKeyPressed(ImGuiKey_PageUp, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
13101 SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
13102 else if (IsKeyPressed(ImGuiKey_PageDown, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
13103 SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
13104 else if (home_pressed)
13105 SetScrollY(window, 0.0f);
13106 else if (end_pressed)
13107 SetScrollY(window, window->ScrollMax.y);
13108 }
13109 else
13110 {
13111 ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
13112 const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
13113 float nav_scoring_rect_offset_y = 0.0f;
13114 if (IsKeyPressed(ImGuiKey_PageUp, true))
13115 {
13116 nav_scoring_rect_offset_y = -page_offset_y;
13117 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)
13118 g.NavMoveClipDir = ImGuiDir_Up;
13119 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
13120 }
13121 else if (IsKeyPressed(ImGuiKey_PageDown, true))
13122 {
13123 nav_scoring_rect_offset_y = +page_offset_y;
13124 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)
13125 g.NavMoveClipDir = ImGuiDir_Down;
13126 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
13127 }
13128 else if (home_pressed)
13129 {
13130 // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
13131 // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
13132 // Preserve current horizontal position if we have any.
13133 nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
13134 if (nav_rect_rel.IsInverted())
13135 nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
13136 g.NavMoveDir = ImGuiDir_Down;
13137 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
13138 // FIXME-NAV: MoveClipDir left to _None, intentional?
13139 }
13140 else if (end_pressed)
13141 {
13142 nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
13143 if (nav_rect_rel.IsInverted())
13144 nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
13145 g.NavMoveDir = ImGuiDir_Up;
13146 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
13147 // FIXME-NAV: MoveClipDir left to _None, intentional?
13148 }
13149 return nav_scoring_rect_offset_y;
13150 }
13151 return 0.0f;
13152}
13153
13154static void ImGui::NavEndFrame()
13155{
13156 ImGuiContext& g = *GImGui;
13157
13158 // Show CTRL+TAB list window
13159 if (g.NavWindowingTarget != NULL)
13160 NavUpdateWindowingOverlay();
13161
13162 // Perform wrap-around in menus
13163 // 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.
13164 // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
13165 if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & ImGuiNavMoveFlags_WrapMask_) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
13166 NavUpdateCreateWrappingRequest();
13167}
13168
13169static void ImGui::NavUpdateCreateWrappingRequest()
13170{
13171 ImGuiContext& g = *GImGui;
13172 ImGuiWindow* window = g.NavWindow;
13173
13174 bool do_forward = false;
13175 ImRect bb_rel = window->NavRectRel[g.NavLayer];
13176 ImGuiDir clip_dir = g.NavMoveDir;
13177
13178 const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
13179 //const ImGuiAxis move_axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
13180 if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
13181 {
13182 bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;
13183 if (move_flags & ImGuiNavMoveFlags_WrapX)
13184 {
13185 bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row
13186 clip_dir = ImGuiDir_Up;
13187 }
13188 do_forward = true;
13189 }
13190 if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
13191 {
13192 bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
13193 if (move_flags & ImGuiNavMoveFlags_WrapX)
13194 {
13195 bb_rel.TranslateY(+bb_rel.GetHeight()); // Next row
13196 clip_dir = ImGuiDir_Down;
13197 }
13198 do_forward = true;
13199 }
13200 if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
13201 {
13202 bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;
13203 if (move_flags & ImGuiNavMoveFlags_WrapY)
13204 {
13205 bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column
13206 clip_dir = ImGuiDir_Left;
13207 }
13208 do_forward = true;
13209 }
13210 if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
13211 {
13212 bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
13213 if (move_flags & ImGuiNavMoveFlags_WrapY)
13214 {
13215 bb_rel.TranslateX(+bb_rel.GetWidth()); // Next column
13216 clip_dir = ImGuiDir_Right;
13217 }
13218 do_forward = true;
13219 }
13220 if (!do_forward)
13221 return;
13222 window->NavRectRel[g.NavLayer] = bb_rel;
13223 NavClearPreferredPosForAxis(ImGuiAxis_X);
13224 NavClearPreferredPosForAxis(ImGuiAxis_Y);
13225 NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags);
13226}
13227
13228static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
13229{
13230 ImGuiContext& g = *GImGui;
13231 IM_UNUSED(g);
13232 int order = window->FocusOrder;
13233 IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
13234 IM_ASSERT(g.WindowsFocusOrder[order] == window);
13235 return order;
13236}
13237
13238static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
13239{
13240 ImGuiContext& g = *GImGui;
13241 for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
13242 if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
13243 return g.WindowsFocusOrder[i];
13244 return NULL;
13245}
13246
13247static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
13248{
13249 ImGuiContext& g = *GImGui;
13250 IM_ASSERT(g.NavWindowingTarget);
13251 if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
13252 return;
13253
13254 const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
13255 ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
13256 if (!window_target)
13257 window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
13258 if (window_target) // Don't reset windowing target if there's a single window in the list
13259 {
13260 g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
13261 g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
13262 }
13263 g.NavWindowingToggleLayer = false;
13264}
13265
13266// Windowing management mode
13267// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
13268// Gamepad: Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
13269static void ImGui::NavUpdateWindowing()
13270{
13271 ImGuiContext& g = *GImGui;
13272 ImGuiIO& io = g.IO;
13273
13274 ImGuiWindow* apply_focus_window = NULL;
13275 bool apply_toggle_layer = false;
13276
13277 ImGuiWindow* modal_window = GetTopMostPopupModal();
13278 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.
13279 if (!allow_windowing)
13280 g.NavWindowingTarget = NULL;
13281
13282 // Fade out
13283 if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
13284 {
13285 g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f);
13286 if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
13287 g.NavWindowingTargetAnim = NULL;
13288 }
13289
13290 // Start CTRL+Tab or Square+L/R window selection
13291 // (g.ConfigNavWindowingKeyNext/g.ConfigNavWindowingKeyPrev defaults are ImGuiMod_Ctrl|ImGuiKey_Tab and ImGuiMod_Ctrl|ImGuiMod_Shift|ImGuiKey_Tab)
13292 const ImGuiID owner_id = ImHashStr("###NavUpdateWindowing");
13293 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
13294 const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13295 const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, owner_id, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
13296 const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, owner_id, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
13297 const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && IsKeyPressed(ImGuiKey_NavGamepadMenu, 0, ImGuiInputFlags_None);
13298 const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
13299 if (start_windowing_with_gamepad || start_windowing_with_keyboard)
13300 if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
13301 {
13302 g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow;
13303 g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
13304 g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
13305 g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer
13306 g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
13307
13308 // Register ownership of our mods. Using ImGuiInputFlags_RouteGlobalHigh in the Shortcut() calls instead would probably be correct but may have more side-effects.
13309 if (keyboard_next_window || keyboard_prev_window)
13310 SetKeyOwnersForKeyChord((g.ConfigNavWindowingKeyNext | g.ConfigNavWindowingKeyPrev) & ImGuiMod_Mask_, owner_id);
13311 }
13312
13313 // Gamepad update
13314 g.NavWindowingTimer += io.DeltaTime;
13315 if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)
13316 {
13317 // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
13318 g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
13319
13320 // Select window to focus
13321 const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1);
13322 if (focus_change_dir != 0)
13323 {
13324 NavUpdateWindowingHighlightWindow(focus_change_dir);
13325 g.NavWindowingHighlightAlpha = 1.0f;
13326 }
13327
13328 // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
13329 if (!IsKeyDown(ImGuiKey_NavGamepadMenu))
13330 {
13331 g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
13332 if (g.NavWindowingToggleLayer && g.NavWindow)
13333 apply_toggle_layer = true;
13334 else if (!g.NavWindowingToggleLayer)
13335 apply_focus_window = g.NavWindowingTarget;
13336 g.NavWindowingTarget = NULL;
13337 }
13338 }
13339
13340 // Keyboard: Focus
13341 if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard)
13342 {
13343 // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
13344 ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_;
13345 IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows.
13346 g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
13347 if (keyboard_next_window || keyboard_prev_window)
13348 NavUpdateWindowingHighlightWindow(keyboard_next_window ? -1 : +1);
13349 else if ((io.KeyMods & shared_mods) != shared_mods)
13350 apply_focus_window = g.NavWindowingTarget;
13351 }
13352
13353 // Keyboard: Press and Release ALT to toggle menu layer
13354 const ImGuiKey windowing_toggle_keys[] = { ImGuiKey_LeftAlt, ImGuiKey_RightAlt };
13355 for (ImGuiKey windowing_toggle_key : windowing_toggle_keys)
13356 if (nav_keyboard_active && IsKeyPressed(windowing_toggle_key, ImGuiKeyOwner_None))
13357 {
13358 g.NavWindowingToggleLayer = true;
13359 g.NavWindowingToggleKey = windowing_toggle_key;
13360 g.NavInputSource = ImGuiInputSource_Keyboard;
13361 break;
13362 }
13363 if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard)
13364 {
13365 // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
13366 // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
13367 // - AltGR is Alt+Ctrl on some layout but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl).
13368 // We cancel toggling nav layer if an owner has claimed the key.
13369 if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper)
13370 g.NavWindowingToggleLayer = false;
13371 if (TestKeyOwner(g.NavWindowingToggleKey, ImGuiKeyOwner_None) == false || TestKeyOwner(ImGuiMod_Alt, ImGuiKeyOwner_None) == false)
13372 g.NavWindowingToggleLayer = false;
13373
13374 // Apply layer toggle on Alt release
13375 // Important: as before version <18314 we lacked an explicit IO event for focus gain/loss, we also compare mouse validity to detect old backends clearing mouse pos on focus loss.
13376 if (IsKeyReleased(g.NavWindowingToggleKey) && g.NavWindowingToggleLayer)
13377 if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
13378 if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev))
13379 apply_toggle_layer = true;
13380 if (!IsKeyDown(g.NavWindowingToggleKey))
13381 g.NavWindowingToggleLayer = false;
13382 }
13383
13384 // Move window
13385 if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
13386 {
13387 ImVec2 nav_move_dir;
13388 if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
13389 nav_move_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
13390 if (g.NavInputSource == ImGuiInputSource_Gamepad)
13391 nav_move_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
13392 if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f)
13393 {
13394 const float NAV_MOVE_SPEED = 800.0f;
13395 const float move_step = NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
13396 g.NavWindowingAccumDeltaPos += nav_move_dir * move_step;
13397 g.NavDisableMouseHover = true;
13398 ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaPos);
13399 if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
13400 {
13401 ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindowDockTree;
13402 SetWindowPos(moving_window, moving_window->Pos + accum_floored, ImGuiCond_Always);
13403 g.NavWindowingAccumDeltaPos -= accum_floored;
13404 }
13405 }
13406 }
13407
13408 // Apply final focus
13409 if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
13410 {
13411 // FIXME: Many actions here could be part of a higher-level/reused function. Why aren't they in FocusWindow()
13412 // Investigate for each of them: ClearActiveID(), NavRestoreHighlightAfterMove(), NavRestoreLastChildNavWindow(), ClosePopupsOverWindow(), NavInitWindow()
13413 ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
13414 ClearActiveID();
13415 NavRestoreHighlightAfterMove();
13416 ClosePopupsOverWindow(apply_focus_window, false);
13417 FocusWindow(apply_focus_window, ImGuiFocusRequestFlags_RestoreFocusedChild);
13418 apply_focus_window = g.NavWindow;
13419 if (apply_focus_window->NavLastIds[0] == 0)
13420 NavInitWindow(apply_focus_window, false);
13421
13422 // If the window has ONLY a menu layer (no main layer), select it directly
13423 // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
13424 // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
13425 // the target window as already been previewed once.
13426 // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
13427 // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
13428 // won't be valid.
13429 if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
13430 g.NavLayer = ImGuiNavLayer_Menu;
13431
13432 // Request OS level focus
13433 if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus)
13434 g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport);
13435 }
13436 if (apply_focus_window)
13437 g.NavWindowingTarget = NULL;
13438
13439 // Apply menu/layer toggle
13440 if (apply_toggle_layer && g.NavWindow)
13441 {
13442 ClearActiveID();
13443
13444 // Move to parent menu if necessary
13445 ImGuiWindow* new_nav_window = g.NavWindow;
13446 while (new_nav_window->ParentWindow
13447 && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
13448 && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
13449 && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
13450 new_nav_window = new_nav_window->ParentWindow;
13451 if (new_nav_window != g.NavWindow)
13452 {
13453 ImGuiWindow* old_nav_window = g.NavWindow;
13454 FocusWindow(new_nav_window);
13455 new_nav_window->NavLastChildNavWindow = old_nav_window;
13456 }
13457
13458 // Toggle layer
13459 const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
13460 if (new_nav_layer != g.NavLayer)
13461 {
13462 // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
13463 const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL);
13464 if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id)
13465 g.NavWindow->NavLastIds[new_nav_layer] = 0;
13466 NavRestoreLayer(new_nav_layer);
13467 NavRestoreHighlightAfterMove();
13468 }
13469 }
13470}
13471
13472// Window has already passed the IsWindowNavFocusable()
13473static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
13474{
13475 if (window->Flags & ImGuiWindowFlags_Popup)
13476 return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingPopup);
13477 if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
13478 return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingMainMenuBar);
13479 if (window->DockNodeAsHost)
13480 return "(Dock node)"; // Not normally shown to user.
13481 return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingUntitled);
13482}
13483
13484// Overlay displayed when using CTRL+TAB. Called by EndFrame().
13485void ImGui::NavUpdateWindowingOverlay()
13486{
13487 ImGuiContext& g = *GImGui;
13488 IM_ASSERT(g.NavWindowingTarget != NULL);
13489
13490 if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
13491 return;
13492
13493 if (g.NavWindowingListWindow == NULL)
13494 g.NavWindowingListWindow = FindWindowByName("###NavWindowingList");
13495 const ImGuiViewport* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ GetMainViewport();
13496 SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
13497 SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
13498 PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
13499 Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
13500 for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
13501 {
13502 ImGuiWindow* window = g.WindowsFocusOrder[n];
13503 IM_ASSERT(window != NULL); // Fix static analyzers
13504 if (!IsWindowNavFocusable(window))
13505 continue;
13506 const char* label = window->Name;
13507 if (label == FindRenderedTextEnd(label))
13508 label = GetFallbackWindowNameForWindowingList(window);
13509 Selectable(label, g.NavWindowingTarget == window);
13510 }
13511 End();
13512 PopStyleVar();
13513}
13514
13515
13516//-----------------------------------------------------------------------------
13517// [SECTION] DRAG AND DROP
13518//-----------------------------------------------------------------------------
13519
13520bool ImGui::IsDragDropActive()
13521{
13522 ImGuiContext& g = *GImGui;
13523 return g.DragDropActive;
13524}
13525
13526void ImGui::ClearDragDrop()
13527{
13528 ImGuiContext& g = *GImGui;
13529 g.DragDropActive = false;
13530 g.DragDropPayload.Clear();
13531 g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
13532 g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
13533 g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
13534 g.DragDropAcceptFrameCount = -1;
13535
13536 g.DragDropPayloadBufHeap.clear();
13537 memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
13538}
13539
13540bool ImGui::BeginTooltipHidden()
13541{
13542 ImGuiContext& g = *GImGui;
13543 bool ret = Begin("##Tooltip_Hidden", NULL, ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize);
13544 SetWindowHiddenAndSkipItemsForCurrentFrame(g.CurrentWindow);
13545 return ret;
13546}
13547
13548// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
13549// If the item has an identifier:
13550// - This assume/require the item to be activated (typically via ButtonBehavior).
13551// - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button.
13552// - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
13553// If the item has no identifier:
13554// - Currently always assume left mouse button.
13555bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
13556{
13557 ImGuiContext& g = *GImGui;
13558 ImGuiWindow* window = g.CurrentWindow;
13559
13560 // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
13561 // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
13562 ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
13563
13564 bool source_drag_active = false;
13565 ImGuiID source_id = 0;
13566 ImGuiID source_parent_id = 0;
13567 if (!(flags & ImGuiDragDropFlags_SourceExtern))
13568 {
13569 source_id = g.LastItemData.ID;
13570 if (source_id != 0)
13571 {
13572 // Common path: items with ID
13573 if (g.ActiveId != source_id)
13574 return false;
13575 if (g.ActiveIdMouseButton != -1)
13576 mouse_button = g.ActiveIdMouseButton;
13577 if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13578 return false;
13579 g.ActiveIdAllowOverlap = false;
13580 }
13581 else
13582 {
13583 // Uncommon path: items without ID
13584 if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13585 return false;
13586 if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
13587 return false;
13588
13589 // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
13590 // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.
13591 if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
13592 {
13593 IM_ASSERT(0);
13594 return false;
13595 }
13596
13597 // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()
13598 // We build a throwaway ID based on current ID stack + relative AABB of items in window.
13599 // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
13600 // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
13601 // Rely on keeping other window->LastItemXXX fields intact.
13602 source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect);
13603 KeepAliveID(source_id);
13604 bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id, g.LastItemData.InFlags);
13605 if (is_hovered && g.IO.MouseClicked[mouse_button])
13606 {
13607 SetActiveID(source_id, window);
13608 FocusWindow(window);
13609 }
13610 if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
13611 g.ActiveIdAllowOverlap = is_hovered;
13612 }
13613 if (g.ActiveId != source_id)
13614 return false;
13615 source_parent_id = window->IDStack.back();
13616 source_drag_active = IsMouseDragging(mouse_button);
13617
13618 // Disable navigation and key inputs while dragging + cancel existing request if any
13619 SetActiveIdUsingAllKeyboardKeys();
13620 }
13621 else
13622 {
13623 window = NULL;
13624 source_id = ImHashStr("#SourceExtern");
13625 source_drag_active = true;
13626 }
13627
13628 if (source_drag_active)
13629 {
13630 if (!g.DragDropActive)
13631 {
13632 IM_ASSERT(source_id != 0);
13633 ClearDragDrop();
13634 ImGuiPayload& payload = g.DragDropPayload;
13635 payload.SourceId = source_id;
13636 payload.SourceParentId = source_parent_id;
13637 g.DragDropActive = true;
13638 g.DragDropSourceFlags = flags;
13639 g.DragDropMouseButton = mouse_button;
13640 if (payload.SourceId == g.ActiveId)
13641 g.ActiveIdNoClearOnFocusLoss = true;
13642 }
13643 g.DragDropSourceFrameCount = g.FrameCount;
13644 g.DragDropWithinSource = true;
13645
13646 if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
13647 {
13648 // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
13649 // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
13650 bool ret;
13651 if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
13652 ret = BeginTooltipHidden();
13653 else
13654 ret = BeginTooltip();
13655 IM_ASSERT(ret); // FIXME-NEWBEGIN: If this ever becomes false, we need to Begin("##Hidden", NULL, ImGuiWindowFlags_NoSavedSettings) + SetWindowHiddendAndSkipItemsForCurrentFrame().
13656 IM_UNUSED(ret);
13657 }
13658
13659 if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
13660 g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
13661
13662 return true;
13663 }
13664 return false;
13665}
13666
13667void ImGui::EndDragDropSource()
13668{
13669 ImGuiContext& g = *GImGui;
13670 IM_ASSERT(g.DragDropActive);
13671 IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
13672
13673 if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
13674 EndTooltip();
13675
13676 // Discard the drag if have not called SetDragDropPayload()
13677 if (g.DragDropPayload.DataFrameCount == -1)
13678 ClearDragDrop();
13679 g.DragDropWithinSource = false;
13680}
13681
13682// Use 'cond' to choose to submit payload on drag start or every frame
13683bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
13684{
13685 ImGuiContext& g = *GImGui;
13686 ImGuiPayload& payload = g.DragDropPayload;
13687 if (cond == 0)
13688 cond = ImGuiCond_Always;
13689
13690 IM_ASSERT(type != NULL);
13691 IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
13692 IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
13693 IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
13694 IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
13695
13696 if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
13697 {
13698 // Copy payload
13699 ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
13700 g.DragDropPayloadBufHeap.resize(0);
13701 if (data_size > sizeof(g.DragDropPayloadBufLocal))
13702 {
13703 // Store in heap
13704 g.DragDropPayloadBufHeap.resize((int)data_size);
13705 payload.Data = g.DragDropPayloadBufHeap.Data;
13706 memcpy(payload.Data, data, data_size);
13707 }
13708 else if (data_size > 0)
13709 {
13710 // Store locally
13711 memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
13712 payload.Data = g.DragDropPayloadBufLocal;
13713 memcpy(payload.Data, data, data_size);
13714 }
13715 else
13716 {
13717 payload.Data = NULL;
13718 }
13719 payload.DataSize = (int)data_size;
13720 }
13721 payload.DataFrameCount = g.FrameCount;
13722
13723 // Return whether the payload has been accepted
13724 return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
13725}
13726
13727bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
13728{
13729 ImGuiContext& g = *GImGui;
13730 if (!g.DragDropActive)
13731 return false;
13732
13733 ImGuiWindow* window = g.CurrentWindow;
13734 ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
13735 if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree)
13736 return false;
13737 IM_ASSERT(id != 0);
13738 if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
13739 return false;
13740 if (window->SkipItems)
13741 return false;
13742
13743 IM_ASSERT(g.DragDropWithinTarget == false);
13744 g.DragDropTargetRect = bb;
13745 g.DragDropTargetClipRect = window->ClipRect; // May want to be overriden by user depending on use case?
13746 g.DragDropTargetId = id;
13747 g.DragDropWithinTarget = true;
13748 return true;
13749}
13750
13751// We don't use BeginDragDropTargetCustom() and duplicate its code because:
13752// 1) we use LastItemData's ImGuiItemStatusFlags_HoveredRect which handles items that push a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
13753// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
13754// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
13755bool ImGui::BeginDragDropTarget()
13756{
13757 ImGuiContext& g = *GImGui;
13758 if (!g.DragDropActive)
13759 return false;
13760
13761 ImGuiWindow* window = g.CurrentWindow;
13762 if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
13763 return false;
13764 ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
13765 if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree || window->SkipItems)
13766 return false;
13767
13768 const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
13769 ImGuiID id = g.LastItemData.ID;
13770 if (id == 0)
13771 {
13772 id = window->GetIDFromRectangle(display_rect);
13773 KeepAliveID(id);
13774 }
13775 if (g.DragDropPayload.SourceId == id)
13776 return false;
13777
13778 IM_ASSERT(g.DragDropWithinTarget == false);
13779 g.DragDropTargetRect = display_rect;
13780 g.DragDropTargetClipRect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasClipRect) ? g.LastItemData.ClipRect : window->ClipRect;
13781 g.DragDropTargetId = id;
13782 g.DragDropWithinTarget = true;
13783 return true;
13784}
13785
13786bool ImGui::IsDragDropPayloadBeingAccepted()
13787{
13788 ImGuiContext& g = *GImGui;
13789 return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
13790}
13791
13792const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
13793{
13794 ImGuiContext& g = *GImGui;
13795 ImGuiPayload& payload = g.DragDropPayload;
13796 IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
13797 IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ?
13798 if (type != NULL && !payload.IsDataType(type))
13799 return NULL;
13800
13801 // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
13802 // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
13803 const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
13804 ImRect r = g.DragDropTargetRect;
13805 float r_surface = r.GetWidth() * r.GetHeight();
13806 if (r_surface > g.DragDropAcceptIdCurrRectSurface)
13807 return NULL;
13808
13809 g.DragDropAcceptFlags = flags;
13810 g.DragDropAcceptIdCurr = g.DragDropTargetId;
13811 g.DragDropAcceptIdCurrRectSurface = r_surface;
13812 //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: accept\n", g.DragDropTargetId);
13813
13814 // Render default drop visuals
13815 payload.Preview = was_accepted_previously;
13816 flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame)
13817 if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
13818 RenderDragDropTargetRect(r, g.DragDropTargetClipRect);
13819
13820 g.DragDropAcceptFrameCount = g.FrameCount;
13821 payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting OS window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
13822 if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
13823 return NULL;
13824
13825 //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: return payload\n", g.DragDropTargetId);
13826 return &payload;
13827}
13828
13829// FIXME-STYLE FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
13830void ImGui::RenderDragDropTargetRect(const ImRect& bb, const ImRect& item_clip_rect)
13831{
13832 ImGuiContext& g = *GImGui;
13833 ImGuiWindow* window = g.CurrentWindow;
13834 ImRect bb_display = bb;
13835 bb_display.ClipWith(item_clip_rect); // Clip THEN expand so we have a way to visualize that target is not entirely visible.
13836 bb_display.Expand(3.5f);
13837 bool push_clip_rect = !window->ClipRect.Contains(bb_display);
13838 if (push_clip_rect)
13839 window->DrawList->PushClipRectFullScreen();
13840 window->DrawList->AddRect(bb_display.Min, bb_display.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
13841 if (push_clip_rect)
13842 window->DrawList->PopClipRect();
13843}
13844
13845const ImGuiPayload* ImGui::GetDragDropPayload()
13846{
13847 ImGuiContext& g = *GImGui;
13848 return (g.DragDropActive && g.DragDropPayload.DataFrameCount != -1) ? &g.DragDropPayload : NULL;
13849}
13850
13851void ImGui::EndDragDropTarget()
13852{
13853 ImGuiContext& g = *GImGui;
13854 IM_ASSERT(g.DragDropActive);
13855 IM_ASSERT(g.DragDropWithinTarget);
13856 g.DragDropWithinTarget = false;
13857
13858 // Clear drag and drop state payload right after delivery
13859 if (g.DragDropPayload.Delivery)
13860 ClearDragDrop();
13861}
13862
13863//-----------------------------------------------------------------------------
13864// [SECTION] LOGGING/CAPTURING
13865//-----------------------------------------------------------------------------
13866// All text output from the interface can be captured into tty/file/clipboard.
13867// By default, tree nodes are automatically opened during logging.
13868//-----------------------------------------------------------------------------
13869
13870// Pass text data straight to log (without being displayed)
13871static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
13872{
13873 if (g.LogFile)
13874 {
13875 g.LogBuffer.Buf.resize(0);
13876 g.LogBuffer.appendfv(fmt, args);
13877 ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
13878 }
13879 else
13880 {
13881 g.LogBuffer.appendfv(fmt, args);
13882 }
13883}
13884
13885void ImGui::LogText(const char* fmt, ...)
13886{
13887 ImGuiContext& g = *GImGui;
13888 if (!g.LogEnabled)
13889 return;
13890
13891 va_list args;
13892 va_start(args, fmt);
13893 LogTextV(g, fmt, args);
13894 va_end(args);
13895}
13896
13897void ImGui::LogTextV(const char* fmt, va_list args)
13898{
13899 ImGuiContext& g = *GImGui;
13900 if (!g.LogEnabled)
13901 return;
13902
13903 LogTextV(g, fmt, args);
13904}
13905
13906// Internal version that takes a position to decide on newline placement and pad items according to their depth.
13907// We split text into individual lines to add current tree level padding
13908// FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
13909void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
13910{
13911 ImGuiContext& g = *GImGui;
13912 ImGuiWindow* window = g.CurrentWindow;
13913
13914 const char* prefix = g.LogNextPrefix;
13915 const char* suffix = g.LogNextSuffix;
13916 g.LogNextPrefix = g.LogNextSuffix = NULL;
13917
13918 if (!text_end)
13919 text_end = FindRenderedTextEnd(text, text_end);
13920
13921 const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
13922 if (ref_pos)
13923 g.LogLinePosY = ref_pos->y;
13924 if (log_new_line)
13925 {
13926 LogText(IM_NEWLINE);
13927 g.LogLineFirstItem = true;
13928 }
13929
13930 if (prefix)
13931 LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure "##" are included here.
13932
13933 // Re-adjust padding if we have popped out of our starting depth
13934 if (g.LogDepthRef > window->DC.TreeDepth)
13935 g.LogDepthRef = window->DC.TreeDepth;
13936 const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
13937
13938 const char* text_remaining = text;
13939 for (;;)
13940 {
13941 // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
13942 // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
13943 const char* line_start = text_remaining;
13944 const char* line_end = ImStreolRange(line_start, text_end);
13945 const bool is_last_line = (line_end == text_end);
13946 if (line_start != line_end || !is_last_line)
13947 {
13948 const int line_length = (int)(line_end - line_start);
13949 const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
13950 LogText("%*s%.*s", indentation, "", line_length, line_start);
13951 g.LogLineFirstItem = false;
13952 if (*line_end == '\n')
13953 {
13954 LogText(IM_NEWLINE);
13955 g.LogLineFirstItem = true;
13956 }
13957 }
13958 if (is_last_line)
13959 break;
13960 text_remaining = line_end + 1;
13961 }
13962
13963 if (suffix)
13964 LogRenderedText(ref_pos, suffix, suffix + strlen(suffix));
13965}
13966
13967// Start logging/capturing text output
13968void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
13969{
13970 ImGuiContext& g = *GImGui;
13971 ImGuiWindow* window = g.CurrentWindow;
13972 IM_ASSERT(g.LogEnabled == false);
13973 IM_ASSERT(g.LogFile == NULL);
13974 IM_ASSERT(g.LogBuffer.empty());
13975 g.LogEnabled = true;
13976 g.LogType = type;
13977 g.LogNextPrefix = g.LogNextSuffix = NULL;
13978 g.LogDepthRef = window->DC.TreeDepth;
13979 g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
13980 g.LogLinePosY = FLT_MAX;
13981 g.LogLineFirstItem = true;
13982}
13983
13984// Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
13985void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
13986{
13987 ImGuiContext& g = *GImGui;
13988 g.LogNextPrefix = prefix;
13989 g.LogNextSuffix = suffix;
13990}
13991
13992void ImGui::LogToTTY(int auto_open_depth)
13993{
13994 ImGuiContext& g = *GImGui;
13995 if (g.LogEnabled)
13996 return;
13997 IM_UNUSED(auto_open_depth);
13998#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13999 LogBegin(ImGuiLogType_TTY, auto_open_depth);
14000 g.LogFile = stdout;
14001#endif
14002}
14003
14004// Start logging/capturing text output to given file
14005void ImGui::LogToFile(int auto_open_depth, const char* filename)
14006{
14007 ImGuiContext& g = *GImGui;
14008 if (g.LogEnabled)
14009 return;
14010
14011 // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
14012 // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
14013 // By opening the file in binary mode "ab" we have consistent output everywhere.
14014 if (!filename)
14015 filename = g.IO.LogFilename;
14016 if (!filename || !filename[0])
14017 return;
14018 ImFileHandle f = ImFileOpen(filename, "ab");
14019 if (!f)
14020 {
14021 IM_ASSERT(0);
14022 return;
14023 }
14024
14025 LogBegin(ImGuiLogType_File, auto_open_depth);
14026 g.LogFile = f;
14027}
14028
14029// Start logging/capturing text output to clipboard
14030void ImGui::LogToClipboard(int auto_open_depth)
14031{
14032 ImGuiContext& g = *GImGui;
14033 if (g.LogEnabled)
14034 return;
14035 LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
14036}
14037
14038void ImGui::LogToBuffer(int auto_open_depth)
14039{
14040 ImGuiContext& g = *GImGui;
14041 if (g.LogEnabled)
14042 return;
14043 LogBegin(ImGuiLogType_Buffer, auto_open_depth);
14044}
14045
14046void ImGui::LogFinish()
14047{
14048 ImGuiContext& g = *GImGui;
14049 if (!g.LogEnabled)
14050 return;
14051
14052 LogText(IM_NEWLINE);
14053 switch (g.LogType)
14054 {
14055 case ImGuiLogType_TTY:
14056#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
14057 fflush(g.LogFile);
14058#endif
14059 break;
14060 case ImGuiLogType_File:
14061 ImFileClose(g.LogFile);
14062 break;
14063 case ImGuiLogType_Buffer:
14064 break;
14065 case ImGuiLogType_Clipboard:
14066 if (!g.LogBuffer.empty())
14067 SetClipboardText(g.LogBuffer.begin());
14068 break;
14069 case ImGuiLogType_None:
14070 IM_ASSERT(0);
14071 break;
14072 }
14073
14074 g.LogEnabled = false;
14075 g.LogType = ImGuiLogType_None;
14076 g.LogFile = NULL;
14077 g.LogBuffer.clear();
14078}
14079
14080// Helper to display logging buttons
14081// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
14082void ImGui::LogButtons()
14083{
14084 ImGuiContext& g = *GImGui;
14085
14086 PushID("LogButtons");
14087#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
14088 const bool log_to_tty = Button("Log To TTY"); SameLine();
14089#else
14090 const bool log_to_tty = false;
14091#endif
14092 const bool log_to_file = Button("Log To File"); SameLine();
14093 const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
14094 PushTabStop(false);
14095 SetNextItemWidth(80.0f);
14096 SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
14097 PopTabStop();
14098 PopID();
14099
14100 // Start logging at the end of the function so that the buttons don't appear in the log
14101 if (log_to_tty)
14102 LogToTTY();
14103 if (log_to_file)
14104 LogToFile();
14105 if (log_to_clipboard)
14106 LogToClipboard();
14107}
14108
14109
14110//-----------------------------------------------------------------------------
14111// [SECTION] SETTINGS
14112//-----------------------------------------------------------------------------
14113// - UpdateSettings() [Internal]
14114// - MarkIniSettingsDirty() [Internal]
14115// - FindSettingsHandler() [Internal]
14116// - ClearIniSettings() [Internal]
14117// - LoadIniSettingsFromDisk()
14118// - LoadIniSettingsFromMemory()
14119// - SaveIniSettingsToDisk()
14120// - SaveIniSettingsToMemory()
14121//-----------------------------------------------------------------------------
14122// - CreateNewWindowSettings() [Internal]
14123// - FindWindowSettingsByID() [Internal]
14124// - FindWindowSettingsByWindow() [Internal]
14125// - ClearWindowSettings() [Internal]
14126// - WindowSettingsHandler_***() [Internal]
14127//-----------------------------------------------------------------------------
14128
14129// Called by NewFrame()
14130void ImGui::UpdateSettings()
14131{
14132 // Load settings on first frame (if not explicitly loaded manually before)
14133 ImGuiContext& g = *GImGui;
14134 if (!g.SettingsLoaded)
14135 {
14136 IM_ASSERT(g.SettingsWindows.empty());
14137 if (g.IO.IniFilename)
14138 LoadIniSettingsFromDisk(g.IO.IniFilename);
14139 g.SettingsLoaded = true;
14140 }
14141
14142 // Save settings (with a delay after the last modification, so we don't spam disk too much)
14143 if (g.SettingsDirtyTimer > 0.0f)
14144 {
14145 g.SettingsDirtyTimer -= g.IO.DeltaTime;
14146 if (g.SettingsDirtyTimer <= 0.0f)
14147 {
14148 if (g.IO.IniFilename != NULL)
14149 SaveIniSettingsToDisk(g.IO.IniFilename);
14150 else
14151 g.IO.WantSaveIniSettings = true; // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
14152 g.SettingsDirtyTimer = 0.0f;
14153 }
14154 }
14155}
14156
14157void ImGui::MarkIniSettingsDirty()
14158{
14159 ImGuiContext& g = *GImGui;
14160 if (g.SettingsDirtyTimer <= 0.0f)
14161 g.SettingsDirtyTimer = g.IO.IniSavingRate;
14162}
14163
14164void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
14165{
14166 ImGuiContext& g = *GImGui;
14167 if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
14168 if (g.SettingsDirtyTimer <= 0.0f)
14169 g.SettingsDirtyTimer = g.IO.IniSavingRate;
14170}
14171
14172void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler)
14173{
14174 ImGuiContext& g = *GImGui;
14175 IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL);
14176 g.SettingsHandlers.push_back(*handler);
14177}
14178
14179void ImGui::RemoveSettingsHandler(const char* type_name)
14180{
14181 ImGuiContext& g = *GImGui;
14182 if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name))
14183 g.SettingsHandlers.erase(handler);
14184}
14185
14186ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
14187{
14188 ImGuiContext& g = *GImGui;
14189 const ImGuiID type_hash = ImHashStr(type_name);
14190 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14191 if (handler.TypeHash == type_hash)
14192 return &handler;
14193 return NULL;
14194}
14195
14196// Clear all settings (windows, tables, docking etc.)
14197void ImGui::ClearIniSettings()
14198{
14199 ImGuiContext& g = *GImGui;
14200 g.SettingsIniData.clear();
14201 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14202 if (handler.ClearAllFn != NULL)
14203 handler.ClearAllFn(&g, &handler);
14204}
14205
14206void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
14207{
14208 size_t file_data_size = 0;
14209 char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
14210 if (!file_data)
14211 return;
14212 if (file_data_size > 0)
14213 LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
14214 IM_FREE(file_data);
14215}
14216
14217// Zero-tolerance, no error reporting, cheap .ini parsing
14218// Set ini_size==0 to let us use strlen(ini_data). Do not call this function with a 0 if your buffer is actually empty!
14219void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
14220{
14221 ImGuiContext& g = *GImGui;
14222 IM_ASSERT(g.Initialized);
14223 //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
14224 //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
14225
14226 // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
14227 // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
14228 if (ini_size == 0)
14229 ini_size = strlen(ini_data);
14230 g.SettingsIniData.Buf.resize((int)ini_size + 1);
14231 char* const buf = g.SettingsIniData.Buf.Data;
14232 char* const buf_end = buf + ini_size;
14233 memcpy(buf, ini_data, ini_size);
14234 buf_end[0] = 0;
14235
14236 // Call pre-read handlers
14237 // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
14238 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14239 if (handler.ReadInitFn != NULL)
14240 handler.ReadInitFn(&g, &handler);
14241
14242 void* entry_data = NULL;
14243 ImGuiSettingsHandler* entry_handler = NULL;
14244
14245 char* line_end = NULL;
14246 for (char* line = buf; line < buf_end; line = line_end + 1)
14247 {
14248 // Skip new lines markers, then find end of the line
14249 while (*line == '\n' || *line == '\r')
14250 line++;
14251 line_end = line;
14252 while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
14253 line_end++;
14254 line_end[0] = 0;
14255 if (line[0] == ';')
14256 continue;
14257 if (line[0] == '[' && line_end > line && line_end[-1] == ']')
14258 {
14259 // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
14260 line_end[-1] = 0;
14261 const char* name_end = line_end - 1;
14262 const char* type_start = line + 1;
14263 char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
14264 const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
14265 if (!type_end || !name_start)
14266 continue;
14267 *type_end = 0; // Overwrite first ']'
14268 name_start++; // Skip second '['
14269 entry_handler = FindSettingsHandler(type_start);
14270 entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
14271 }
14272 else if (entry_handler != NULL && entry_data != NULL)
14273 {
14274 // Let type handler parse the line
14275 entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
14276 }
14277 }
14278 g.SettingsLoaded = true;
14279
14280 // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
14281 memcpy(buf, ini_data, ini_size);
14282
14283 // Call post-read handlers
14284 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14285 if (handler.ApplyAllFn != NULL)
14286 handler.ApplyAllFn(&g, &handler);
14287}
14288
14289void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
14290{
14291 ImGuiContext& g = *GImGui;
14292 g.SettingsDirtyTimer = 0.0f;
14293 if (!ini_filename)
14294 return;
14295
14296 size_t ini_data_size = 0;
14297 const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
14298 ImFileHandle f = ImFileOpen(ini_filename, "wt");
14299 if (!f)
14300 return;
14301 ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
14302 ImFileClose(f);
14303}
14304
14305// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
14306const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
14307{
14308 ImGuiContext& g = *GImGui;
14309 g.SettingsDirtyTimer = 0.0f;
14310 g.SettingsIniData.Buf.resize(0);
14311 g.SettingsIniData.Buf.push_back(0);
14312 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14313 handler.WriteAllFn(&g, &handler, &g.SettingsIniData);
14314 if (out_size)
14315 *out_size = (size_t)g.SettingsIniData.size();
14316 return g.SettingsIniData.c_str();
14317}
14318
14319ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
14320{
14321 ImGuiContext& g = *GImGui;
14322
14323 if (g.IO.ConfigDebugIniSettings == false)
14324 {
14325 // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
14326 // Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier.
14327 if (const char* p = strstr(name, "###"))
14328 name = p;
14329 }
14330 const size_t name_len = strlen(name);
14331
14332 // Allocate chunk
14333 const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
14334 ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
14335 IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
14336 settings->ID = ImHashStr(name, name_len);
14337 memcpy(settings->GetName(), name, name_len + 1); // Store with zero terminator
14338
14339 return settings;
14340}
14341
14342// We don't provide a FindWindowSettingsByName() because Docking system doesn't always hold on names.
14343// This is called once per window .ini entry + once per newly instantiated window.
14344ImGuiWindowSettings* ImGui::FindWindowSettingsByID(ImGuiID id)
14345{
14346 ImGuiContext& g = *GImGui;
14347 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14348 if (settings->ID == id && !settings->WantDelete)
14349 return settings;
14350 return NULL;
14351}
14352
14353// This is faster if you are holding on a Window already as we don't need to perform a search.
14354ImGuiWindowSettings* ImGui::FindWindowSettingsByWindow(ImGuiWindow* window)
14355{
14356 ImGuiContext& g = *GImGui;
14357 if (window->SettingsOffset != -1)
14358 return g.SettingsWindows.ptr_from_offset(window->SettingsOffset);
14359 return FindWindowSettingsByID(window->ID);
14360}
14361
14362// This will revert window to its initial state, including enabling the ImGuiCond_FirstUseEver/ImGuiCond_Once conditions once more.
14363void ImGui::ClearWindowSettings(const char* name)
14364{
14365 //IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name);
14366 ImGuiContext& g = *GImGui;
14367 ImGuiWindow* window = FindWindowByName(name);
14368 if (window != NULL)
14369 {
14370 window->Flags |= ImGuiWindowFlags_NoSavedSettings;
14371 InitOrLoadWindowSettings(window, NULL);
14372 if (window->DockId != 0)
14373 DockContextProcessUndockWindow(&g, window, true);
14374 }
14375 if (ImGuiWindowSettings* settings = window ? FindWindowSettingsByWindow(window) : FindWindowSettingsByID(ImHashStr(name)))
14376 settings->WantDelete = true;
14377}
14378
14379static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
14380{
14381 ImGuiContext& g = *ctx;
14382 for (ImGuiWindow* window : g.Windows)
14383 window->SettingsOffset = -1;
14384 g.SettingsWindows.clear();
14385}
14386
14387static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
14388{
14389 ImGuiID id = ImHashStr(name);
14390 ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByID(id);
14391 if (settings)
14392 *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
14393 else
14394 settings = ImGui::CreateNewWindowSettings(name);
14395 settings->ID = id;
14396 settings->WantApply = true;
14397 return (void*)settings;
14398}
14399
14400static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
14401{
14402 ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
14403 int x, y;
14404 int i;
14405 ImU32 u1;
14406 if (sscanf(line, "Pos=%i,%i", &x, &y) == 2) { settings->Pos = ImVec2ih((short)x, (short)y); }
14407 else if (sscanf(line, "Size=%i,%i", &x, &y) == 2) { settings->Size = ImVec2ih((short)x, (short)y); }
14408 else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1) { settings->ViewportId = u1; }
14409 else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2){ settings->ViewportPos = ImVec2ih((short)x, (short)y); }
14410 else if (sscanf(line, "Collapsed=%d", &i) == 1) { settings->Collapsed = (i != 0); }
14411 else if (sscanf(line, "IsChild=%d", &i) == 1) { settings->IsChild = (i != 0); }
14412 else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2) { settings->DockId = u1; settings->DockOrder = (short)i; }
14413 else if (sscanf(line, "DockId=0x%X", &u1) == 1) { settings->DockId = u1; settings->DockOrder = -1; }
14414 else if (sscanf(line, "ClassId=0x%X", &u1) == 1) { settings->ClassId = u1; }
14415}
14416
14417// Apply to existing windows (if any)
14418static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
14419{
14420 ImGuiContext& g = *ctx;
14421 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14422 if (settings->WantApply)
14423 {
14424 if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
14425 ApplyWindowSettings(window, settings);
14426 settings->WantApply = false;
14427 }
14428}
14429
14430static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
14431{
14432 // Gather data from windows that were active during this session
14433 // (if a window wasn't opened in this session we preserve its settings)
14434 ImGuiContext& g = *ctx;
14435 for (ImGuiWindow* window : g.Windows)
14436 {
14437 if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
14438 continue;
14439
14440 ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByWindow(window);
14441 if (!settings)
14442 {
14443 settings = ImGui::CreateNewWindowSettings(window->Name);
14444 window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
14445 }
14446 IM_ASSERT(settings->ID == window->ID);
14447 settings->Pos = ImVec2ih(window->Pos - window->ViewportPos);
14448 settings->Size = ImVec2ih(window->SizeFull);
14449 settings->ViewportId = window->ViewportId;
14450 settings->ViewportPos = ImVec2ih(window->ViewportPos);
14451 IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId);
14452 settings->DockId = window->DockId;
14453 settings->ClassId = window->WindowClass.ClassId;
14454 settings->DockOrder = window->DockOrder;
14455 settings->Collapsed = window->Collapsed;
14456 settings->IsChild = (window->RootWindow != window); // Cannot rely on ImGuiWindowFlags_ChildWindow here as docked windows have this set.
14457 settings->WantDelete = false;
14458 }
14459
14460 // Write to text buffer
14461 buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
14462 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14463 {
14464 if (settings->WantDelete)
14465 continue;
14466 const char* settings_name = settings->GetName();
14467 buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
14468 if (settings->IsChild)
14469 {
14470 buf->appendf("IsChild=1\n");
14471 buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
14472 }
14473 else
14474 {
14475 if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
14476 {
14477 buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y);
14478 buf->appendf("ViewportId=0x%08X\n", settings->ViewportId);
14479 }
14480 if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
14481 buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
14482 if (settings->Size.x != 0 || settings->Size.y != 0)
14483 buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
14484 buf->appendf("Collapsed=%d\n", settings->Collapsed);
14485 if (settings->DockId != 0)
14486 {
14487 //buf->appendf("TabId=0x%08X\n", ImHashStr("#TAB", 4, settings->ID)); // window->TabId: this is not read back but writing it makes "debugging" the .ini data easier.
14488 if (settings->DockOrder == -1)
14489 buf->appendf("DockId=0x%08X\n", settings->DockId);
14490 else
14491 buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder);
14492 if (settings->ClassId != 0)
14493 buf->appendf("ClassId=0x%08X\n", settings->ClassId);
14494 }
14495 }
14496 buf->append("\n");
14497 }
14498}
14499
14500
14501//-----------------------------------------------------------------------------
14502// [SECTION] LOCALIZATION
14503//-----------------------------------------------------------------------------
14504
14505void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count)
14506{
14507 ImGuiContext& g = *GImGui;
14508 for (int n = 0; n < count; n++)
14509 g.LocalizationTable[entries[n].Key] = entries[n].Text;
14510}
14511
14512
14513//-----------------------------------------------------------------------------
14514// [SECTION] VIEWPORTS, PLATFORM WINDOWS
14515//-----------------------------------------------------------------------------
14516// - GetMainViewport()
14517// - FindViewportByID()
14518// - FindViewportByPlatformHandle()
14519// - SetCurrentViewport() [Internal]
14520// - SetWindowViewport() [Internal]
14521// - GetWindowAlwaysWantOwnViewport() [Internal]
14522// - UpdateTryMergeWindowIntoHostViewport() [Internal]
14523// - UpdateTryMergeWindowIntoHostViewports() [Internal]
14524// - TranslateWindowsInViewport() [Internal]
14525// - ScaleWindowsInViewport() [Internal]
14526// - FindHoveredViewportFromPlatformWindowStack() [Internal]
14527// - UpdateViewportsNewFrame() [Internal]
14528// - UpdateViewportsEndFrame() [Internal]
14529// - AddUpdateViewport() [Internal]
14530// - WindowSelectViewport() [Internal]
14531// - WindowSyncOwnedViewport() [Internal]
14532// - UpdatePlatformWindows()
14533// - RenderPlatformWindowsDefault()
14534// - FindPlatformMonitorForPos() [Internal]
14535// - FindPlatformMonitorForRect() [Internal]
14536// - UpdateViewportPlatformMonitor() [Internal]
14537// - DestroyPlatformWindow() [Internal]
14538// - DestroyPlatformWindows()
14539//-----------------------------------------------------------------------------
14540
14541ImGuiViewport* ImGui::GetMainViewport()
14542{
14543 ImGuiContext& g = *GImGui;
14544 return g.Viewports[0];
14545}
14546
14547// FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236)
14548ImGuiViewport* ImGui::FindViewportByID(ImGuiID id)
14549{
14550 ImGuiContext& g = *GImGui;
14551 for (ImGuiViewportP* viewport : g.Viewports)
14552 if (viewport->ID == id)
14553 return viewport;
14554 return NULL;
14555}
14556
14557ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle)
14558{
14559 ImGuiContext& g = *GImGui;
14560 for (ImGuiViewportP* viewport : g.Viewports)
14561 if (viewport->PlatformHandle == platform_handle)
14562 return viewport;
14563 return NULL;
14564}
14565
14566void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport)
14567{
14568 ImGuiContext& g = *GImGui;
14569 (void)current_window;
14570
14571 if (viewport)
14572 viewport->LastFrameActive = g.FrameCount;
14573 if (g.CurrentViewport == viewport)
14574 return;
14575 g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f;
14576 g.CurrentViewport = viewport;
14577 //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0);
14578
14579 // Notify platform layer of viewport changes
14580 // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
14581 if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport)
14582 g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport);
14583}
14584
14585void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
14586{
14587 // Abandon viewport
14588 if (window->ViewportOwned && window->Viewport->Window == window)
14589 window->Viewport->Size = ImVec2(0.0f, 0.0f);
14590
14591 window->Viewport = viewport;
14592 window->ViewportId = viewport->ID;
14593 window->ViewportOwned = (viewport->Window == window);
14594}
14595
14596static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window)
14597{
14598 // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own.
14599 ImGuiContext& g = *GImGui;
14600 if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge))
14601 if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
14602 if (!window->DockIsActive)
14603 if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0)
14604 if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0)
14605 return true;
14606 return false;
14607}
14608
14609static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
14610{
14611 ImGuiContext& g = *GImGui;
14612 if (window->Viewport == viewport)
14613 return false;
14614 if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) == 0)
14615 return false;
14616 if ((viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0)
14617 return false;
14618 if (!viewport->GetMainRect().Contains(window->Rect()))
14619 return false;
14620 if (GetWindowAlwaysWantOwnViewport(window))
14621 return false;
14622
14623 // FIXME: Can't use g.WindowsFocusOrder[] for root windows only as we care about Z order. If we maintained a DisplayOrder along with FocusOrder we could..
14624 for (ImGuiWindow* window_behind : g.Windows)
14625 {
14626 if (window_behind == window)
14627 break;
14628 if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow))
14629 if (window_behind->Viewport->GetMainRect().Overlaps(window->Rect()))
14630 return false;
14631 }
14632
14633 // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child)
14634 ImGuiViewportP* old_viewport = window->Viewport;
14635 if (window->ViewportOwned)
14636 for (int n = 0; n < g.Windows.Size; n++)
14637 if (g.Windows[n]->Viewport == old_viewport)
14638 SetWindowViewport(g.Windows[n], viewport);
14639 SetWindowViewport(window, viewport);
14640 BringWindowToDisplayFront(window);
14641
14642 return true;
14643}
14644
14645// FIXME: handle 0 to N host viewports
14646static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window)
14647{
14648 ImGuiContext& g = *GImGui;
14649 return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]);
14650}
14651
14652// Translate Dear ImGui windows when a Host Viewport has been moved
14653// (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
14654void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos)
14655{
14656 ImGuiContext& g = *GImGui;
14657 IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows));
14658
14659 // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently
14660 // translate imgui windows from OS-window-local to absolute coordinates or vice-versa.
14661 // 2) If it's not going to fit into the new size, keep it at same absolute position.
14662 // One problem with this is that most Win32 applications doesn't update their render while dragging,
14663 // and so the window will appear to teleport when releasing the mouse.
14664 const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable);
14665 ImRect test_still_fit_rect(old_pos, old_pos + viewport->Size);
14666 ImVec2 delta_pos = new_pos - old_pos;
14667 for (ImGuiWindow* window : g.Windows) // FIXME-OPT
14668 if (translate_all_windows || (window->Viewport == viewport && test_still_fit_rect.Contains(window->Rect())))
14669 TranslateWindow(window, delta_pos);
14670}
14671
14672// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
14673void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
14674{
14675 ImGuiContext& g = *GImGui;
14676 if (viewport->Window)
14677 {
14678 ScaleWindow(viewport->Window, scale);
14679 }
14680 else
14681 {
14682 for (ImGuiWindow* window : g.Windows)
14683 if (window->Viewport == viewport)
14684 ScaleWindow(window, scale);
14685 }
14686}
14687
14688// If the backend doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
14689// A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
14690// B) It requires Platform_GetWindowFocus to be implemented by backend.
14691ImGuiViewportP* ImGui::FindHoveredViewportFromPlatformWindowStack(const ImVec2& mouse_platform_pos)
14692{
14693 ImGuiContext& g = *GImGui;
14694 ImGuiViewportP* best_candidate = NULL;
14695 for (ImGuiViewportP* viewport : g.Viewports)
14696 if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_IsMinimized)) && viewport->GetMainRect().Contains(mouse_platform_pos))
14697 if (best_candidate == NULL || best_candidate->LastFocusedStampCount < viewport->LastFocusedStampCount)
14698 best_candidate = viewport;
14699 return best_candidate;
14700}
14701
14702// Update viewports and monitor infos
14703// Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info.
14704static void ImGui::UpdateViewportsNewFrame()
14705{
14706 ImGuiContext& g = *GImGui;
14707 IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size);
14708
14709 // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport)
14710 // Update Focused status
14711 const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0;
14712 if (viewports_enabled)
14713 {
14714 ImGuiViewportP* focused_viewport = NULL;
14715 for (ImGuiViewportP* viewport : g.Viewports)
14716 {
14717 const bool platform_funcs_available = viewport->PlatformWindowCreated;
14718 if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available)
14719 {
14720 bool is_minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport);
14721 if (is_minimized)
14722 viewport->Flags |= ImGuiViewportFlags_IsMinimized;
14723 else
14724 viewport->Flags &= ~ImGuiViewportFlags_IsMinimized;
14725 }
14726
14727 // Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport.
14728 // When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored.
14729 if (g.PlatformIO.Platform_GetWindowFocus && platform_funcs_available)
14730 {
14731 bool is_focused = g.PlatformIO.Platform_GetWindowFocus(viewport);
14732 if (is_focused)
14733 viewport->Flags |= ImGuiViewportFlags_IsFocused;
14734 else
14735 viewport->Flags &= ~ImGuiViewportFlags_IsFocused;
14736 if (is_focused)
14737 focused_viewport = viewport;
14738 }
14739 }
14740
14741 // Focused viewport has changed?
14742 if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID)
14743 {
14744 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Focused viewport changed %08X -> %08X, attempting to apply our focus.\n", g.PlatformLastFocusedViewportId, focused_viewport->ID);
14745 const ImGuiViewport* prev_focused_viewport = FindViewportByID(g.PlatformLastFocusedViewportId);
14746 const bool prev_focused_has_been_destroyed = (prev_focused_viewport == NULL) || (prev_focused_viewport->PlatformWindowCreated == false);
14747
14748 // Store a tag so we can infer z-order easily from all our windows
14749 // We compare PlatformLastFocusedViewportId so newly created viewports with _NoFocusOnAppearing flag
14750 // will keep the front most stamp instead of losing it back to their parent viewport.
14751 if (focused_viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
14752 focused_viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
14753 g.PlatformLastFocusedViewportId = focused_viewport->ID;
14754
14755 // Focus associated dear imgui window
14756 // - if focus didn't happen with a click within imgui boundaries, e.g. Clicking platform title bar. (#6299)
14757 // - if focus didn't happen because we destroyed another window (#6462)
14758 // FIXME: perhaps 'FocusTopMostWindowUnderOne()' can handle the 'focused_window->Window != NULL' case as well.
14759 const bool apply_imgui_focus_on_focused_viewport = !IsAnyMouseDown() && !prev_focused_has_been_destroyed;
14760 if (apply_imgui_focus_on_focused_viewport)
14761 {
14762 focused_viewport->LastFocusedHadNavWindow |= (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport); // Update so a window changing viewport won't lose focus.
14763 ImGuiFocusRequestFlags focus_request_flags = ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild;
14764 if (focused_viewport->Window != NULL)
14765 FocusWindow(focused_viewport->Window, focus_request_flags);
14766 else if (focused_viewport->LastFocusedHadNavWindow)
14767 FocusTopMostWindowUnderOne(NULL, NULL, focused_viewport, focus_request_flags); // Focus top most in viewport
14768 else
14769 FocusWindow(NULL, focus_request_flags); // No window had focus last time viewport was focused
14770 }
14771 }
14772 if (focused_viewport)
14773 focused_viewport->LastFocusedHadNavWindow = (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport);
14774 }
14775
14776 // Create/update main viewport with current platform position.
14777 // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
14778 ImGuiViewportP* main_viewport = g.Viewports[0];
14779 IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID);
14780 IM_ASSERT(main_viewport->Window == NULL);
14781 ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f);
14782 ImVec2 main_viewport_size = g.IO.DisplaySize;
14783 if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_IsMinimized))
14784 {
14785 main_viewport_pos = main_viewport->Pos; // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path)
14786 main_viewport_size = main_viewport->Size;
14787 }
14788 AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows);
14789
14790 g.CurrentDpiScale = 0.0f;
14791 g.CurrentViewport = NULL;
14792 g.MouseViewport = NULL;
14793 for (int n = 0; n < g.Viewports.Size; n++)
14794 {
14795 ImGuiViewportP* viewport = g.Viewports[n];
14796 viewport->Idx = n;
14797
14798 // Erase unused viewports
14799 if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2)
14800 {
14801 DestroyViewport(viewport);
14802 n--;
14803 continue;
14804 }
14805
14806 const bool platform_funcs_available = viewport->PlatformWindowCreated;
14807 if (viewports_enabled)
14808 {
14809 // Update Position and Size (from Platform Window to ImGui) if requested.
14810 // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities.
14811 if (!(viewport->Flags & ImGuiViewportFlags_IsMinimized) && platform_funcs_available)
14812 {
14813 // Viewport->WorkPos and WorkSize will be updated below
14814 if (viewport->PlatformRequestMove)
14815 viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
14816 if (viewport->PlatformRequestResize)
14817 viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport);
14818 }
14819 }
14820
14821 // Update/copy monitor info
14822 UpdateViewportPlatformMonitor(viewport);
14823
14824 // Lock down space taken by menu bars and status bars, reset the offset for functions like BeginMainMenuBar() to alter them again.
14825 viewport->WorkOffsetMin = viewport->BuildWorkOffsetMin;
14826 viewport->WorkOffsetMax = viewport->BuildWorkOffsetMax;
14827 viewport->BuildWorkOffsetMin = viewport->BuildWorkOffsetMax = ImVec2(0.0f, 0.0f);
14828 viewport->UpdateWorkRect();
14829
14830 // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back.
14831 viewport->Alpha = 1.0f;
14832
14833 // Translate Dear ImGui windows when a Host Viewport has been moved
14834 // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
14835 const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos;
14836 if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f))
14837 TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos);
14838
14839 // Update DPI scale
14840 float new_dpi_scale;
14841 if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available)
14842 new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
14843 else if (viewport->PlatformMonitor != -1)
14844 new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
14845 else
14846 new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
14847 if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale)
14848 {
14849 float scale_factor = new_dpi_scale / viewport->DpiScale;
14850 if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
14851 ScaleWindowsInViewport(viewport, scale_factor);
14852 //if (viewport == GetMainViewport())
14853 // g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
14854
14855 // Scale our window moving pivot so that the window will rescale roughly around the mouse position.
14856 // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border.
14857 // (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.)
14858 //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport)
14859 // g.ActiveIdClickOffset = ImTrunc(g.ActiveIdClickOffset * scale_factor);
14860 }
14861 viewport->DpiScale = new_dpi_scale;
14862 }
14863
14864 // Update fallback monitor
14865 g.PlatformMonitorsFullWorkRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
14866 if (g.PlatformIO.Monitors.Size == 0)
14867 {
14868 ImGuiPlatformMonitor* monitor = &g.FallbackMonitor;
14869 monitor->MainPos = main_viewport->Pos;
14870 monitor->MainSize = main_viewport->Size;
14871 monitor->WorkPos = main_viewport->WorkPos;
14872 monitor->WorkSize = main_viewport->WorkSize;
14873 monitor->DpiScale = main_viewport->DpiScale;
14874 g.PlatformMonitorsFullWorkRect.Add(monitor->WorkPos);
14875 g.PlatformMonitorsFullWorkRect.Add(monitor->WorkPos + monitor->WorkSize);
14876 }
14877 for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
14878 {
14879 g.PlatformMonitorsFullWorkRect.Add(monitor.WorkPos);
14880 g.PlatformMonitorsFullWorkRect.Add(monitor.WorkPos + monitor.WorkSize);
14881 }
14882
14883 if (!viewports_enabled)
14884 {
14885 g.MouseViewport = main_viewport;
14886 return;
14887 }
14888
14889 // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
14890 // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set.
14891 ImGuiViewportP* viewport_hovered = NULL;
14892 if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
14893 {
14894 viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL;
14895 if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
14896 viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); // Backend failed to handle _NoInputs viewport: revert to our fallback.
14897 }
14898 else
14899 {
14900 // If the backend doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search:
14901 // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
14902 // B) won't take account of how the backend apply parent<>child relationship to secondary viewports, which affects their Z order.
14903 // C) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO)
14904 viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos);
14905 }
14906 if (viewport_hovered != NULL)
14907 g.MouseLastHoveredViewport = viewport_hovered;
14908 else if (g.MouseLastHoveredViewport == NULL)
14909 g.MouseLastHoveredViewport = g.Viewports[0];
14910
14911 // Update mouse reference viewport
14912 // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode)
14913 // (MovingViewport->Viewport will be NULL in the rare situation where the window disappared while moving, set UpdateMouseMovingWindowNewFrame() for details)
14914 if (g.MovingWindow && g.MovingWindow->Viewport)
14915 g.MouseViewport = g.MovingWindow->Viewport;
14916 else
14917 g.MouseViewport = g.MouseLastHoveredViewport;
14918
14919 // When dragging something, always refer to the last hovered viewport.
14920 // - when releasing a moving window we will revert to aiming behind (at viewport_hovered)
14921 // - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info)
14922 // - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release.
14923 // FIXME-VIEWPORT: This is essentially broken, when ImGuiBackendFlags_HasMouseHoveredViewport is set we want to trust when viewport_hovered==NULL and use that.
14924 const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive;
14925 if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL)
14926 viewport_hovered = g.MouseLastHoveredViewport;
14927 if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown())
14928 if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
14929 g.MouseViewport = viewport_hovered;
14930
14931 IM_ASSERT(g.MouseViewport != NULL);
14932}
14933
14934// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
14935static void ImGui::UpdateViewportsEndFrame()
14936{
14937 ImGuiContext& g = *GImGui;
14938 g.PlatformIO.Viewports.resize(0);
14939 for (int i = 0; i < g.Viewports.Size; i++)
14940 {
14941 ImGuiViewportP* viewport = g.Viewports[i];
14942 viewport->LastPos = viewport->Pos;
14943 if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f)
14944 if (i > 0) // Always include main viewport in the list
14945 continue;
14946 if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window))
14947 continue;
14948 if (i > 0)
14949 IM_ASSERT(viewport->Window != NULL);
14950 g.PlatformIO.Viewports.push_back(viewport);
14951 }
14952 g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called
14953}
14954
14955// FIXME: We should ideally refactor the system to call this every frame (we currently don't)
14956ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags)
14957{
14958 ImGuiContext& g = *GImGui;
14959 IM_ASSERT(id != 0);
14960
14961 flags |= ImGuiViewportFlags_IsPlatformWindow;
14962 if (window != NULL)
14963 {
14964 if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window)
14965 flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing;
14966 if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs))
14967 flags |= ImGuiViewportFlags_NoInputs;
14968 if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing)
14969 flags |= ImGuiViewportFlags_NoFocusOnAppearing;
14970 }
14971
14972 ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id);
14973 if (viewport)
14974 {
14975 // Always update for main viewport as we are already pulling correct platform pos/size (see #4900)
14976 if (!viewport->PlatformRequestMove || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
14977 viewport->Pos = pos;
14978 if (!viewport->PlatformRequestResize || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
14979 viewport->Size = size;
14980 viewport->Flags = flags | (viewport->Flags & (ImGuiViewportFlags_IsMinimized | ImGuiViewportFlags_IsFocused)); // Preserve existing flags
14981 }
14982 else
14983 {
14984 // New viewport
14985 viewport = IM_NEW(ImGuiViewportP)();
14986 viewport->ID = id;
14987 viewport->Idx = g.Viewports.Size;
14988 viewport->Pos = viewport->LastPos = pos;
14989 viewport->Size = size;
14990 viewport->Flags = flags;
14991 UpdateViewportPlatformMonitor(viewport);
14992 g.Viewports.push_back(viewport);
14993 g.ViewportCreatedCount++;
14994 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Add Viewport %08X '%s'\n", id, window ? window->Name : "<NULL>");
14995
14996 // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport.
14997 // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame
14998 g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x);
14999 g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y);
15000 g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x);
15001 g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y);
15002
15003 // Store initial DpiScale before the OS platform window creation, based on expected monitor data.
15004 // This is so we can select an appropriate font size on the first frame of our window lifetime
15005 if (viewport->PlatformMonitor != -1)
15006 viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
15007 }
15008
15009 viewport->Window = window;
15010 viewport->LastFrameActive = g.FrameCount;
15011 viewport->UpdateWorkRect();
15012 IM_ASSERT(window == NULL || viewport->ID == window->ID);
15013
15014 if (window != NULL)
15015 window->ViewportOwned = true;
15016
15017 return viewport;
15018}
15019
15020static void ImGui::DestroyViewport(ImGuiViewportP* viewport)
15021{
15022 // Clear references to this viewport in windows (window->ViewportId becomes the master data)
15023 ImGuiContext& g = *GImGui;
15024 for (ImGuiWindow* window : g.Windows)
15025 {
15026 if (window->Viewport != viewport)
15027 continue;
15028 window->Viewport = NULL;
15029 window->ViewportOwned = false;
15030 }
15031 if (viewport == g.MouseLastHoveredViewport)
15032 g.MouseLastHoveredViewport = NULL;
15033
15034 // Destroy
15035 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Delete Viewport %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15036 DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here.
15037 IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false);
15038 IM_ASSERT(g.Viewports[viewport->Idx] == viewport);
15039 g.Viewports.erase(g.Viewports.Data + viewport->Idx);
15040 IM_DELETE(viewport);
15041}
15042
15043// FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten.
15044static void ImGui::WindowSelectViewport(ImGuiWindow* window)
15045{
15046 ImGuiContext& g = *GImGui;
15047 ImGuiWindowFlags flags = window->Flags;
15048 window->ViewportAllowPlatformMonitorExtend = -1;
15049
15050 // Restore main viewport if multi-viewport is not supported by the backend
15051 ImGuiViewportP* main_viewport = (ImGuiViewportP*)(void*)GetMainViewport();
15052 if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
15053 {
15054 SetWindowViewport(window, main_viewport);
15055 return;
15056 }
15057 window->ViewportOwned = false;
15058
15059 // Appearing popups reset their viewport so they can inherit again
15060 if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing)
15061 {
15062 window->Viewport = NULL;
15063 window->ViewportId = 0;
15064 }
15065
15066 if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0)
15067 {
15068 // By default inherit from parent window
15069 if (window->Viewport == NULL && window->ParentWindow && (!window->ParentWindow->IsFallbackWindow || window->ParentWindow->WasActive))
15070 window->Viewport = window->ParentWindow->Viewport;
15071
15072 // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file
15073 if (window->Viewport == NULL && window->ViewportId != 0)
15074 {
15075 window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId);
15076 if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX)
15077 window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None);
15078 }
15079 }
15080
15081 bool lock_viewport = false;
15082 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport)
15083 {
15084 // Code explicitly request a viewport
15085 window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId);
15086 window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet.
15087 if (window->Viewport && (window->Flags & ImGuiWindowFlags_DockNodeHost) != 0 && window->Viewport->Window != NULL)
15088 {
15089 window->Viewport->Window = window;
15090 window->Viewport->ID = window->ViewportId = window->ID; // Overwrite ID (always owned by node)
15091 }
15092 lock_viewport = true;
15093 }
15094 else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu))
15095 {
15096 // Always inherit viewport from parent window
15097 if (window->DockNode && window->DockNode->HostWindow)
15098 IM_ASSERT(window->DockNode->HostWindow->Viewport == window->ParentWindow->Viewport);
15099 window->Viewport = window->ParentWindow->Viewport;
15100 }
15101 else if (window->DockNode && window->DockNode->HostWindow)
15102 {
15103 // This covers the "always inherit viewport from parent window" case for when a window reattach to a node that was just created mid-frame
15104 window->Viewport = window->DockNode->HostWindow->Viewport;
15105 }
15106 else if (flags & ImGuiWindowFlags_Tooltip)
15107 {
15108 window->Viewport = g.MouseViewport;
15109 }
15110 else if (GetWindowAlwaysWantOwnViewport(window))
15111 {
15112 window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
15113 }
15114 else if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window && IsMousePosValid())
15115 {
15116 if (window->Viewport != NULL && window->Viewport->Window == window)
15117 window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
15118 }
15119 else
15120 {
15121 // Merge into host viewport?
15122 // We cannot test window->ViewportOwned as it set lower in the function.
15123 // Testing (g.ActiveId == 0 || g.ActiveIdAllowOverlap) to avoid merging during a short-term widget interaction. Main intent was to avoid during resize (see #4212)
15124 bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && (g.ActiveId == 0 || g.ActiveIdAllowOverlap));
15125 if (try_to_merge_into_host_viewport)
15126 UpdateTryMergeWindowIntoHostViewports(window);
15127 }
15128
15129 // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport
15130 if (window->Viewport == NULL)
15131 if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport))
15132 window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
15133
15134 // Mark window as allowed to protrude outside of its viewport and into the current monitor
15135 if (!lock_viewport)
15136 {
15137 if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
15138 {
15139 // We need to take account of the possibility that mouse may become invalid.
15140 // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds.
15141 ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos;
15142 bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow);
15143 bool mouse_valid = IsMousePosValid(&mouse_ref);
15144 if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid))
15145 window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos());
15146 else
15147 window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
15148 }
15149 else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow) && window->DockNode == NULL)
15150 {
15151 // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code.
15152 const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true;
15153 if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible)
15154 {
15155 // Steal/transfer ownership
15156 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name);
15157 window->Viewport->Window = window;
15158 window->Viewport->ID = window->ID;
15159 window->Viewport->LastNameHash = 0;
15160 }
15161 else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge?
15162 {
15163 // New viewport
15164 window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
15165 }
15166 }
15167 else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0)
15168 {
15169 // Regular (non-child, non-popup) windows by default are also allowed to protrude
15170 // Child windows are kept contained within their parent.
15171 window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
15172 }
15173 }
15174
15175 // Update flags
15176 window->ViewportOwned = (window == window->Viewport->Window);
15177 window->ViewportId = window->Viewport->ID;
15178
15179 // If the OS window has a title bar, hide our imgui title bar
15180 //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
15181 // window->Flags |= ImGuiWindowFlags_NoTitleBar;
15182}
15183
15184void ImGui::WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack)
15185{
15186 ImGuiContext& g = *GImGui;
15187
15188 bool viewport_rect_changed = false;
15189
15190 // Synchronize window --> viewport in most situations
15191 // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM
15192 if (window->Viewport->PlatformRequestMove)
15193 {
15194 window->Pos = window->Viewport->Pos;
15195 MarkIniSettingsDirty(window);
15196 }
15197 else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0)
15198 {
15199 viewport_rect_changed = true;
15200 window->Viewport->Pos = window->Pos;
15201 }
15202
15203 if (window->Viewport->PlatformRequestResize)
15204 {
15205 window->Size = window->SizeFull = window->Viewport->Size;
15206 MarkIniSettingsDirty(window);
15207 }
15208 else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0)
15209 {
15210 viewport_rect_changed = true;
15211 window->Viewport->Size = window->Size;
15212 }
15213 window->Viewport->UpdateWorkRect();
15214
15215 // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame()
15216 // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect.
15217 if (viewport_rect_changed)
15218 UpdateViewportPlatformMonitor(window->Viewport);
15219
15220 // Update common viewport flags
15221 const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear;
15222 ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear;
15223 ImGuiWindowFlags window_flags = window->Flags;
15224 const bool is_modal = (window_flags & ImGuiWindowFlags_Modal) != 0;
15225 const bool is_short_lived_floating_window = (window_flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0;
15226 if (window_flags & ImGuiWindowFlags_Tooltip)
15227 viewport_flags |= ImGuiViewportFlags_TopMost;
15228 if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal)
15229 viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon;
15230 if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window)
15231 viewport_flags |= ImGuiViewportFlags_NoDecoration;
15232
15233 // Not correct to set modal as topmost because:
15234 // - Because other popups can be stacked above a modal (e.g. combo box in a modal)
15235 // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost"
15236 //if (flags & ImGuiWindowFlags_Modal)
15237 // viewport_flags |= ImGuiViewportFlags_TopMost;
15238
15239 // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them
15240 // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration).
15241 // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app,
15242 // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere.
15243 if (is_short_lived_floating_window && !is_modal)
15244 viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick;
15245
15246 // We can overwrite viewport flags using ImGuiWindowClass (advanced users)
15247 if (window->WindowClass.ViewportFlagsOverrideSet)
15248 viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet;
15249 if (window->WindowClass.ViewportFlagsOverrideClear)
15250 viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear;
15251
15252 // We can also tell the backend that clearing the platform window won't be necessary,
15253 // as our window background is filling the viewport and we have disabled BgAlpha.
15254 // FIXME: Work on support for per-viewport transparency (#2766)
15255 if (!(window_flags & ImGuiWindowFlags_NoBackground))
15256 viewport_flags |= ImGuiViewportFlags_NoRendererClear;
15257
15258 window->Viewport->Flags = viewport_flags;
15259
15260 // Update parent viewport ID
15261 // (the !IsFallbackWindow test mimic the one done in WindowSelectViewport())
15262 if (window->WindowClass.ParentViewportId != (ImGuiID)-1)
15263 window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId;
15264 else if ((window_flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack && (!parent_window_in_stack->IsFallbackWindow || parent_window_in_stack->WasActive))
15265 window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID;
15266 else
15267 window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID;
15268}
15269
15270// Called by user at the end of the main loop, after EndFrame()
15271// This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api.
15272void ImGui::UpdatePlatformWindows()
15273{
15274 ImGuiContext& g = *GImGui;
15275 IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?");
15276 IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount);
15277 g.FrameCountPlatformEnded = g.FrameCount;
15278 if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
15279 return;
15280
15281 // Create/resize/destroy platform windows to match each active viewport.
15282 // Skip the main viewport (index 0), which is always fully handled by the application!
15283 for (int i = 1; i < g.Viewports.Size; i++)
15284 {
15285 ImGuiViewportP* viewport = g.Viewports[i];
15286
15287 // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window
15288 // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame)
15289 bool destroy_platform_window = false;
15290 destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1);
15291 destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window));
15292 if (destroy_platform_window)
15293 {
15294 DestroyPlatformWindow(viewport);
15295 continue;
15296 }
15297
15298 // New windows that appears directly in a new viewport won't always have a size on their first frame
15299 if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0)
15300 continue;
15301
15302 // Create window
15303 const bool is_new_platform_window = (viewport->PlatformWindowCreated == false);
15304 if (is_new_platform_window)
15305 {
15306 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Create Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15307 g.PlatformIO.Platform_CreateWindow(viewport);
15308 if (g.PlatformIO.Renderer_CreateWindow != NULL)
15309 g.PlatformIO.Renderer_CreateWindow(viewport);
15310 g.PlatformWindowsCreatedCount++;
15311 viewport->LastNameHash = 0;
15312 viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?)
15313 viewport->LastRendererSize = viewport->Size; // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it.
15314 viewport->PlatformWindowCreated = true;
15315 }
15316
15317 // Apply Position and Size (from ImGui to Platform/Renderer backends)
15318 if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove)
15319 g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos);
15320 if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize)
15321 g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size);
15322 if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize)
15323 g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size);
15324 viewport->LastPlatformPos = viewport->Pos;
15325 viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size;
15326
15327 // Update title bar (if it changed)
15328 if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window))
15329 {
15330 const char* title_begin = window_for_title->Name;
15331 char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin);
15332 const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin);
15333 if (viewport->LastNameHash != title_hash)
15334 {
15335 char title_end_backup_c = *title_end;
15336 *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain.
15337 g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin);
15338 *title_end = title_end_backup_c;
15339 viewport->LastNameHash = title_hash;
15340 }
15341 }
15342
15343 // Update alpha (if it changed)
15344 if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha)
15345 g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha);
15346 viewport->LastAlpha = viewport->Alpha;
15347
15348 // Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed.
15349 if (g.PlatformIO.Platform_UpdateWindow)
15350 g.PlatformIO.Platform_UpdateWindow(viewport);
15351
15352 if (is_new_platform_window)
15353 {
15354 // On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late)
15355 if (g.FrameCount < 3)
15356 viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing;
15357
15358 // Show window
15359 g.PlatformIO.Platform_ShowWindow(viewport);
15360
15361 // Even without focus, we assume the window becomes front-most.
15362 // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available.
15363 if (viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
15364 viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
15365 }
15366
15367 // Clear request flags
15368 viewport->ClearRequestFlags();
15369 }
15370}
15371
15372// This is a default/basic function for performing the rendering/swap of multiple Platform Windows.
15373// Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves.
15374// The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
15375//
15376// ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
15377// for (int i = 1; i < platform_io.Viewports.Size; i++)
15378// if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
15379// MyRenderFunction(platform_io.Viewports[i], my_args);
15380// for (int i = 1; i < platform_io.Viewports.Size; i++)
15381// if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
15382// MySwapBufferFunction(platform_io.Viewports[i], my_args);
15383//
15384void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg)
15385{
15386 // Skip the main viewport (index 0), which is always fully handled by the application!
15387 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
15388 for (int i = 1; i < platform_io.Viewports.Size; i++)
15389 {
15390 ImGuiViewport* viewport = platform_io.Viewports[i];
15391 if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
15392 continue;
15393 if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg);
15394 if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg);
15395 }
15396 for (int i = 1; i < platform_io.Viewports.Size; i++)
15397 {
15398 ImGuiViewport* viewport = platform_io.Viewports[i];
15399 if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
15400 continue;
15401 if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg);
15402 if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg);
15403 }
15404}
15405
15406static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos)
15407{
15408 ImGuiContext& g = *GImGui;
15409 for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
15410 {
15411 const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
15412 if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos))
15413 return monitor_n;
15414 }
15415 return -1;
15416}
15417
15418// Search for the monitor with the largest intersection area with the given rectangle
15419// We generally try to avoid searching loops but the monitor count should be very small here
15420// FIXME-OPT: We could test the last monitor used for that viewport first, and early
15421static int ImGui::FindPlatformMonitorForRect(const ImRect& rect)
15422{
15423 ImGuiContext& g = *GImGui;
15424
15425 const int monitor_count = g.PlatformIO.Monitors.Size;
15426 if (monitor_count <= 1)
15427 return monitor_count - 1;
15428
15429 // Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position.
15430 // This is necessary for tooltips which always resize down to zero at first.
15431 const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f);
15432 int best_monitor_n = -1;
15433 float best_monitor_surface = 0.001f;
15434
15435 for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++)
15436 {
15437 const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
15438 const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize);
15439 if (monitor_rect.Contains(rect))
15440 return monitor_n;
15441 ImRect overlapping_rect = rect;
15442 overlapping_rect.ClipWithFull(monitor_rect);
15443 float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight();
15444 if (overlapping_surface < best_monitor_surface)
15445 continue;
15446 best_monitor_surface = overlapping_surface;
15447 best_monitor_n = monitor_n;
15448 }
15449 return best_monitor_n;
15450}
15451
15452// Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor)
15453static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport)
15454{
15455 viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetMainRect());
15456}
15457
15458// Return value is always != NULL, but don't hold on it across frames.
15459const ImGuiPlatformMonitor* ImGui::GetViewportPlatformMonitor(ImGuiViewport* viewport_p)
15460{
15461 ImGuiContext& g = *GImGui;
15462 ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)viewport_p;
15463 int monitor_idx = viewport->PlatformMonitor;
15464 if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
15465 return &g.PlatformIO.Monitors[monitor_idx];
15466 return &g.FallbackMonitor;
15467}
15468
15469void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport)
15470{
15471 ImGuiContext& g = *GImGui;
15472 if (viewport->PlatformWindowCreated)
15473 {
15474 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Destroy Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15475 if (g.PlatformIO.Renderer_DestroyWindow)
15476 g.PlatformIO.Renderer_DestroyWindow(viewport);
15477 if (g.PlatformIO.Platform_DestroyWindow)
15478 g.PlatformIO.Platform_DestroyWindow(viewport);
15479 IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL);
15480
15481 // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize()
15482 // The righter way may be to leave it to the backend to set this flag all-together, and made the flag public.
15483 if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID)
15484 viewport->PlatformWindowCreated = false;
15485 }
15486 else
15487 {
15488 IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL);
15489 }
15490 viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL;
15491 viewport->ClearRequestFlags();
15492}
15493
15494void ImGui::DestroyPlatformWindows()
15495{
15496 // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the backend
15497 // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData.
15498 // It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling
15499 // code to operator a consistent manner.
15500 // It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without
15501 // crashing if it doesn't have data stored.
15502 ImGuiContext& g = *GImGui;
15503 for (ImGuiViewportP* viewport : g.Viewports)
15504 DestroyPlatformWindow(viewport);
15505}
15506
15507
15508//-----------------------------------------------------------------------------
15509// [SECTION] DOCKING
15510//-----------------------------------------------------------------------------
15511// Docking: Internal Types
15512// Docking: Forward Declarations
15513// Docking: ImGuiDockContext
15514// Docking: ImGuiDockContext Docking/Undocking functions
15515// Docking: ImGuiDockNode
15516// Docking: ImGuiDockNode Tree manipulation functions
15517// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
15518// Docking: Builder Functions
15519// Docking: Begin/End Support Functions (called from Begin/End)
15520// Docking: Settings
15521//-----------------------------------------------------------------------------
15522
15523//-----------------------------------------------------------------------------
15524// Typical Docking call flow: (root level is generally public API):
15525//-----------------------------------------------------------------------------
15526// - NewFrame() new dear imgui frame
15527// | DockContextNewFrameUpdateUndocking() - process queued undocking requests
15528// | - DockContextProcessUndockWindow() - process one window undocking request
15529// | - DockContextProcessUndockNode() - process one whole node undocking request
15530// | DockContextNewFrameUpdateUndocking() - process queue docking requests, create floating dock nodes
15531// | - update g.HoveredDockNode - [debug] update node hovered by mouse
15532// | - DockContextProcessDock() - process one docking request
15533// | - DockNodeUpdate()
15534// | - DockNodeUpdateForRootNode()
15535// | - DockNodeUpdateFlagsAndCollapse()
15536// | - DockNodeFindInfo()
15537// | - destroy unused node or tab bar
15538// | - create dock node host window
15539// | - Begin() etc.
15540// | - DockNodeStartMouseMovingWindow()
15541// | - DockNodeTreeUpdatePosSize()
15542// | - DockNodeTreeUpdateSplitter()
15543// | - draw node background
15544// | - DockNodeUpdateTabBar() - create/update tab bar for a docking node
15545// | - DockNodeAddTabBar()
15546// | - DockNodeWindowMenuUpdate()
15547// | - DockNodeCalcTabBarLayout()
15548// | - BeginTabBarEx()
15549// | - TabItemEx() calls
15550// | - EndTabBar()
15551// | - BeginDockableDragDropTarget()
15552// | - DockNodeUpdate() - recurse into child nodes...
15553//-----------------------------------------------------------------------------
15554// - DockSpace() user submit a dockspace into a window
15555// | Begin(Child) - create a child window
15556// | DockNodeUpdate() - call main dock node update function
15557// | End(Child)
15558// | ItemSize()
15559//-----------------------------------------------------------------------------
15560// - Begin()
15561// | BeginDocked()
15562// | BeginDockableDragDropSource()
15563// | BeginDockableDragDropTarget()
15564// | - DockNodePreviewDockRender()
15565//-----------------------------------------------------------------------------
15566// - EndFrame()
15567// | DockContextEndFrame()
15568//-----------------------------------------------------------------------------
15569
15570//-----------------------------------------------------------------------------
15571// Docking: Internal Types
15572//-----------------------------------------------------------------------------
15573// - ImGuiDockRequestType
15574// - ImGuiDockRequest
15575// - ImGuiDockPreviewData
15576// - ImGuiDockNodeSettings
15577// - ImGuiDockContext
15578//-----------------------------------------------------------------------------
15579
15587
15589{
15591 ImGuiWindow* DockTargetWindow; // Destination/Target Window to dock into (may be a loose window or a DockNode, might be NULL in which case DockTargetNode cannot be NULL)
15592 ImGuiDockNode* DockTargetNode; // Destination/Target Node to dock into
15593 ImGuiWindow* DockPayload; // Source/Payload window to dock (may be a loose window or a DockNode), [Optional]
15598 ImGuiDockNode* UndockTargetNode;
15599
15601 {
15605 DockSplitDir = ImGuiDir_None;
15606 DockSplitRatio = 0.5f;
15607 DockSplitOuter = false;
15608 }
15609};
15610
15612{
15613 ImGuiDockNode FutureNode;
15616 bool IsSidesAvailable; // Hold your breath, grammar freaks..
15617 bool IsSplitDirExplicit; // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window)
15618 ImGuiDockNode* SplitNode;
15619 ImGuiDir SplitDir;
15621 ImRect DropRectsDraw[ImGuiDir_COUNT + 1]; // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects()
15622
15623 ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; for (int n = 0; n < IM_ARRAYSIZE(DropRectsDraw); n++) DropRectsDraw[n] = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); }
15624};
15625
15626// Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes)
15628{
15629 ImGuiID ID;
15633 signed char SplitAxis;
15634 char Depth;
15635 ImGuiDockNodeFlags Flags; // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_)
15636 ImVec2ih Pos;
15637 ImVec2ih Size;
15638 ImVec2ih SizeRef;
15639 ImGuiDockNodeSettings() { memset(this, 0, sizeof(*this)); SplitAxis = ImGuiAxis_None; }
15640};
15641
15642//-----------------------------------------------------------------------------
15643// Docking: Forward Declarations
15644//-----------------------------------------------------------------------------
15645
15646namespace ImGui
15647{
15648 // ImGuiDockContext
15649 static ImGuiDockNode* DockContextAddNode(ImGuiContext* ctx, ImGuiID id);
15650 static void DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node);
15651 static void DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node);
15652 static void DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req);
15653 static void DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx);
15654 static ImGuiDockNode* DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window);
15655 static void DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count);
15656 static void DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id); // Use root_id==0 to add all
15657
15658 // ImGuiDockNode
15659 static void DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar);
15660 static void DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
15661 static void DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
15662 static ImGuiWindow* DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id);
15663 static void DockNodeApplyPosSizeToWindows(ImGuiDockNode* node);
15664 static void DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id);
15665 static void DockNodeHideHostWindow(ImGuiDockNode* node);
15666 static void DockNodeUpdate(ImGuiDockNode* node);
15667 static void DockNodeUpdateForRootNode(ImGuiDockNode* node);
15668 static void DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node);
15669 static void DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node);
15670 static void DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window);
15671 static void DockNodeAddTabBar(ImGuiDockNode* node);
15672 static void DockNodeRemoveTabBar(ImGuiDockNode* node);
15673 static void DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar);
15674 static void DockNodeUpdateVisibleFlag(ImGuiDockNode* node);
15675 static void DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window);
15676 static bool DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window);
15677 static void DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking);
15678 static void DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data);
15679 static void DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos);
15680 static void DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired);
15681 static bool DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos);
15682 static const char* DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; }
15683 static int DockNodeGetTabOrder(ImGuiWindow* window);
15684
15685 // ImGuiDockNode tree manipulations
15686 static void DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node);
15687 static void DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child);
15688 static void DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node = NULL);
15689 static void DockNodeTreeUpdateSplitter(ImGuiDockNode* node);
15690 static ImGuiDockNode* DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos);
15691 static ImGuiDockNode* DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node);
15692
15693 // Settings
15694 static void DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id);
15695 static void DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count);
15696 static ImGuiDockNodeSettings* DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id);
15697 static void DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
15698 static void DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
15699 static void* DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
15700 static void DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
15701 static void DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
15702}
15703
15704//-----------------------------------------------------------------------------
15705// Docking: ImGuiDockContext
15706//-----------------------------------------------------------------------------
15707// The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings,
15708// or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active.
15709// At boot time only, we run a simple GC to remove nodes that have no references.
15710// Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures),
15711// we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does).
15712// This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data.
15713//-----------------------------------------------------------------------------
15714// - DockContextInitialize()
15715// - DockContextShutdown()
15716// - DockContextClearNodes()
15717// - DockContextRebuildNodes()
15718// - DockContextNewFrameUpdateUndocking()
15719// - DockContextNewFrameUpdateDocking()
15720// - DockContextEndFrame()
15721// - DockContextFindNodeByID()
15722// - DockContextBindNodeToWindow()
15723// - DockContextGenNodeID()
15724// - DockContextAddNode()
15725// - DockContextRemoveNode()
15726// - ImGuiDockContextPruneNodeData
15727// - DockContextPruneUnusedSettingsNodes()
15728// - DockContextBuildNodesFromSettings()
15729// - DockContextBuildAddWindowsToNodes()
15730//-----------------------------------------------------------------------------
15731
15732void ImGui::DockContextInitialize(ImGuiContext* ctx)
15733{
15734 ImGuiContext& g = *ctx;
15735
15736 // Add .ini handle for persistent docking data
15737 ImGuiSettingsHandler ini_handler;
15738 ini_handler.TypeName = "Docking";
15739 ini_handler.TypeHash = ImHashStr("Docking");
15740 ini_handler.ClearAllFn = DockSettingsHandler_ClearAll;
15741 ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read
15742 ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen;
15743 ini_handler.ReadLineFn = DockSettingsHandler_ReadLine;
15744 ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll;
15745 ini_handler.WriteAllFn = DockSettingsHandler_WriteAll;
15746 g.SettingsHandlers.push_back(ini_handler);
15747
15748 g.DockNodeWindowMenuHandler = &DockNodeWindowMenuHandler_Default;
15749}
15750
15751void ImGui::DockContextShutdown(ImGuiContext* ctx)
15752{
15753 ImGuiDockContext* dc = &ctx->DockContext;
15754 for (int n = 0; n < dc->Nodes.Data.Size; n++)
15755 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15756 IM_DELETE(node);
15757}
15758
15759void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs)
15760{
15761 IM_UNUSED(ctx);
15762 IM_ASSERT(ctx == GImGui);
15763 DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs);
15764 DockBuilderRemoveNodeChildNodes(root_id);
15765}
15766
15767// [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch
15768// (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!)
15769void ImGui::DockContextRebuildNodes(ImGuiContext* ctx)
15770{
15771 ImGuiContext& g = *ctx;
15772 ImGuiDockContext* dc = &ctx->DockContext;
15773 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRebuildNodes\n");
15774 SaveIniSettingsToMemory();
15775 ImGuiID root_id = 0; // Rebuild all
15776 DockContextClearNodes(ctx, root_id, false);
15777 DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
15778 DockContextBuildAddWindowsToNodes(ctx, root_id);
15779}
15780
15781// Docking context update function, called by NewFrame()
15782void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx)
15783{
15784 ImGuiContext& g = *ctx;
15785 ImGuiDockContext* dc = &ctx->DockContext;
15786 if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
15787 {
15788 if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0)
15789 DockContextClearNodes(ctx, 0, true);
15790 return;
15791 }
15792
15793 // Setting NoSplit at runtime merges all nodes
15794 if (g.IO.ConfigDockingNoSplit)
15795 for (int n = 0; n < dc->Nodes.Data.Size; n++)
15796 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15797 if (node->IsRootNode() && node->IsSplitNode())
15798 {
15799 DockBuilderRemoveNodeChildNodes(node->ID);
15800 //dc->WantFullRebuild = true;
15801 }
15802
15803 // Process full rebuild
15804#if 0
15805 if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))
15806 dc->WantFullRebuild = true;
15807#endif
15808 if (dc->WantFullRebuild)
15809 {
15810 DockContextRebuildNodes(ctx);
15811 dc->WantFullRebuild = false;
15812 }
15813
15814 // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame)
15815 for (ImGuiDockRequest& req : dc->Requests)
15816 {
15817 if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetWindow)
15818 DockContextProcessUndockWindow(ctx, req.UndockTargetWindow);
15819 else if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetNode)
15820 DockContextProcessUndockNode(ctx, req.UndockTargetNode);
15821 }
15822}
15823
15824// Docking context update function, called by NewFrame()
15825void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx)
15826{
15827 ImGuiContext& g = *ctx;
15828 ImGuiDockContext* dc = &ctx->DockContext;
15829 if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
15830 return;
15831
15832 // [DEBUG] Store hovered dock node.
15833 // We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut.
15834 // Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering.
15835 g.DebugHoveredDockNode = NULL;
15836 if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow)
15837 {
15838 if (hovered_window->DockNodeAsHost)
15839 g.DebugHoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos);
15840 else if (hovered_window->RootWindow->DockNode)
15841 g.DebugHoveredDockNode = hovered_window->RootWindow->DockNode;
15842 }
15843
15844 // Process Docking requests
15845 for (ImGuiDockRequest& req : dc->Requests)
15846 if (req.Type == ImGuiDockRequestType_Dock)
15847 DockContextProcessDock(ctx, &req);
15848 dc->Requests.resize(0);
15849
15850 // Create windows for each automatic docking nodes
15851 // We can have NULL pointers when we delete nodes, but because ID are recycled this should amortize nicely (and our node count will never be very high)
15852 for (int n = 0; n < dc->Nodes.Data.Size; n++)
15853 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15854 if (node->IsFloatingNode())
15855 DockNodeUpdate(node);
15856}
15857
15858void ImGui::DockContextEndFrame(ImGuiContext* ctx)
15859{
15860 // Draw backgrounds of node missing their window
15861 ImGuiContext& g = *ctx;
15862 ImGuiDockContext* dc = &g.DockContext;
15863 for (int n = 0; n < dc->Nodes.Data.Size; n++)
15864 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15865 if (node->LastFrameActive == g.FrameCount && node->IsVisible && node->HostWindow && node->IsLeafNode() && !node->IsBgDrawnThisFrame)
15866 {
15867 ImRect bg_rect(node->Pos + ImVec2(0.0f, GetFrameHeight()), node->Pos + node->Size);
15868 ImDrawFlags bg_rounding_flags = CalcRoundingFlagsForRectInRect(bg_rect, node->HostWindow->Rect(), g.Style.DockingSeparatorSize);
15869 node->HostWindow->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
15870 node->HostWindow->DrawList->AddRectFilled(bg_rect.Min, bg_rect.Max, node->LastBgColor, node->HostWindow->WindowRounding, bg_rounding_flags);
15871 }
15872}
15873
15874ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id)
15875{
15876 return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(id);
15877}
15878
15879ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx)
15880{
15881 // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used)
15882 // FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0
15883 // We should poke in ctx->Nodes to find a suitable ID faster. Even more so trivial that ctx->Nodes lookup is already sorted.
15884 ImGuiID id = 0x0001;
15885 while (DockContextFindNodeByID(ctx, id) != NULL)
15886 id++;
15887 return id;
15888}
15889
15890static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id)
15891{
15892 // Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window.
15893 ImGuiContext& g = *ctx;
15894 if (id == 0)
15895 id = DockContextGenNodeID(ctx);
15896 else
15897 IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL);
15898
15899 // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings!
15900 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextAddNode 0x%08X\n", id);
15901 ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id);
15902 ctx->DockContext.Nodes.SetVoidPtr(node->ID, node);
15903 return node;
15904}
15905
15906static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node)
15907{
15908 ImGuiContext& g = *ctx;
15909 ImGuiDockContext* dc = &ctx->DockContext;
15910
15911 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRemoveNode 0x%08X\n", node->ID);
15912 IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node);
15913 IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL);
15914 IM_ASSERT(node->Windows.Size == 0);
15915
15916 if (node->HostWindow)
15917 node->HostWindow->DockNodeAsHost = NULL;
15918
15919 ImGuiDockNode* parent_node = node->ParentNode;
15920 const bool merge = (merge_sibling_into_parent_node && parent_node != NULL);
15921 if (merge)
15922 {
15923 IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node);
15924 ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]);
15925 DockNodeTreeMerge(&g, parent_node, sibling_node);
15926 }
15927 else
15928 {
15929 for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++)
15930 if (parent_node->ChildNodes[n] == node)
15931 node->ParentNode->ChildNodes[n] = NULL;
15932 dc->Nodes.SetVoidPtr(node->ID, NULL);
15933 IM_DELETE(node);
15934 }
15935}
15936
15937static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs)
15938{
15939 const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs;
15940 const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs;
15941 return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a);
15942}
15943
15944// Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here.
15951
15952// Garbage collect unused nodes (run once at init time)
15953static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx)
15954{
15955 ImGuiContext& g = *ctx;
15956 ImGuiDockContext* dc = &ctx->DockContext;
15957 IM_ASSERT(g.Windows.Size == 0);
15958
15959 ImPool<ImGuiDockContextPruneNodeData> pool;
15960 pool.Reserve(dc->NodesSettings.Size);
15961
15962 // Count child nodes and compute RootID
15963 for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
15964 {
15965 ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
15966 ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0;
15967 pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID;
15968 if (settings->ParentNodeId)
15969 pool.GetOrAddByKey(settings->ParentNodeId)->CountChildNodes++;
15970 }
15971
15972 // Count reference to dock ids from dockspaces
15973 // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes()
15974 for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
15975 {
15976 ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
15977 if (settings->ParentWindowId != 0)
15978 if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->ParentWindowId))
15979 if (window_settings->DockId)
15980 if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(window_settings->DockId))
15981 data->CountChildNodes++;
15982 }
15983
15984 // Count reference to dock ids from window settings
15985 // We guard against the possibility of an invalid .ini file (RootID may point to a missing node)
15986 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
15987 if (ImGuiID dock_id = settings->DockId)
15988 if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id))
15989 {
15990 data->CountWindows++;
15991 if (ImGuiDockContextPruneNodeData* data_root = (data->RootId == dock_id) ? data : pool.GetByKey(data->RootId))
15992 data_root->CountChildWindows++;
15993 }
15994
15995 // Prune
15996 for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
15997 {
15998 ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
15999 ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID);
16000 if (data->CountWindows > 1)
16001 continue;
16002 ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(data->RootId);
16003
16004 bool remove = false;
16005 remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode)); // Floating root node with only 1 window
16006 remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window
16007 remove |= (data_root->CountChildWindows == 0);
16008 if (remove)
16009 {
16010 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID);
16011 DockSettingsRemoveNodeReferences(&settings->ID, 1);
16012 settings->ID = 0;
16013 }
16014 }
16015}
16016
16017static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count)
16018{
16019 // Build nodes
16020 for (int node_n = 0; node_n < node_settings_count; node_n++)
16021 {
16022 ImGuiDockNodeSettings* settings = &node_settings_array[node_n];
16023 if (settings->ID == 0)
16024 continue;
16025 ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID);
16026 node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, settings->ParentNodeId) : NULL;
16027 node->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
16028 node->Size = ImVec2(settings->Size.x, settings->Size.y);
16029 node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y);
16030 node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode;
16031 if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL)
16032 node->ParentNode->ChildNodes[0] = node;
16033 else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL)
16034 node->ParentNode->ChildNodes[1] = node;
16035 node->SelectedTabId = settings->SelectedTabId;
16036 node->SplitAxis = (ImGuiAxis)settings->SplitAxis;
16037 node->SetLocalFlags(settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_);
16038
16039 // Bind host window immediately if it already exist (in case of a rebuild)
16040 // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set.
16041 char host_window_title[20];
16042 ImGuiDockNode* root_node = DockNodeGetRootNode(node);
16043 node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_ARRAYSIZE(host_window_title)));
16044 }
16045}
16046
16047void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id)
16048{
16049 // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame)
16050 ImGuiContext& g = *ctx;
16051 for (ImGuiWindow* window : g.Windows)
16052 {
16053 if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1)
16054 continue;
16055 if (window->DockNode != NULL)
16056 continue;
16057
16058 ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
16059 IM_ASSERT(node != NULL); // This should have been called after DockContextBuildNodesFromSettings()
16060 if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id)
16061 DockNodeAddWindow(node, window, true);
16062 }
16063}
16064
16065//-----------------------------------------------------------------------------
16066// Docking: ImGuiDockContext Docking/Undocking functions
16067//-----------------------------------------------------------------------------
16068// - DockContextQueueDock()
16069// - DockContextQueueUndockWindow()
16070// - DockContextQueueUndockNode()
16071// - DockContextQueueNotifyRemovedNode()
16072// - DockContextProcessDock()
16073// - DockContextProcessUndockWindow()
16074// - DockContextProcessUndockNode()
16075// - DockContextCalcDropPosForDocking()
16076//-----------------------------------------------------------------------------
16077
16078void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer)
16079{
16080 IM_ASSERT(target != payload);
16081 ImGuiDockRequest req;
16083 req.DockTargetWindow = target;
16084 req.DockTargetNode = target_node;
16085 req.DockPayload = payload;
16086 req.DockSplitDir = split_dir;
16087 req.DockSplitRatio = split_ratio;
16088 req.DockSplitOuter = split_outer;
16089 ctx->DockContext.Requests.push_back(req);
16090}
16091
16092void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window)
16093{
16094 ImGuiDockRequest req;
16096 req.UndockTargetWindow = window;
16097 ctx->DockContext.Requests.push_back(req);
16098}
16099
16100void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
16101{
16102 ImGuiDockRequest req;
16104 req.UndockTargetNode = node;
16105 ctx->DockContext.Requests.push_back(req);
16106}
16107
16108void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node)
16109{
16110 ImGuiDockContext* dc = &ctx->DockContext;
16111 for (ImGuiDockRequest& req : dc->Requests)
16112 if (req.DockTargetNode == node)
16113 req.Type = ImGuiDockRequestType_None;
16114}
16115
16116void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req)
16117{
16118 IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL));
16119 IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL);
16120
16121 ImGuiContext& g = *ctx;
16122 IM_UNUSED(g);
16123
16124 ImGuiWindow* payload_window = req->DockPayload; // Optional
16125 ImGuiWindow* target_window = req->DockTargetWindow;
16126 ImGuiDockNode* node = req->DockTargetNode;
16127 if (payload_window)
16128 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X target '%s' dock window '%s', split_dir %d\n", node ? node->ID : 0, target_window ? target_window->Name : "NULL", payload_window->Name, req->DockSplitDir);
16129 else
16130 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir);
16131
16132 // Decide which Tab will be selected at the end of the operation
16133 ImGuiID next_selected_id = 0;
16134 ImGuiDockNode* payload_node = NULL;
16135 if (payload_window)
16136 {
16137 payload_node = payload_window->DockNodeAsHost;
16138 payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later.
16139 if (payload_node && payload_node->IsLeafNode())
16140 next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId;
16141 if (payload_node == NULL)
16142 next_selected_id = payload_window->TabId;
16143 }
16144
16145 // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well
16146 // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==.
16147 if (node)
16148 IM_ASSERT(node->LastFrameAlive <= g.FrameCount);
16149 if (node && target_window && node == target_window->DockNodeAsHost)
16150 IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode());
16151
16152 // Create new node and add existing window to it
16153 if (node == NULL)
16154 {
16155 node = DockContextAddNode(ctx, 0);
16156 node->Pos = target_window->Pos;
16157 node->Size = target_window->Size;
16158 if (target_window->DockNodeAsHost == NULL)
16159 {
16160 DockNodeAddWindow(node, target_window, true);
16161 node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted;
16162 target_window->DockIsActive = true;
16163 }
16164 }
16165
16166 ImGuiDir split_dir = req->DockSplitDir;
16167 if (split_dir != ImGuiDir_None)
16168 {
16169 // Split into two, one side will be our payload node unless we are dropping a loose window
16170 const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
16171 const int split_inheritor_child_idx = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0; // Current contents will be moved to the opposite side
16172 const float split_ratio = req->DockSplitRatio;
16173 DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node); // payload_node may be NULL here!
16174 ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1];
16175 new_node->HostWindow = node->HostWindow;
16176 node = new_node;
16177 }
16178 node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
16179
16180 if (node != payload_node)
16181 {
16182 // Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!)
16183 if (node->Windows.Size > 0 && node->TabBar == NULL)
16184 {
16185 DockNodeAddTabBar(node);
16186 for (int n = 0; n < node->Windows.Size; n++)
16187 TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
16188 }
16189
16190 if (payload_node != NULL)
16191 {
16192 // Transfer full payload node (with 1+ child windows or child nodes)
16193 if (payload_node->IsSplitNode())
16194 {
16195 if (node->Windows.Size > 0)
16196 {
16197 // We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node.
16198 // In this situation, we move the windows of the target node into the currently visible node of the payload.
16199 // This allows us to preserve some of the underlying dock tree settings nicely.
16200 IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted.
16201 ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows;
16202 if (visible_node->TabBar)
16203 IM_ASSERT(visible_node->TabBar->Tabs.Size > 0);
16204 DockNodeMoveWindows(node, visible_node);
16205 DockNodeMoveWindows(visible_node, node);
16206 DockSettingsRenameNodeReferences(node->ID, visible_node->ID);
16207 }
16208 if (node->IsCentralNode())
16209 {
16210 // Central node property needs to be moved to a leaf node, pick the last focused one.
16211 // FIXME-DOCK: If we had to transfer other flags here, what would the policy be?
16212 ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeId);
16213 IM_ASSERT(last_focused_node != NULL);
16214 ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node);
16215 IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node));
16216 last_focused_node->SetLocalFlags(last_focused_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
16217 node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_CentralNode);
16218 last_focused_root_node->CentralNode = last_focused_node;
16219 }
16220
16221 IM_ASSERT(node->Windows.Size == 0);
16222 DockNodeMoveChildNodes(node, payload_node);
16223 }
16224 else
16225 {
16226 const ImGuiID payload_dock_id = payload_node->ID;
16227 DockNodeMoveWindows(node, payload_node);
16228 DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
16229 }
16230 DockContextRemoveNode(ctx, payload_node, true);
16231 }
16232 else if (payload_window)
16233 {
16234 // Transfer single window
16235 const ImGuiID payload_dock_id = payload_window->DockId;
16236 node->VisibleWindow = payload_window;
16237 DockNodeAddWindow(node, payload_window, true);
16238 if (payload_dock_id != 0)
16239 DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
16240 }
16241 }
16242 else
16243 {
16244 // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar
16245 node->WantHiddenTabBarUpdate = true;
16246 }
16247
16248 // Update selection immediately
16249 if (ImGuiTabBar* tab_bar = node->TabBar)
16250 tab_bar->NextSelectedTabId = next_selected_id;
16251 MarkIniSettingsDirty();
16252}
16253
16254// Problem:
16255// Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more
16256// than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic
16257// with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be
16258// due to missing ImGuiBackendFlags_HasMouseCursors backend flag).
16259// Solution:
16260// When undocking a window we currently force its maximum size to 90% of the host viewport or monitor.
16261// Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch).
16262static ImVec2 FixLargeWindowsWhenUndocking(const ImVec2& size, ImGuiViewport* ref_viewport)
16263{
16264 if (ref_viewport == NULL)
16265 return size;
16266
16267 ImGuiContext& g = *GImGui;
16268 ImVec2 max_size = ImTrunc(ref_viewport->WorkSize * 0.90f);
16269 if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
16270 {
16271 const ImGuiPlatformMonitor* monitor = ImGui::GetViewportPlatformMonitor(ref_viewport);
16272 max_size = ImTrunc(monitor->WorkSize * 0.90f);
16273 }
16274 return ImMin(size, max_size);
16275}
16276
16277void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref)
16278{
16279 ImGuiContext& g = *ctx;
16280 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockWindow window '%s', clear_persistent_docking_ref = %d\n", window->Name, clear_persistent_docking_ref);
16281 if (window->DockNode)
16282 DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId);
16283 else
16284 window->DockId = 0;
16285 window->Collapsed = false;
16286 window->DockIsActive = false;
16287 window->DockNodeIsVisible = window->DockTabIsVisible = false;
16288 window->Size = window->SizeFull = FixLargeWindowsWhenUndocking(window->SizeFull, window->Viewport);
16289
16290 MarkIniSettingsDirty();
16291}
16292
16293void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
16294{
16295 ImGuiContext& g = *ctx;
16296 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockNode node %08X\n", node->ID);
16297 IM_ASSERT(node->IsLeafNode());
16298 IM_ASSERT(node->Windows.Size >= 1);
16299
16300 if (node->IsRootNode() || node->IsCentralNode())
16301 {
16302 // In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload.
16303 ImGuiDockNode* new_node = DockContextAddNode(ctx, 0);
16304 new_node->Pos = node->Pos;
16305 new_node->Size = node->Size;
16306 new_node->SizeRef = node->SizeRef;
16307 DockNodeMoveWindows(new_node, node);
16308 DockSettingsRenameNodeReferences(node->ID, new_node->ID);
16309 node = new_node;
16310 }
16311 else
16312 {
16313 // Otherwise extract our node and merge our sibling back into the parent node.
16314 IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
16315 int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1;
16316 node->ParentNode->ChildNodes[index_in_parent] = NULL;
16317 DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]);
16318 node->ParentNode->AuthorityForViewport = ImGuiDataAuthority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport
16319 node->ParentNode = NULL;
16320 }
16321 for (ImGuiWindow* window : node->Windows)
16322 {
16323 window->Flags &= ~ImGuiWindowFlags_ChildWindow;
16324 if (window->ParentWindow)
16325 window->ParentWindow->DC.ChildWindows.find_erase(window);
16326 UpdateWindowParentAndRootLinks(window, window->Flags, NULL);
16327 }
16328 node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_DockNode;
16329 node->Size = FixLargeWindowsWhenUndocking(node->Size, node->Windows[0]->Viewport);
16330 node->WantMouseMove = true;
16331 MarkIniSettingsDirty();
16332}
16333
16334// This is mostly used for automation.
16335bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos)
16336{
16337 if (target != NULL && target_node == NULL)
16338 target_node = target->DockNode;
16339
16340 // In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects
16341 // (which would be functionally identical) we only show the outer one. Reflect this here.
16342 if (target_node && target_node->ParentNode == NULL && target_node->IsCentralNode() && split_dir != ImGuiDir_None)
16343 split_outer = true;
16344 ImGuiDockPreviewData split_data;
16345 DockNodePreviewDockSetup(target, target_node, payload_window, payload_node, &split_data, false, split_outer);
16346 if (split_data.DropRectsDraw[split_dir+1].IsInverted())
16347 return false;
16348 *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter();
16349 return true;
16350}
16351
16352//-----------------------------------------------------------------------------
16353// Docking: ImGuiDockNode
16354//-----------------------------------------------------------------------------
16355// - DockNodeGetTabOrder()
16356// - DockNodeAddWindow()
16357// - DockNodeRemoveWindow()
16358// - DockNodeMoveChildNodes()
16359// - DockNodeMoveWindows()
16360// - DockNodeApplyPosSizeToWindows()
16361// - DockNodeHideHostWindow()
16362// - ImGuiDockNodeFindInfoResults
16363// - DockNodeFindInfo()
16364// - DockNodeFindWindowByID()
16365// - DockNodeUpdateFlagsAndCollapse()
16366// - DockNodeUpdateHasCentralNodeFlag()
16367// - DockNodeUpdateVisibleFlag()
16368// - DockNodeStartMouseMovingWindow()
16369// - DockNodeUpdate()
16370// - DockNodeUpdateWindowMenu()
16371// - DockNodeBeginAmendTabBar()
16372// - DockNodeEndAmendTabBar()
16373// - DockNodeUpdateTabBar()
16374// - DockNodeAddTabBar()
16375// - DockNodeRemoveTabBar()
16376// - DockNodeIsDropAllowedOne()
16377// - DockNodeIsDropAllowed()
16378// - DockNodeCalcTabBarLayout()
16379// - DockNodeCalcSplitRects()
16380// - DockNodeCalcDropRectsAndTestMousePos()
16381// - DockNodePreviewDockSetup()
16382// - DockNodePreviewDockRender()
16383//-----------------------------------------------------------------------------
16384
16385ImGuiDockNode::ImGuiDockNode(ImGuiID id)
16386{
16387 ID = id;
16388 SharedFlags = LocalFlags = LocalFlagsInWindows = MergedFlags = ImGuiDockNodeFlags_None;
16389 ParentNode = ChildNodes[0] = ChildNodes[1] = NULL;
16390 TabBar = NULL;
16391 SplitAxis = ImGuiAxis_None;
16392
16393 State = ImGuiDockNodeState_Unknown;
16394 LastBgColor = IM_COL32_WHITE;
16395 HostWindow = VisibleWindow = NULL;
16396 CentralNode = OnlyNodeWithWindows = NULL;
16397 CountNodeWithWindows = 0;
16398 LastFrameAlive = LastFrameActive = LastFrameFocused = -1;
16399 LastFocusedNodeId = 0;
16400 SelectedTabId = 0;
16401 WantCloseTabId = 0;
16402 RefViewportId = 0;
16403 AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode;
16404 AuthorityForViewport = ImGuiDataAuthority_Auto;
16405 IsVisible = true;
16406 IsFocused = HasCloseButton = HasWindowMenuButton = HasCentralNodeChild = false;
16407 IsBgDrawnThisFrame = false;
16408 WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false;
16409}
16410
16411ImGuiDockNode::~ImGuiDockNode()
16412{
16413 IM_DELETE(TabBar);
16414 TabBar = NULL;
16415 ChildNodes[0] = ChildNodes[1] = NULL;
16416}
16417
16418int ImGui::DockNodeGetTabOrder(ImGuiWindow* window)
16419{
16420 ImGuiTabBar* tab_bar = window->DockNode->TabBar;
16421 if (tab_bar == NULL)
16422 return -1;
16423 ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, window->TabId);
16424 return tab ? TabBarGetTabOrder(tab_bar, tab) : -1;
16425}
16426
16427static void DockNodeHideWindowDuringHostWindowCreation(ImGuiWindow* window)
16428{
16429 window->Hidden = true;
16430 window->HiddenFramesCanSkipItems = window->Active ? 1 : 2;
16431}
16432
16433static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar)
16434{
16435 ImGuiContext& g = *GImGui; (void)g;
16436 if (window->DockNode)
16437 {
16438 // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node)
16439 IM_ASSERT(window->DockNode->ID != node->ID);
16440 DockNodeRemoveWindow(window->DockNode, window, 0);
16441 }
16442 IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL);
16443 IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name);
16444
16445 // If more than 2 windows appeared on the same frame leading to the creation of a new hosting window,
16446 // we'll hide windows until the host window is ready. Hide the 1st window after its been output (so it is not visible for one frame).
16447 // We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin()
16448 if (node->HostWindow == NULL && node->Windows.Size == 1 && node->Windows[0]->WasActive == false)
16449 DockNodeHideWindowDuringHostWindowCreation(node->Windows[0]);
16450
16451 node->Windows.push_back(window);
16452 node->WantHiddenTabBarUpdate = true;
16453 window->DockNode = node;
16454 window->DockId = node->ID;
16455 window->DockIsActive = (node->Windows.Size > 1);
16456 window->DockTabWantClose = false;
16457
16458 // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage.
16459 // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one.
16460 if (node->HostWindow == NULL && node->IsFloatingNode())
16461 {
16462 if (node->AuthorityForPos == ImGuiDataAuthority_Auto)
16463 node->AuthorityForPos = ImGuiDataAuthority_Window;
16464 if (node->AuthorityForSize == ImGuiDataAuthority_Auto)
16465 node->AuthorityForSize = ImGuiDataAuthority_Window;
16466 if (node->AuthorityForViewport == ImGuiDataAuthority_Auto)
16467 node->AuthorityForViewport = ImGuiDataAuthority_Window;
16468 }
16469
16470 // Add to tab bar if requested
16471 if (add_to_tab_bar)
16472 {
16473 if (node->TabBar == NULL)
16474 {
16475 DockNodeAddTabBar(node);
16476 node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId;
16477
16478 // Add existing windows
16479 for (int n = 0; n < node->Windows.Size - 1; n++)
16480 TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
16481 }
16482 TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window);
16483 }
16484
16485 DockNodeUpdateVisibleFlag(node);
16486
16487 // Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame.
16488 if (node->HostWindow)
16489 UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow);
16490}
16491
16492static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id)
16493{
16494 ImGuiContext& g = *GImGui;
16495 IM_ASSERT(window->DockNode == node);
16496 //IM_ASSERT(window->RootWindowDockTree == node->HostWindow);
16497 //IM_ASSERT(window->LastFrameActive < g.FrameCount); // We may call this from Begin()
16498 IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID);
16499 IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name);
16500
16501 window->DockNode = NULL;
16502 window->DockIsActive = window->DockTabWantClose = false;
16503 window->DockId = save_dock_id;
16504 window->Flags &= ~ImGuiWindowFlags_ChildWindow;
16505 if (window->ParentWindow)
16506 window->ParentWindow->DC.ChildWindows.find_erase(window);
16507 UpdateWindowParentAndRootLinks(window, window->Flags, NULL); // Update immediately
16508
16509 if (node->HostWindow && node->HostWindow->ViewportOwned)
16510 {
16511 // When undocking from a user interaction this will always run in NewFrame() and have not much effect.
16512 // But mid-frame, if we clear viewport we need to mark window as hidden as well.
16513 window->Viewport = NULL;
16514 window->ViewportId = 0;
16515 window->ViewportOwned = false;
16516 window->Hidden = true;
16517 }
16518
16519 // Remove window
16520 bool erased = false;
16521 for (int n = 0; n < node->Windows.Size; n++)
16522 if (node->Windows[n] == window)
16523 {
16524 node->Windows.erase(node->Windows.Data + n);
16525 erased = true;
16526 break;
16527 }
16528 if (!erased)
16529 IM_ASSERT(erased);
16530 if (node->VisibleWindow == window)
16531 node->VisibleWindow = NULL;
16532
16533 // Remove tab and possibly tab bar
16534 node->WantHiddenTabBarUpdate = true;
16535 if (node->TabBar)
16536 {
16537 TabBarRemoveTab(node->TabBar, window->TabId);
16538 const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2;
16539 if (node->Windows.Size < tab_count_threshold_for_tab_bar)
16540 DockNodeRemoveTabBar(node);
16541 }
16542
16543 if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID)
16544 {
16545 // Automatic dock node delete themselves if they are not holding at least one tab
16546 DockContextRemoveNode(&g, node, true);
16547 return;
16548 }
16549
16550 if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow)
16551 {
16552 ImGuiWindow* remaining_window = node->Windows[0];
16553 // Note: we used to transport viewport ownership here.
16554 remaining_window->Collapsed = node->HostWindow->Collapsed;
16555 }
16556
16557 // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree
16558 DockNodeUpdateVisibleFlag(node);
16559}
16560
16561static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
16562{
16563 IM_ASSERT(dst_node->Windows.Size == 0);
16564 dst_node->ChildNodes[0] = src_node->ChildNodes[0];
16565 dst_node->ChildNodes[1] = src_node->ChildNodes[1];
16566 if (dst_node->ChildNodes[0])
16567 dst_node->ChildNodes[0]->ParentNode = dst_node;
16568 if (dst_node->ChildNodes[1])
16569 dst_node->ChildNodes[1]->ParentNode = dst_node;
16570 dst_node->SplitAxis = src_node->SplitAxis;
16571 dst_node->SizeRef = src_node->SizeRef;
16572 src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL;
16573}
16574
16575static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
16576{
16577 // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered)
16578 IM_ASSERT(src_node && dst_node && dst_node != src_node);
16579 ImGuiTabBar* src_tab_bar = src_node->TabBar;
16580 if (src_tab_bar != NULL)
16581 IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size);
16582
16583 // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.)
16584 bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL);
16585 if (move_tab_bar)
16586 {
16587 dst_node->TabBar = src_node->TabBar;
16588 src_node->TabBar = NULL;
16589 }
16590
16591 // Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar().
16592 for (ImGuiWindow* window : src_node->Windows)
16593 {
16594 window->DockNode = NULL;
16595 window->DockIsActive = false;
16596 DockNodeAddWindow(dst_node, window, !move_tab_bar);
16597 }
16598 src_node->Windows.clear();
16599
16600 if (!move_tab_bar && src_node->TabBar)
16601 {
16602 if (dst_node->TabBar)
16603 dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId;
16604 DockNodeRemoveTabBar(src_node);
16605 }
16606}
16607
16608static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node)
16609{
16610 for (ImGuiWindow* window : node->Windows)
16611 {
16612 SetWindowPos(window, node->Pos, ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame
16613 SetWindowSize(window, node->Size, ImGuiCond_Always);
16614 }
16615}
16616
16617static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node)
16618{
16619 if (node->HostWindow)
16620 {
16621 if (node->HostWindow->DockNodeAsHost == node)
16622 node->HostWindow->DockNodeAsHost = NULL;
16623 node->HostWindow = NULL;
16624 }
16625
16626 if (node->Windows.Size == 1)
16627 {
16628 node->VisibleWindow = node->Windows[0];
16629 node->Windows[0]->DockIsActive = false;
16630 }
16631
16632 if (node->TabBar)
16633 DockNodeRemoveTabBar(node);
16634}
16635
16636// Search function called once by root node in DockNodeUpdate()
16638{
16639 ImGuiDockNode* CentralNode;
16640 ImGuiDockNode* FirstNodeWithWindows;
16642 //ImGuiWindowClass WindowClassForMerges;
16643
16644 ImGuiDockNodeTreeInfo() { memset(this, 0, sizeof(*this)); }
16645};
16646
16647static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeTreeInfo* info)
16648{
16649 if (node->Windows.Size > 0)
16650 {
16651 if (info->FirstNodeWithWindows == NULL)
16652 info->FirstNodeWithWindows = node;
16653 info->CountNodesWithWindows++;
16654 }
16655 if (node->IsCentralNode())
16656 {
16657 IM_ASSERT(info->CentralNode == NULL); // Should be only one
16658 IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this.");
16659 info->CentralNode = node;
16660 }
16661 if (info->CountNodesWithWindows > 1 && info->CentralNode != NULL)
16662 return;
16663 if (node->ChildNodes[0])
16664 DockNodeFindInfo(node->ChildNodes[0], info);
16665 if (node->ChildNodes[1])
16666 DockNodeFindInfo(node->ChildNodes[1], info);
16667}
16668
16669static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id)
16670{
16671 IM_ASSERT(id != 0);
16672 for (ImGuiWindow* window : node->Windows)
16673 if (window->ID == id)
16674 return window;
16675 return NULL;
16676}
16677
16678// - Remove inactive windows/nodes.
16679// - Update visibility flag.
16680static void ImGui::DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node)
16681{
16682 ImGuiContext& g = *GImGui;
16683 IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
16684
16685 // Inherit most flags
16686 if (node->ParentNode)
16687 node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
16688
16689 // Recurse into children
16690 // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'.
16691 // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node'
16692 // If 'node->ChildNode[1]' delete itself, then 'node->ChildNode[0]->Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless)
16693 node->HasCentralNodeChild = false;
16694 if (node->ChildNodes[0])
16695 DockNodeUpdateFlagsAndCollapse(node->ChildNodes[0]);
16696 if (node->ChildNodes[1])
16697 DockNodeUpdateFlagsAndCollapse(node->ChildNodes[1]);
16698
16699 // Remove inactive windows, collapse nodes
16700 // Merge node flags overrides stored in windows
16701 node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
16702 for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16703 {
16704 ImGuiWindow* window = node->Windows[window_n];
16705 IM_ASSERT(window->DockNode == node);
16706
16707 bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
16708 bool remove = false;
16709 remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount);
16710 remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument); // Submit all _expected_ closure from last frame
16711 remove |= (window->DockTabWantClose);
16712 if (remove)
16713 {
16714 window->DockTabWantClose = false;
16715 if (node->Windows.Size == 1 && !node->IsCentralNode())
16716 {
16717 DockNodeHideHostWindow(node);
16718 node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
16719 DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return
16720 return;
16721 }
16722 DockNodeRemoveWindow(node, window, node->ID);
16723 window_n--;
16724 continue;
16725 }
16726
16727 // FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this.
16728 //node->LocalFlagsInWindow &= ~window->WindowClass.DockNodeFlagsOverrideClear;
16729 node->LocalFlagsInWindows |= window->WindowClass.DockNodeFlagsOverrideSet;
16730 }
16731 node->UpdateMergedFlags();
16732
16733 // Auto-hide tab bar option
16734 ImGuiDockNodeFlags node_flags = node->MergedFlags;
16735 if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar())
16736 node->WantHiddenTabBarToggle = true;
16737 node->WantHiddenTabBarUpdate = false;
16738
16739 // Cancel toggling if we know our tab bar is enforced to be hidden at all times
16740 if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar))
16741 node->WantHiddenTabBarToggle = false;
16742
16743 // Apply toggles at a single point of the frame (here!)
16744 if (node->Windows.Size > 1)
16745 node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
16746 else if (node->WantHiddenTabBarToggle)
16747 node->SetLocalFlags(node->LocalFlags ^ ImGuiDockNodeFlags_HiddenTabBar);
16748 node->WantHiddenTabBarToggle = false;
16749
16750 DockNodeUpdateVisibleFlag(node);
16751}
16752
16753// This is rarely called as DockNodeUpdateForRootNode() generally does it most frames.
16754static void ImGui::DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node)
16755{
16756 node->HasCentralNodeChild = false;
16757 if (node->ChildNodes[0])
16758 DockNodeUpdateHasCentralNodeChild(node->ChildNodes[0]);
16759 if (node->ChildNodes[1])
16760 DockNodeUpdateHasCentralNodeChild(node->ChildNodes[1]);
16761 if (node->IsRootNode())
16762 {
16763 ImGuiDockNode* mark_node = node->CentralNode;
16764 while (mark_node)
16765 {
16766 mark_node->HasCentralNodeChild = true;
16767 mark_node = mark_node->ParentNode;
16768 }
16769 }
16770}
16771
16772static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node)
16773{
16774 // Update visibility flag
16775 bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode();
16776 is_visible |= (node->Windows.Size > 0);
16777 is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible);
16778 is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible);
16779 node->IsVisible = is_visible;
16780}
16781
16782static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window)
16783{
16784 ImGuiContext& g = *GImGui;
16785 IM_ASSERT(node->WantMouseMove == true);
16786 StartMouseMovingWindow(window);
16787 g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos;
16788 g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision.
16789 node->WantMouseMove = false;
16790}
16791
16792// Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class.
16793static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode* node)
16794{
16795 DockNodeUpdateFlagsAndCollapse(node);
16796
16797 // - Setup central node pointers
16798 // - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!)
16799 // Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing
16801 DockNodeFindInfo(node, &info);
16802 node->CentralNode = info.CentralNode;
16803 node->OnlyNodeWithWindows = (info.CountNodesWithWindows == 1) ? info.FirstNodeWithWindows : NULL;
16804 node->CountNodeWithWindows = info.CountNodesWithWindows;
16805 if (node->LastFocusedNodeId == 0 && info.FirstNodeWithWindows != NULL)
16806 node->LastFocusedNodeId = info.FirstNodeWithWindows->ID;
16807
16808 // Copy the window class from of our first window so it can be used for proper dock filtering.
16809 // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy.
16810 // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec.
16811 if (ImGuiDockNode* first_node_with_windows = info.FirstNodeWithWindows)
16812 {
16813 node->WindowClass = first_node_with_windows->Windows[0]->WindowClass;
16814 for (int n = 1; n < first_node_with_windows->Windows.Size; n++)
16815 if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false)
16816 {
16817 node->WindowClass = first_node_with_windows->Windows[n]->WindowClass;
16818 break;
16819 }
16820 }
16821
16822 ImGuiDockNode* mark_node = node->CentralNode;
16823 while (mark_node)
16824 {
16825 mark_node->HasCentralNodeChild = true;
16826 mark_node = mark_node->ParentNode;
16827 }
16828}
16829
16830static void DockNodeSetupHostWindow(ImGuiDockNode* node, ImGuiWindow* host_window)
16831{
16832 // Remove ourselves from any previous different host window
16833 // This can happen if a user mistakenly does (see #4295 for details):
16834 // - N+0: DockBuilderAddNode(id, 0) // missing ImGuiDockNodeFlags_DockSpace
16835 // - N+1: NewFrame() // will create floating host window for that node
16836 // - N+1: DockSpace(id) // requalify node as dockspace, moving host window
16837 if (node->HostWindow && node->HostWindow != host_window && node->HostWindow->DockNodeAsHost == node)
16838 node->HostWindow->DockNodeAsHost = NULL;
16839
16840 host_window->DockNodeAsHost = node;
16841 node->HostWindow = host_window;
16842}
16843
16844static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
16845{
16846 ImGuiContext& g = *GImGui;
16847 IM_ASSERT(node->LastFrameActive != g.FrameCount);
16848 node->LastFrameAlive = g.FrameCount;
16849 node->IsBgDrawnThisFrame = false;
16850
16851 node->CentralNode = node->OnlyNodeWithWindows = NULL;
16852 if (node->IsRootNode())
16853 DockNodeUpdateForRootNode(node);
16854
16855 // Remove tab bar if not needed
16856 if (node->TabBar && node->IsNoTabBar())
16857 DockNodeRemoveTabBar(node);
16858
16859 // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId)
16860 bool want_to_hide_host_window = false;
16861 if (node->IsFloatingNode())
16862 {
16863 if (node->Windows.Size <= 1 && node->IsLeafNode())
16864 if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar))
16865 want_to_hide_host_window = true;
16866 if (node->CountNodeWithWindows == 0)
16867 want_to_hide_host_window = true;
16868 }
16869 if (want_to_hide_host_window)
16870 {
16871 if (node->Windows.Size == 1)
16872 {
16873 // Floating window pos/size is authoritative
16874 ImGuiWindow* single_window = node->Windows[0];
16875 node->Pos = single_window->Pos;
16876 node->Size = single_window->SizeFull;
16877 node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
16878
16879 // Transfer focus immediately so when we revert to a regular window it is immediately selected
16880 if (node->HostWindow && g.NavWindow == node->HostWindow)
16881 FocusWindow(single_window);
16882 if (node->HostWindow)
16883 {
16884 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Node %08X transfer Viewport %08X->%08X to Window '%s'\n", node->ID, node->HostWindow->Viewport->ID, single_window->ID, single_window->Name);
16885 single_window->Viewport = node->HostWindow->Viewport;
16886 single_window->ViewportId = node->HostWindow->ViewportId;
16887 if (node->HostWindow->ViewportOwned)
16888 {
16889 single_window->Viewport->ID = single_window->ID;
16890 single_window->Viewport->Window = single_window;
16891 single_window->ViewportOwned = true;
16892 }
16893 }
16894 node->RefViewportId = single_window->ViewportId;
16895 }
16896
16897 DockNodeHideHostWindow(node);
16898 node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
16899 node->WantCloseAll = false;
16900 node->WantCloseTabId = 0;
16901 node->HasCloseButton = node->HasWindowMenuButton = false;
16902 node->LastFrameActive = g.FrameCount;
16903
16904 if (node->WantMouseMove && node->Windows.Size == 1)
16905 DockNodeStartMouseMovingWindow(node, node->Windows[0]);
16906 return;
16907 }
16908
16909 // In some circumstance we will defer creating the host window (so everything will be kept hidden),
16910 // while the expected visible window is resizing itself.
16911 // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled,
16912 // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up:
16913 // N+0: Begin(): window created (with no known size), node is created
16914 // N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible
16915 // N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible
16916 // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code.
16917 // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin().
16918 // In reality it isn't very important as user quickly ends up with size data in .ini file.
16919 if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode())
16920 {
16921 IM_ASSERT(node->Windows.Size > 0);
16922 ImGuiWindow* ref_window = NULL;
16923 if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them!
16924 ref_window = DockNodeFindWindowByID(node, node->SelectedTabId);
16925 if (ref_window == NULL)
16926 ref_window = node->Windows[0];
16927 if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0)
16928 {
16929 node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing;
16930 return;
16931 }
16932 }
16933
16934 const ImGuiDockNodeFlags node_flags = node->MergedFlags;
16935
16936 // Decide if the node will have a close button and a window menu button
16937 node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
16938 node->HasCloseButton = false;
16939 for (ImGuiWindow* window : node->Windows)
16940 {
16941 // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call.
16942 node->HasCloseButton |= window->HasCloseButton;
16943 window->DockIsActive = (node->Windows.Size > 1);
16944 }
16945 if (node_flags & ImGuiDockNodeFlags_NoCloseButton)
16946 node->HasCloseButton = false;
16947
16948 // Bind or create host window
16949 ImGuiWindow* host_window = NULL;
16950 bool beginned_into_host_window = false;
16951 if (node->IsDockSpace())
16952 {
16953 // [Explicit root dockspace node]
16954 IM_ASSERT(node->HostWindow);
16955 host_window = node->HostWindow;
16956 }
16957 else
16958 {
16959 // [Automatic root or child nodes]
16960 if (node->IsRootNode() && node->IsVisible)
16961 {
16962 ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
16963
16964 // Sync Pos
16965 if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window)
16966 SetNextWindowPos(ref_window->Pos);
16967 else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode)
16968 SetNextWindowPos(node->Pos);
16969
16970 // Sync Size
16971 if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
16972 SetNextWindowSize(ref_window->SizeFull);
16973 else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode)
16974 SetNextWindowSize(node->Size);
16975
16976 // Sync Collapsed
16977 if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
16978 SetNextWindowCollapsed(ref_window->Collapsed);
16979
16980 // Sync Viewport
16981 if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window)
16982 SetNextWindowViewport(ref_window->ViewportId);
16983 else if (node->AuthorityForViewport == ImGuiDataAuthority_Window && node->RefViewportId != 0)
16984 SetNextWindowViewport(node->RefViewportId);
16985
16986 SetNextWindowClass(&node->WindowClass);
16987
16988 // Begin into the host window
16989 char window_label[20];
16990 DockNodeGetHostWindowTitle(node, window_label, IM_ARRAYSIZE(window_label));
16991 ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost;
16992 window_flags |= ImGuiWindowFlags_NoFocusOnAppearing;
16993 window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse;
16994 window_flags |= ImGuiWindowFlags_NoTitleBar;
16995
16996 SetNextWindowBgAlpha(0.0f); // Don't set ImGuiWindowFlags_NoBackground because it disables borders
16997 PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
16998 Begin(window_label, NULL, window_flags);
16999 PopStyleVar();
17000 beginned_into_host_window = true;
17001
17002 host_window = g.CurrentWindow;
17003 DockNodeSetupHostWindow(node, host_window);
17004 host_window->DC.CursorPos = host_window->Pos;
17005 node->Pos = host_window->Pos;
17006 node->Size = host_window->Size;
17007
17008 // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow)
17009 // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags.
17010 // One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again.
17011 // When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window
17012 // during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back
17013 // after the dock host window, losing their top-most status.
17014 if (node->HostWindow->Appearing)
17015 BringWindowToDisplayFront(node->HostWindow);
17016
17017 node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
17018 }
17019 else if (node->ParentNode)
17020 {
17021 node->HostWindow = host_window = node->ParentNode->HostWindow;
17022 node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
17023 }
17024 if (node->WantMouseMove && node->HostWindow)
17025 DockNodeStartMouseMovingWindow(node, node->HostWindow);
17026 }
17027 node->RefViewportId = 0; // Clear when we have a host window
17028
17029 // Update focused node (the one whose title bar is highlight) within a node tree
17030 if (node->IsSplitNode())
17031 IM_ASSERT(node->TabBar == NULL);
17032 if (node->IsRootNode())
17033 if (ImGuiWindow* p_window = g.NavWindow ? g.NavWindow->RootWindow : NULL)
17034 while (p_window != NULL && p_window->DockNode != NULL)
17035 {
17036 ImGuiDockNode* p_node = DockNodeGetRootNode(p_window->DockNode);
17037 if (p_node == node)
17038 {
17039 node->LastFocusedNodeId = p_window->DockNode->ID; // Note: not using root node ID!
17040 break;
17041 }
17042 p_window = p_node->HostWindow ? p_node->HostWindow->RootWindow : NULL;
17043 }
17044
17045 // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace
17046 ImGuiDockNode* central_node = node->CentralNode;
17047 const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty();
17048 bool central_node_hole_register_hit_test_hole = central_node_hole;
17049 if (central_node_hole)
17050 if (const ImGuiPayload* payload = ImGui::GetDragDropPayload())
17051 if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow**)payload->Data))
17052 central_node_hole_register_hit_test_hole = false;
17053 if (central_node_hole_register_hit_test_hole)
17054 {
17055 // We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily.
17056 // (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen
17057 // covering passthru node we'd have a gap on the edge not covered by the hole)
17058 IM_ASSERT(node->IsDockSpace()); // We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window->ParentNode
17059 ImGuiDockNode* root_node = DockNodeGetRootNode(central_node);
17060 ImRect root_rect(root_node->Pos, root_node->Pos + root_node->Size);
17061 ImRect hole_rect(central_node->Pos, central_node->Pos + central_node->Size);
17062 if (hole_rect.Min.x > root_rect.Min.x) { hole_rect.Min.x += WINDOWS_HOVER_PADDING; }
17063 if (hole_rect.Max.x < root_rect.Max.x) { hole_rect.Max.x -= WINDOWS_HOVER_PADDING; }
17064 if (hole_rect.Min.y > root_rect.Min.y) { hole_rect.Min.y += WINDOWS_HOVER_PADDING; }
17065 if (hole_rect.Max.y < root_rect.Max.y) { hole_rect.Max.y -= WINDOWS_HOVER_PADDING; }
17066 //GetForegroundDrawList()->AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255));
17067 if (central_node_hole && !hole_rect.IsInverted())
17068 {
17069 SetWindowHitTestHole(host_window, hole_rect.Min, hole_rect.Max - hole_rect.Min);
17070 if (host_window->ParentWindow)
17071 SetWindowHitTestHole(host_window->ParentWindow, hole_rect.Min, hole_rect.Max - hole_rect.Min);
17072 }
17073 }
17074
17075 // Update position/size, process and draw resizing splitters
17076 if (node->IsRootNode() && host_window)
17077 {
17078 DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size);
17079 PushStyleColor(ImGuiCol_Separator, g.Style.Colors[ImGuiCol_Border]);
17080 PushStyleColor(ImGuiCol_SeparatorActive, g.Style.Colors[ImGuiCol_ResizeGripActive]);
17081 PushStyleColor(ImGuiCol_SeparatorHovered, g.Style.Colors[ImGuiCol_ResizeGripHovered]);
17082 DockNodeTreeUpdateSplitter(node);
17083 PopStyleColor(3);
17084 }
17085
17086 // Draw empty node background (currently can only be the Central Node)
17087 if (host_window && node->IsEmpty() && node->IsVisible)
17088 {
17089 host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
17090 node->LastBgColor = (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) ? 0 : GetColorU32(ImGuiCol_DockingEmptyBg);
17091 if (node->LastBgColor != 0)
17092 host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, node->LastBgColor);
17093 node->IsBgDrawnThisFrame = true;
17094 }
17095
17096 // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set.
17097 // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size
17098 // _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order!
17099 const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0;
17100 if (render_dockspace_bg && node->IsVisible)
17101 {
17102 host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
17103 if (central_node_hole)
17104 RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f);
17105 else
17106 host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f);
17107 }
17108
17109 // Draw and populate Tab Bar
17110 if (host_window)
17111 host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
17112 if (host_window && node->Windows.Size > 0)
17113 {
17114 DockNodeUpdateTabBar(node, host_window);
17115 }
17116 else
17117 {
17118 node->WantCloseAll = false;
17119 node->WantCloseTabId = 0;
17120 node->IsFocused = false;
17121 }
17122 if (node->TabBar && node->TabBar->SelectedTabId)
17123 node->SelectedTabId = node->TabBar->SelectedTabId;
17124 else if (node->Windows.Size > 0)
17125 node->SelectedTabId = node->Windows[0]->TabId;
17126
17127 // Draw payload drop target
17128 if (host_window && node->IsVisible)
17129 if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != host_window))
17130 BeginDockableDragDropTarget(host_window);
17131
17132 // We update this after DockNodeUpdateTabBar()
17133 node->LastFrameActive = g.FrameCount;
17134
17135 // Recurse into children
17136 // FIXME-DOCK FIXME-OPT: Should not need to recurse into children
17137 if (host_window)
17138 {
17139 if (node->ChildNodes[0])
17140 DockNodeUpdate(node->ChildNodes[0]);
17141 if (node->ChildNodes[1])
17142 DockNodeUpdate(node->ChildNodes[1]);
17143
17144 // Render outer borders last (after the tab bar)
17145 if (node->IsRootNode())
17146 RenderWindowOuterBorders(host_window);
17147 }
17148
17149 // End host window
17150 if (beginned_into_host_window) //-V1020
17151 End();
17152}
17153
17154// Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame.
17155static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs)
17156{
17157 ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window;
17158 ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window;
17159 if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder))
17160 return d;
17161 return (a->BeginOrderWithinContext - b->BeginOrderWithinContext);
17162}
17163
17164// Default handler for g.DockNodeWindowMenuHandler(): display the list of windows for a given dock-node.
17165// This is exceptionally stored in a function pointer to also user applications to tweak this menu (undocumented)
17166// Custom overrides may want to decorate, group, sort entries.
17167// Please note those are internal structures: if you copy this expect occasional breakage.
17168// (if you don't need to modify the "Tabs.Size == 1" behavior/path it is recommend you call this function in your handler)
17169void ImGui::DockNodeWindowMenuHandler_Default(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar)
17170{
17171 IM_UNUSED(ctx);
17172 if (tab_bar->Tabs.Size == 1)
17173 {
17174 // "Hide tab bar" option. Being one of our rare user-facing string we pull it from a table.
17175 if (MenuItem(LocalizeGetMsg(ImGuiLocKey_DockingHideTabBar), NULL, node->IsHiddenTabBar()))
17176 node->WantHiddenTabBarToggle = true;
17177 }
17178 else
17179 {
17180 // Display a selectable list of windows in this docking node
17181 for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
17182 {
17183 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
17184 if (tab->Flags & ImGuiTabItemFlags_Button)
17185 continue;
17186 if (Selectable(TabBarGetTabName(tab_bar, tab), tab->ID == tab_bar->SelectedTabId))
17187 TabBarQueueFocus(tab_bar, tab);
17188 SameLine();
17189 Text(" ");
17190 }
17191 }
17192}
17193
17194static void ImGui::DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar)
17195{
17196 // Try to position the menu so it is more likely to stays within the same viewport
17197 ImGuiContext& g = *GImGui;
17198 if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left)
17199 SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f));
17200 else
17201 SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f));
17202 if (BeginPopup("#WindowMenu"))
17203 {
17204 node->IsFocused = true;
17205 g.DockNodeWindowMenuHandler(&g, node, tab_bar);
17206 EndPopup();
17207 }
17208}
17209
17210// User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button.
17211bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node)
17212{
17213 if (node->TabBar == NULL || node->HostWindow == NULL)
17214 return false;
17215 if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
17216 return false;
17217 if (node->TabBar->ID == 0)
17218 return false;
17219 Begin(node->HostWindow->Name);
17220 PushOverrideID(node->ID);
17221 bool ret = BeginTabBarEx(node->TabBar, node->TabBar->BarRect, node->TabBar->Flags);
17222 IM_UNUSED(ret);
17223 IM_ASSERT(ret);
17224 return true;
17225}
17226
17227void ImGui::DockNodeEndAmendTabBar()
17228{
17229 EndTabBar();
17230 PopID();
17231 End();
17232}
17233
17234static bool IsDockNodeTitleBarHighlighted(ImGuiDockNode* node, ImGuiDockNode* root_node)
17235{
17236 // CTRL+Tab highlight (only highlighting leaf node, not whole hierarchy)
17237 ImGuiContext& g = *GImGui;
17238 if (g.NavWindowingTarget)
17239 return (g.NavWindowingTarget->DockNode == node);
17240
17241 // FIXME-DOCKING: May want alternative to treat central node void differently? e.g. if (g.NavWindow == host_window)
17242 if (g.NavWindow && root_node->LastFocusedNodeId == node->ID)
17243 {
17244 // FIXME: This could all be backed in RootWindowForTitleBarHighlight? Probably need to reorganize for both dock nodes + other RootWindowForTitleBarHighlight users (not-node)
17245 ImGuiWindow* parent_window = g.NavWindow->RootWindow;
17246 while (parent_window->Flags & ImGuiWindowFlags_ChildMenu)
17247 parent_window = parent_window->ParentWindow->RootWindow;
17248 ImGuiDockNode* start_parent_node = parent_window->DockNodeAsHost ? parent_window->DockNodeAsHost : parent_window->DockNode;
17249 for (ImGuiDockNode* parent_node = start_parent_node; parent_node != NULL; parent_node = parent_node->HostWindow ? parent_node->HostWindow->RootWindow->DockNode : NULL)
17250 if ((parent_node = ImGui::DockNodeGetRootNode(parent_node)) == root_node)
17251 return true;
17252 }
17253 return false;
17254}
17255
17256// Submit the tab bar corresponding to a dock node and various housekeeping details.
17257static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window)
17258{
17259 ImGuiContext& g = *GImGui;
17260 ImGuiStyle& style = g.Style;
17261
17262 const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
17263 const bool closed_all = node->WantCloseAll && node_was_active;
17264 const ImGuiID closed_one = node->WantCloseTabId && node_was_active;
17265 node->WantCloseAll = false;
17266 node->WantCloseTabId = 0;
17267
17268 // Decide if we should use a focused title bar color
17269 bool is_focused = false;
17270 ImGuiDockNode* root_node = DockNodeGetRootNode(node);
17271 if (IsDockNodeTitleBarHighlighted(node, root_node))
17272 is_focused = true;
17273
17274 // Hidden tab bar will show a triangle on the upper-left (in Begin)
17275 if (node->IsHiddenTabBar() || node->IsNoTabBar())
17276 {
17277 node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
17278 node->IsFocused = is_focused;
17279 if (is_focused)
17280 node->LastFrameFocused = g.FrameCount;
17281 if (node->VisibleWindow)
17282 {
17283 // Notify root of visible window (used to display title in OS task bar)
17284 if (is_focused || root_node->VisibleWindow == NULL)
17285 root_node->VisibleWindow = node->VisibleWindow;
17286 if (node->TabBar)
17287 node->TabBar->VisibleTabId = node->VisibleWindow->TabId;
17288 }
17289 return;
17290 }
17291
17292 // Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed
17293 bool backup_skip_item = host_window->SkipItems;
17294 if (!node->IsDockSpace())
17295 {
17296 host_window->SkipItems = false;
17297 host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
17298 }
17299
17300 // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID.
17301 // This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs,
17302 // as docked windows themselves will override the stack with their own root ID.
17303 PushOverrideID(node->ID);
17304 ImGuiTabBar* tab_bar = node->TabBar;
17305 bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden
17306 if (tab_bar == NULL)
17307 {
17308 DockNodeAddTabBar(node);
17309 tab_bar = node->TabBar;
17310 }
17311
17312 ImGuiID focus_tab_id = 0;
17313 node->IsFocused = is_focused;
17314
17315 const ImGuiDockNodeFlags node_flags = node->MergedFlags;
17316 const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None);
17317
17318 // In a dock node, the Collapse Button turns into the Window Menu button.
17319 // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes?
17320 if (has_window_menu_button && IsPopupOpen("#WindowMenu"))
17321 {
17322 ImGuiID next_selected_tab_id = tab_bar->NextSelectedTabId;
17323 DockNodeWindowMenuUpdate(node, tab_bar);
17324 if (tab_bar->NextSelectedTabId != 0 && tab_bar->NextSelectedTabId != next_selected_tab_id)
17325 focus_tab_id = tab_bar->NextSelectedTabId;
17326 is_focused |= node->IsFocused;
17327 }
17328
17329 // Layout
17330 ImRect title_bar_rect, tab_bar_rect;
17331 ImVec2 window_menu_button_pos;
17332 ImVec2 close_button_pos;
17333 DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos, &close_button_pos);
17334
17335 // Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value.
17336 const int tabs_count_old = tab_bar->Tabs.Size;
17337 for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17338 {
17339 ImGuiWindow* window = node->Windows[window_n];
17340 if (TabBarFindTabByID(tab_bar, window->TabId) == NULL)
17341 TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window);
17342 }
17343
17344 // Title bar
17345 if (is_focused)
17346 node->LastFrameFocused = g.FrameCount;
17347 ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
17348 ImDrawFlags rounding_flags = CalcRoundingFlagsForRectInRect(title_bar_rect, host_window->Rect(), g.Style.DockingSeparatorSize);
17349 host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, rounding_flags);
17350
17351 // Docking/Collapse button
17352 if (has_window_menu_button)
17353 {
17354 if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node)) // == DockNodeGetWindowMenuButtonId(node)
17355 OpenPopup("#WindowMenu");
17356 if (IsItemActive())
17357 focus_tab_id = tab_bar->SelectedTabId;
17358 if (IsItemHovered(ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal) && g.HoveredIdTimer > 0.5f)
17359 SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingDragToUndockOrMoveNode));
17360 }
17361
17362 // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value
17363 int tabs_unsorted_start = tab_bar->Tabs.Size;
17364 for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--)
17365 {
17366 // FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting?
17367 tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted;
17368 tabs_unsorted_start = tab_n;
17369 }
17370 if (tab_bar->Tabs.Size > tabs_unsorted_start)
17371 {
17372 IMGUI_DEBUG_LOG_DOCKING("[docking] In node 0x%08X: %d new appearing tabs:%s\n", node->ID, tab_bar->Tabs.Size - tabs_unsorted_start, (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ? " (will sort)" : "");
17373 for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++)
17374 {
17375 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
17376 IMGUI_DEBUG_LOG_DOCKING("[docking] - Tab 0x%08X '%s' Order %d\n", tab->ID, TabBarGetTabName(tab_bar, tab), tab->Window ? tab->Window->DockOrder : -1);
17377 }
17378 IMGUI_DEBUG_LOG_DOCKING("[docking] SelectedTabId = 0x%08X, NavWindow->TabId = 0x%08X\n", node->SelectedTabId, g.NavWindow ? g.NavWindow->TabId : -1);
17379 if (tab_bar->Tabs.Size > tabs_unsorted_start + 1)
17380 ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder);
17381 }
17382
17383 // Apply NavWindow focus back to the tab bar
17384 if (g.NavWindow && g.NavWindow->RootWindow->DockNode == node)
17385 tab_bar->SelectedTabId = g.NavWindow->RootWindow->TabId;
17386
17387 // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated
17388 if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabId) != NULL)
17389 tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId;
17390 else if (tab_bar->Tabs.Size > tabs_count_old)
17391 tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->TabId;
17392
17393 // Begin tab bar
17394 ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons);
17395 tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;// | ImGuiTabBarFlags_FittingPolicyScroll;
17396 if (!host_window->Collapsed && is_focused)
17397 tab_bar_flags |= ImGuiTabBarFlags_IsFocused;
17398 tab_bar->ID = GetID("#TabBar");
17399 tab_bar->SeparatorMinX = node->Pos.x + host_window->WindowBorderSize; // Separator cover the whole node width
17400 tab_bar->SeparatorMaxX = node->Pos.x + node->Size.x - host_window->WindowBorderSize;
17401 BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags);
17402 //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255));
17403
17404 // Backup style colors
17405 ImVec4 backup_style_cols[ImGuiWindowDockStyleCol_COUNT];
17406 for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17407 backup_style_cols[color_n] = g.Style.Colors[GWindowDockStyleColors[color_n]];
17408
17409 // Submit actual tabs
17410 node->VisibleWindow = NULL;
17411 for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17412 {
17413 ImGuiWindow* window = node->Windows[window_n];
17414 if ((closed_all || closed_one == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument))
17415 continue;
17416 if (window->LastFrameActive + 1 >= g.FrameCount || !node_was_active)
17417 {
17418 ImGuiTabItemFlags tab_item_flags = 0;
17419 tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet;
17420 if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
17421 tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
17422 if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
17423 tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
17424
17425 // Apply stored style overrides for the window
17426 for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17427 g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(window->DockStyle.Colors[color_n]);
17428
17429 // Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so)
17430 bool tab_open = true;
17431 TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window);
17432 if (!tab_open)
17433 node->WantCloseTabId = window->TabId;
17434 if (tab_bar->VisibleTabId == window->TabId)
17435 node->VisibleWindow = window;
17436
17437 // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
17438 window->DockTabItemStatusFlags = g.LastItemData.StatusFlags;
17439 window->DockTabItemRect = g.LastItemData.Rect;
17440
17441 // Update navigation ID on menu layer
17442 if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0)
17443 host_window->NavLastIds[1] = window->TabId;
17444 }
17445 }
17446
17447 // Restore style colors
17448 for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17449 g.Style.Colors[GWindowDockStyleColors[color_n]] = backup_style_cols[color_n];
17450
17451 // Notify root of visible window (used to display title in OS task bar)
17452 if (node->VisibleWindow)
17453 if (is_focused || root_node->VisibleWindow == NULL)
17454 root_node->VisibleWindow = node->VisibleWindow;
17455
17456 // Close button (after VisibleWindow was updated)
17457 // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->TabId may be != from tab_bar->SelectedTabId
17458 const bool close_button_is_enabled = node->HasCloseButton && node->VisibleWindow && node->VisibleWindow->HasCloseButton;
17459 const bool close_button_is_visible = node->HasCloseButton;
17460 //const bool close_button_is_visible = close_button_is_enabled; // Most people would expect this behavior of not even showing the button (leaving a hole since we can't claim that space as other windows in the tba bar have one)
17461 if (close_button_is_visible)
17462 {
17463 if (!close_button_is_enabled)
17464 {
17465 PushItemFlag(ImGuiItemFlags_Disabled, true);
17466 PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.4f));
17467 }
17468 if (CloseButton(host_window->GetID("#CLOSE"), close_button_pos))
17469 {
17470 node->WantCloseAll = true;
17471 for (int n = 0; n < tab_bar->Tabs.Size; n++)
17472 TabBarCloseTab(tab_bar, &tab_bar->Tabs[n]);
17473 }
17474 //if (IsItemActive())
17475 // focus_tab_id = tab_bar->SelectedTabId;
17476 if (!close_button_is_enabled)
17477 {
17478 PopStyleColor();
17479 PopItemFlag();
17480 }
17481 }
17482
17483 // When clicking on the title bar outside of tabs, we still focus the selected tab for that node
17484 // FIXME: TabItems submitted earlier use AllowItemOverlap so we manually perform a more specific test for now (hovered || held) in order to not cover them.
17485 ImGuiID title_bar_id = host_window->GetID("#TITLEBAR");
17486 if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id)
17487 {
17488 // AllowOverlap mode required for appending into dock node tab bar,
17489 // otherwise dragging window will steal HoveredId and amended tabs cannot get them.
17490 bool held;
17491 KeepAliveID(title_bar_id);
17492 ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held, ImGuiButtonFlags_AllowOverlap);
17493 if (g.HoveredId == title_bar_id)
17494 {
17495 g.LastItemData.ID = title_bar_id;
17496 }
17497 if (held)
17498 {
17499 if (IsMouseClicked(0))
17500 focus_tab_id = tab_bar->SelectedTabId;
17501
17502 // Forward moving request to selected window
17503 if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
17504 StartMouseMovingWindowOrNode(tab->Window ? tab->Window : node->HostWindow, node, false); // Undock from tab bar empty space
17505 }
17506 }
17507
17508 // Forward focus from host node to selected window
17509 //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget)
17510 // focus_tab_id = tab_bar->SelectedTabId;
17511
17512 // When clicked on a tab we requested focus to the docked child
17513 // This overrides the value set by "forward focus from host node to selected window".
17514 if (tab_bar->NextSelectedTabId)
17515 focus_tab_id = tab_bar->NextSelectedTabId;
17516
17517 // Apply navigation focus
17518 if (focus_tab_id != 0)
17519 if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id))
17520 if (tab->Window)
17521 {
17522 FocusWindow(tab->Window);
17523 NavInitWindow(tab->Window, false);
17524 }
17525
17526 EndTabBar();
17527 PopID();
17528
17529 // Restore SkipItems flag
17530 if (!node->IsDockSpace())
17531 {
17532 host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
17533 host_window->SkipItems = backup_skip_item;
17534 }
17535}
17536
17537static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node)
17538{
17539 IM_ASSERT(node->TabBar == NULL);
17540 node->TabBar = IM_NEW(ImGuiTabBar);
17541}
17542
17543static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node)
17544{
17545 if (node->TabBar == NULL)
17546 return;
17547 IM_DELETE(node->TabBar);
17548 node->TabBar = NULL;
17549}
17550
17551static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window)
17552{
17553 if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext)
17554 return false;
17555
17556 ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass;
17557 ImGuiWindowClass* payload_class = &payload->WindowClass;
17558 if (host_class->ClassId != payload_class->ClassId)
17559 {
17560 bool pass = false;
17561 if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0)
17562 pass = true;
17563 if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0)
17564 pass = true;
17565 if (!pass)
17566 return false;
17567 }
17568
17569 // Prevent docking any window created above a popup
17570 // Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features),
17571 // by e.g. adding a 'if (!ImGui::IsWindowWithinBeginStackOf(host_window, popup_window))' test.
17572 // But it would requires more work on our end because the dock host windows is technically created in NewFrame()
17573 // and our ->ParentXXX and ->RootXXX pointers inside windows are currently mislading or lacking.
17574 ImGuiContext& g = *GImGui;
17575 for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
17576 if (ImGuiWindow* popup_window = g.OpenPopupStack[i].Window)
17577 if (ImGui::IsWindowWithinBeginStackOf(payload, popup_window)) // Payload is created from within a popup begin stack.
17578 return false;
17579
17580 return true;
17581}
17582
17583static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload)
17584{
17585 if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode()) // FIXME-DOCK: Missing filtering
17586 return true;
17587
17588 const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1;
17589 for (int payload_n = 0; payload_n < payload_count; payload_n++)
17590 {
17591 ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload;
17592 if (DockNodeIsDropAllowedOne(payload, host_window))
17593 return true;
17594 }
17595 return false;
17596}
17597
17598// window menu button == collapse button when not in a dock node.
17599// FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code.
17600static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos)
17601{
17602 ImGuiContext& g = *GImGui;
17603 ImGuiStyle& style = g.Style;
17604
17605 ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + g.FontSize + g.Style.FramePadding.y * 2.0f);
17606 if (out_title_rect) { *out_title_rect = r; }
17607
17608 r.Min.x += style.WindowBorderSize;
17609 r.Max.x -= style.WindowBorderSize;
17610
17611 float button_sz = g.FontSize;
17612 r.Min.x += style.FramePadding.x;
17613 r.Max.x -= style.FramePadding.x;
17614 ImVec2 window_menu_button_pos = ImVec2(r.Min.x, r.Min.y + style.FramePadding.y);
17615 if (node->HasCloseButton)
17616 {
17617 if (out_close_button_pos) *out_close_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
17618 r.Max.x -= button_sz + style.ItemInnerSpacing.x;
17619 }
17620 if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Left)
17621 {
17622 r.Min.x += button_sz + style.ItemInnerSpacing.x;
17623 }
17624 else if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Right)
17625 {
17626 window_menu_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
17627 r.Max.x -= button_sz + style.ItemInnerSpacing.x;
17628 }
17629 if (out_tab_bar_rect) { *out_tab_bar_rect = r; }
17630 if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; }
17631}
17632
17633void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired)
17634{
17635 ImGuiContext& g = *GImGui;
17636 const float dock_spacing = g.Style.ItemInnerSpacing.x;
17637 const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
17638 pos_new[axis ^ 1] = pos_old[axis ^ 1];
17639 size_new[axis ^ 1] = size_old[axis ^ 1];
17640
17641 // Distribute size on given axis (with a desired size or equally)
17642 const float w_avail = size_old[axis] - dock_spacing;
17643 if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f)
17644 {
17645 size_new[axis] = size_new_desired[axis];
17646 size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
17647 }
17648 else
17649 {
17650 size_new[axis] = IM_TRUNC(w_avail * 0.5f);
17651 size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
17652 }
17653
17654 // Position each node
17655 if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
17656 {
17657 pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing;
17658 }
17659 else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up)
17660 {
17661 pos_new[axis] = pos_old[axis];
17662 pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing;
17663 }
17664}
17665
17666// Retrieve the drop rectangles for a given direction or for the center + perform hit testing.
17667bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos)
17668{
17669 ImGuiContext& g = *GImGui;
17670
17671 const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight());
17672 const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f));
17673 float hs_w; // Half-size, longer axis
17674 float hs_h; // Half-size, smaller axis
17675 ImVec2 off; // Distance from edge or center
17676 if (outer_docking)
17677 {
17678 //hs_w = ImTrunc(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f));
17679 //hs_h = ImTrunc(hs_w * 0.15f);
17680 //off = ImVec2(ImTrunc(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImTrunc(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h));
17681 hs_w = ImTrunc(hs_for_central_nodes * 1.50f);
17682 hs_h = ImTrunc(hs_for_central_nodes * 0.80f);
17683 off = ImTrunc(ImVec2(parent.GetWidth() * 0.5f - hs_h, parent.GetHeight() * 0.5f - hs_h));
17684 }
17685 else
17686 {
17687 hs_w = ImTrunc(hs_for_central_nodes);
17688 hs_h = ImTrunc(hs_for_central_nodes * 0.90f);
17689 off = ImTrunc(ImVec2(hs_w * 2.40f, hs_w * 2.40f));
17690 }
17691
17692 ImVec2 c = ImTrunc(parent.GetCenter());
17693 if (dir == ImGuiDir_None) { out_r = ImRect(c.x - hs_w, c.y - hs_w, c.x + hs_w, c.y + hs_w); }
17694 else if (dir == ImGuiDir_Up) { out_r = ImRect(c.x - hs_w, c.y - off.y - hs_h, c.x + hs_w, c.y - off.y + hs_h); }
17695 else if (dir == ImGuiDir_Down) { out_r = ImRect(c.x - hs_w, c.y + off.y - hs_h, c.x + hs_w, c.y + off.y + hs_h); }
17696 else if (dir == ImGuiDir_Left) { out_r = ImRect(c.x - off.x - hs_h, c.y - hs_w, c.x - off.x + hs_h, c.y + hs_w); }
17697 else if (dir == ImGuiDir_Right) { out_r = ImRect(c.x + off.x - hs_h, c.y - hs_w, c.x + off.x + hs_h, c.y + hs_w); }
17698
17699 if (test_mouse_pos == NULL)
17700 return false;
17701
17702 ImRect hit_r = out_r;
17703 if (!outer_docking)
17704 {
17705 // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides
17706 hit_r.Expand(ImTrunc(hs_w * 0.30f));
17707 ImVec2 mouse_delta = (*test_mouse_pos - c);
17708 float mouse_delta_len2 = ImLengthSqr(mouse_delta);
17709 float r_threshold_center = hs_w * 1.4f;
17710 float r_threshold_sides = hs_w * (1.4f + 1.2f);
17711 if (mouse_delta_len2 < r_threshold_center * r_threshold_center)
17712 return (dir == ImGuiDir_None);
17713 if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides)
17714 return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y));
17715 }
17716 return hit_r.Contains(*test_mouse_pos);
17717}
17718
17719// host_node may be NULL if the window doesn't have a DockNode already.
17720// FIXME-DOCK: This is misnamed since it's also doing the filtering.
17721static void ImGui::DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking)
17722{
17723 ImGuiContext& g = *GImGui;
17724
17725 // There is an edge case when docking into a dockspace which only has inactive nodes.
17726 // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive.
17727 // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference.
17728 if (payload_node == NULL)
17729 payload_node = payload_window->DockNodeAsHost;
17730 ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node;
17731 if (ref_node_for_rect)
17732 IM_ASSERT(ref_node_for_rect->IsVisible == true);
17733
17734 // Filter, figure out where we are allowed to dock
17735 ImGuiDockNodeFlags src_node_flags = payload_node ? payload_node->MergedFlags : payload_window->WindowClass.DockNodeFlagsOverrideSet;
17736 ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->MergedFlags : host_window->WindowClass.DockNodeFlagsOverrideSet;
17737 data->IsCenterAvailable = true;
17738 if (is_outer_docking)
17739 data->IsCenterAvailable = false;
17740 else if (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe)
17741 data->IsCenterAvailable = false;
17742 else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverCentralNode) && host_node->IsCentralNode())
17743 data->IsCenterAvailable = false;
17744 else if ((!host_node || !host_node->IsEmpty()) && payload_node && payload_node->IsSplitNode() && (payload_node->OnlyNodeWithWindows == NULL)) // Is _visibly_ split?
17745 data->IsCenterAvailable = false;
17746 else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther) && (!host_node || !host_node->IsEmpty()))
17747 data->IsCenterAvailable = false;
17748 else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverEmpty) && host_node && host_node->IsEmpty())
17749 data->IsCenterAvailable = false;
17750
17751 data->IsSidesAvailable = true;
17752 if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplit) || g.IO.ConfigDockingNoSplit)
17753 data->IsSidesAvailable = false;
17754 else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode())
17755 data->IsSidesAvailable = false;
17756 else if (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther)
17757 data->IsSidesAvailable = false;
17758
17759 // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split)
17760 data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (payload_window->HasCloseButton);
17761 data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0);
17762 data->FutureNode.Pos = ref_node_for_rect ? ref_node_for_rect->Pos : host_window->Pos;
17763 data->FutureNode.Size = ref_node_for_rect ? ref_node_for_rect->Size : host_window->Size;
17764
17765 // Calculate drop shapes geometry for allowed splitting directions
17766 IM_ASSERT(ImGuiDir_None == -1);
17767 data->SplitNode = host_node;
17768 data->SplitDir = ImGuiDir_None;
17769 data->IsSplitDirExplicit = false;
17770 if (!host_window->Collapsed)
17771 for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
17772 {
17773 if (dir == ImGuiDir_None && !data->IsCenterAvailable)
17774 continue;
17775 if (dir != ImGuiDir_None && !data->IsSidesAvailable)
17776 continue;
17777 if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking, &g.IO.MousePos))
17778 {
17779 data->SplitDir = (ImGuiDir)dir;
17780 data->IsSplitDirExplicit = true;
17781 }
17782 }
17783
17784 // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar
17785 data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable);
17786 if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift)
17787 data->IsDropAllowed = false;
17788
17789 // Calculate split area
17790 data->SplitRatio = 0.0f;
17791 if (data->SplitDir != ImGuiDir_None)
17792 {
17793 ImGuiDir split_dir = data->SplitDir;
17794 ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
17795 ImVec2 pos_new, pos_old = data->FutureNode.Pos;
17796 ImVec2 size_new, size_old = data->FutureNode.Size;
17797 DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, payload_window->Size);
17798
17799 // Calculate split ratio so we can pass it down the docking request
17800 float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]);
17801 data->FutureNode.Pos = pos_new;
17802 data->FutureNode.Size = size_new;
17803 data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio);
17804 }
17805}
17806
17807static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data)
17808{
17809 ImGuiContext& g = *GImGui;
17810 IM_ASSERT(g.CurrentWindow == host_window); // Because we rely on font size to calculate tab sizes
17811
17812 // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent.
17813 // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes.
17814 const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload;
17815
17816 // In case the two windows involved are on different viewports, we will draw the overlay on each of them.
17817 int overlay_draw_lists_count = 0;
17818 ImDrawList* overlay_draw_lists[2];
17819 overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(host_window->Viewport);
17820 if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload)
17821 overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(root_payload->Viewport);
17822
17823 // Draw main preview rectangle
17824 const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f);
17825 const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f);
17826 const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f);
17827 const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f);
17828
17829 // Display area preview
17830 const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0);
17831 if (data->IsDropAllowed)
17832 {
17833 ImRect overlay_rect = data->FutureNode.Rect();
17834 if (data->SplitDir == ImGuiDir_None && can_preview_tabs)
17835 overlay_rect.Min.y += GetFrameHeight();
17836 if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable)
17837 for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17838 overlay_draw_lists[overlay_n]->AddRectFilled(overlay_rect.Min, overlay_rect.Max, overlay_col_main, host_window->WindowRounding, CalcRoundingFlagsForRectInRect(overlay_rect, host_window->Rect(), g.Style.DockingSeparatorSize));
17839 }
17840
17841 // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read)
17842 if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable)
17843 {
17844 // Compute target tab bar geometry so we can locate our preview tabs
17845 ImRect tab_bar_rect;
17846 DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL, NULL);
17847 ImVec2 tab_pos = tab_bar_rect.Min;
17848 if (host_node && host_node->TabBar)
17849 {
17850 if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar())
17851 tab_pos.x += host_node->TabBar->WidthAllTabs + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission.
17852 else
17853 tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]).x;
17854 }
17855 else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost))
17856 {
17857 tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_window).x; // Account for slight offset which will be added when changing from title bar to tab bar
17858 }
17859
17860 // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows)
17861 if (root_payload->DockNodeAsHost)
17862 IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size);
17863 ImGuiTabBar* tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL;
17864 const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1;
17865 for (int payload_n = 0; payload_n < payload_count; payload_n++)
17866 {
17867 // DockNode's TabBar may have non-window Tabs manually appended by user
17868 ImGuiWindow* payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload;
17869 if (tab_bar_with_payload && payload_window == NULL)
17870 continue;
17871 if (!DockNodeIsDropAllowedOne(payload_window, host_window))
17872 continue;
17873
17874 // Calculate the tab bounding box for each payload window
17875 ImVec2 tab_size = TabItemCalcSize(payload_window);
17876 ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y);
17877 tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x;
17878 const ImU32 overlay_col_text = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_Text]);
17879 const ImU32 overlay_col_tabs = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_TabActive]);
17880 PushStyleColor(ImGuiCol_Text, overlay_col_text);
17881 for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17882 {
17883 ImGuiTabItemFlags tab_flags = (payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0;
17884 if (!tab_bar_rect.Contains(tab_bb))
17885 overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max);
17886 TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs);
17887 TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload_window->Name, 0, 0, false, NULL, NULL);
17888 if (!tab_bar_rect.Contains(tab_bb))
17889 overlay_draw_lists[overlay_n]->PopClipRect();
17890 }
17891 PopStyleColor();
17892 }
17893 }
17894
17895 // Display drop boxes
17896 const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding);
17897 for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
17898 {
17899 if (!data->DropRectsDraw[dir + 1].IsInverted())
17900 {
17901 ImRect draw_r = data->DropRectsDraw[dir + 1];
17902 ImRect draw_r_in = draw_r;
17903 draw_r_in.Expand(-2.0f);
17904 ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop;
17905 for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17906 {
17907 ImVec2 center = ImFloor(draw_r_in.GetCenter());
17908 overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding);
17909 overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding);
17910 if (dir == ImGuiDir_Left || dir == ImGuiDir_Right)
17911 overlay_draw_lists[overlay_n]->AddLine(ImVec2(center.x, draw_r_in.Min.y), ImVec2(center.x, draw_r_in.Max.y), overlay_col_lines);
17912 if (dir == ImGuiDir_Up || dir == ImGuiDir_Down)
17913 overlay_draw_lists[overlay_n]->AddLine(ImVec2(draw_r_in.Min.x, center.y), ImVec2(draw_r_in.Max.x, center.y), overlay_col_lines);
17914 }
17915 }
17916
17917 // Stop after ImGuiDir_None
17918 if ((host_node && (host_node->MergedFlags & ImGuiDockNodeFlags_NoDockingSplit)) || g.IO.ConfigDockingNoSplit)
17919 return;
17920 }
17921}
17922
17923//-----------------------------------------------------------------------------
17924// Docking: ImGuiDockNode Tree manipulation functions
17925//-----------------------------------------------------------------------------
17926// - DockNodeTreeSplit()
17927// - DockNodeTreeMerge()
17928// - DockNodeTreeUpdatePosSize()
17929// - DockNodeTreeUpdateSplitterFindTouchingNode()
17930// - DockNodeTreeUpdateSplitter()
17931// - DockNodeTreeFindFallbackLeafNode()
17932// - DockNodeTreeFindNodeByPos()
17933//-----------------------------------------------------------------------------
17934
17935void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node)
17936{
17937 ImGuiContext& g = *GImGui;
17938 IM_ASSERT(split_axis != ImGuiAxis_None);
17939
17940 ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0);
17941 child_0->ParentNode = parent_node;
17942
17943 ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0);
17944 child_1->ParentNode = parent_node;
17945
17946 ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1;
17947 DockNodeMoveChildNodes(child_inheritor, parent_node);
17948 parent_node->ChildNodes[0] = child_0;
17949 parent_node->ChildNodes[1] = child_1;
17950 parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow;
17951 parent_node->SplitAxis = split_axis;
17952 parent_node->VisibleWindow = NULL;
17953 parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode;
17954
17955 float size_avail = (parent_node->Size[split_axis] - g.Style.DockingSeparatorSize);
17956 size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f);
17957 IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting.
17958 child_0->SizeRef = child_1->SizeRef = parent_node->Size;
17959 child_0->SizeRef[split_axis] = ImTrunc(size_avail * split_ratio);
17960 child_1->SizeRef[split_axis] = ImTrunc(size_avail - child_0->SizeRef[split_axis]);
17961
17962 DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node);
17963 DockSettingsRenameNodeReferences(parent_node->ID, parent_node->ChildNodes[split_inheritor_child_idx]->ID);
17964 DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(parent_node));
17965 DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size);
17966
17967 // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property)
17968 child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
17969 child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
17970 child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17971 parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17972 child_0->UpdateMergedFlags();
17973 child_1->UpdateMergedFlags();
17974 parent_node->UpdateMergedFlags();
17975 if (child_inheritor->IsCentralNode())
17976 DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor;
17977}
17978
17979void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child)
17980{
17981 // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL.
17982 ImGuiContext& g = *GImGui;
17983 ImGuiDockNode* child_0 = parent_node->ChildNodes[0];
17984 ImGuiDockNode* child_1 = parent_node->ChildNodes[1];
17985 IM_ASSERT(child_0 || child_1);
17986 IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1);
17987 if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0))
17988 {
17989 IM_ASSERT(parent_node->TabBar == NULL);
17990 IM_ASSERT(parent_node->Windows.Size == 0);
17991 }
17992 IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeTreeMerge: 0x%08X + 0x%08X back into parent 0x%08X\n", child_0 ? child_0->ID : 0, child_1 ? child_1->ID : 0, parent_node->ID);
17993
17994 ImVec2 backup_last_explicit_size = parent_node->SizeRef;
17995 DockNodeMoveChildNodes(parent_node, merge_lead_child);
17996 if (child_0)
17997 {
17998 DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows
17999 DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID);
18000 }
18001 if (child_1)
18002 {
18003 DockNodeMoveWindows(parent_node, child_1);
18004 DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID);
18005 }
18006 DockNodeApplyPosSizeToWindows(parent_node);
18007 parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto;
18008 parent_node->VisibleWindow = merge_lead_child->VisibleWindow;
18009 parent_node->SizeRef = backup_last_explicit_size;
18010
18011 // Flags transfer
18012 parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag
18013 parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18014 parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18015 parent_node->LocalFlagsInWindows = (child_0 ? child_0->LocalFlagsInWindows : 0) | (child_1 ? child_1->LocalFlagsInWindows : 0); // FIXME: Would be more consistent to update from actual windows
18016 parent_node->UpdateMergedFlags();
18017
18018 if (child_0)
18019 {
18020 ctx->DockContext.Nodes.SetVoidPtr(child_0->ID, NULL);
18021 IM_DELETE(child_0);
18022 }
18023 if (child_1)
18024 {
18025 ctx->DockContext.Nodes.SetVoidPtr(child_1->ID, NULL);
18026 IM_DELETE(child_1);
18027 }
18028}
18029
18030// Update Pos/Size for a node hierarchy (don't affect child Windows yet)
18031// (Depth-first, Pre-Order)
18032void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node)
18033{
18034 // During the regular dock node update we write to all nodes.
18035 // 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away.
18036 ImGuiContext& g = *GImGui;
18037 const bool write_to_node = only_write_to_single_node == NULL || only_write_to_single_node == node;
18038 if (write_to_node)
18039 {
18040 node->Pos = pos;
18041 node->Size = size;
18042 }
18043
18044 if (node->IsLeafNode())
18045 return;
18046
18047 ImGuiDockNode* child_0 = node->ChildNodes[0];
18048 ImGuiDockNode* child_1 = node->ChildNodes[1];
18049 ImVec2 child_0_pos = pos, child_1_pos = pos;
18050 ImVec2 child_0_size = size, child_1_size = size;
18051
18052 const bool child_0_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_0));
18053 const bool child_1_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_1));
18054 const bool child_0_is_or_will_be_visible = child_0->IsVisible || child_0_is_toward_single_node;
18055 const bool child_1_is_or_will_be_visible = child_1->IsVisible || child_1_is_toward_single_node;
18056
18057 if (child_0_is_or_will_be_visible && child_1_is_or_will_be_visible)
18058 {
18059 const float spacing = g.Style.DockingSeparatorSize;
18060 const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
18061 const float size_avail = ImMax(size[axis] - spacing, 0.0f);
18062
18063 // Size allocation policy
18064 // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows.
18065 const float size_min_each = ImTrunc(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f);
18066
18067 // FIXME: Blocks 2) and 3) are essentially doing nearly the same thing.
18068 // Difference are: write-back to SizeRef; application of a minimum size; rounding before ImTrunc()
18069 // Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce
18070
18071 // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge)
18072 if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce)
18073 {
18074 child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, child_0->Size[axis]);
18075 child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
18076 IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
18077 }
18078 else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce)
18079 {
18080 child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, child_1->Size[axis]);
18081 child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]);
18082 IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
18083 }
18084 else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce)
18085 {
18086 // FIXME-DOCK: We cannot honor the requested size, so apply ratio.
18087 // Currently this path will only be taken if code programmatically sets WantLockSizeOnce
18088 float split_ratio = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]);
18089 child_0_size[axis] = child_0->SizeRef[axis] = ImTrunc(size_avail * split_ratio);
18090 child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
18091 IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
18092 }
18093
18094 // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node
18095 else if (child_0->SizeRef[axis] != 0.0f && child_1->HasCentralNodeChild)
18096 {
18097 child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]);
18098 child_1_size[axis] = (size_avail - child_0_size[axis]);
18099 }
18100 else if (child_1->SizeRef[axis] != 0.0f && child_0->HasCentralNodeChild)
18101 {
18102 child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]);
18103 child_0_size[axis] = (size_avail - child_1_size[axis]);
18104 }
18105 else
18106 {
18107 // 4) Otherwise distribute according to the relative ratio of each SizeRef value
18108 float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]);
18109 child_0_size[axis] = ImMax(size_min_each, ImTrunc(size_avail * split_ratio + 0.5f));
18110 child_1_size[axis] = (size_avail - child_0_size[axis]);
18111 }
18112
18113 child_1_pos[axis] += spacing + child_0_size[axis];
18114 }
18115
18116 if (only_write_to_single_node == NULL)
18117 child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false;
18118
18119 const bool child_0_recurse = only_write_to_single_node ? child_0_is_toward_single_node : child_0->IsVisible;
18120 const bool child_1_recurse = only_write_to_single_node ? child_1_is_toward_single_node : child_1->IsVisible;
18121 if (child_0_recurse)
18122 DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size);
18123 if (child_1_recurse)
18124 DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size);
18125}
18126
18127static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector<ImGuiDockNode*>* touching_nodes)
18128{
18129 if (node->IsLeafNode())
18130 {
18131 touching_nodes->push_back(node);
18132 return;
18133 }
18134 if (node->ChildNodes[0]->IsVisible)
18135 if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible)
18136 DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes);
18137 if (node->ChildNodes[1]->IsVisible)
18138 if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible)
18139 DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes);
18140}
18141
18142// (Depth-First, Pre-Order)
18143void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node)
18144{
18145 if (node->IsLeafNode())
18146 return;
18147
18148 ImGuiContext& g = *GImGui;
18149
18150 ImGuiDockNode* child_0 = node->ChildNodes[0];
18151 ImGuiDockNode* child_1 = node->ChildNodes[1];
18152 if (child_0->IsVisible && child_1->IsVisible)
18153 {
18154 // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally)
18155 const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
18156 IM_ASSERT(axis != ImGuiAxis_None);
18157 ImRect bb;
18158 bb.Min = child_0->Pos;
18159 bb.Max = child_1->Pos;
18160 bb.Min[axis] += child_0->Size[axis];
18161 bb.Max[axis ^ 1] += child_1->Size[axis ^ 1];
18162 //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255));
18163
18164 const ImGuiDockNodeFlags merged_flags = child_0->MergedFlags | child_1->MergedFlags; // Merged flags for BOTH childs
18165 const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY;
18166 if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag))
18167 {
18168 ImGuiWindow* window = g.CurrentWindow;
18169 window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding);
18170 }
18171 else
18172 {
18173 //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node.
18174 //bb.Max[axis] -= 1;
18175 PushID(node->ID);
18176
18177 // Find resizing limits by gathering list of nodes that are touching the splitter line.
18178 ImVector<ImGuiDockNode*> touching_nodes[2];
18179 float min_size = g.Style.WindowMinSize[axis];
18180 float resize_limits[2];
18181 resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size;
18182 resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size;
18183
18184 ImGuiID splitter_id = GetID("##Splitter");
18185 if (g.ActiveId == splitter_id) // Only process when splitter is active
18186 {
18187 DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]);
18188 DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]);
18189 for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++)
18190 resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size);
18191 for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++)
18192 resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size);
18193
18194 // [DEBUG] Render touching nodes & limits
18195 /*
18196 ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
18197 for (int n = 0; n < 2; n++)
18198 {
18199 for (int touching_node_n = 0; touching_node_n < touching_nodes[n].Size; touching_node_n++)
18200 draw_list->AddRect(touching_nodes[n][touching_node_n]->Pos, touching_nodes[n][touching_node_n]->Pos + touching_nodes[n][touching_node_n]->Size, IM_COL32(0, 255, 0, 255));
18201 if (axis == ImGuiAxis_X)
18202 draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f);
18203 else
18204 draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f);
18205 }
18206 */
18207 }
18208
18209 // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters
18210 float cur_size_0 = child_0->Size[axis];
18211 float cur_size_1 = child_1->Size[axis];
18212 float min_size_0 = resize_limits[0] - child_0->Pos[axis];
18213 float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1];
18214 ImU32 bg_col = GetColorU32(ImGuiCol_WindowBg);
18215 if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, WINDOWS_HOVER_PADDING, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER, bg_col))
18216 {
18217 if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0)
18218 {
18219 child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0;
18220 child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis];
18221 child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1;
18222
18223 // Lock the size of every node that is a sibling of the node we are touching
18224 // This might be less desirable if we can merge sibling of a same axis into the same parental level.
18225 for (int side_n = 0; side_n < 2; side_n++)
18226 for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++)
18227 {
18228 ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n];
18229 //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
18230 //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255));
18231 while (touching_node->ParentNode != node)
18232 {
18233 if (touching_node->ParentNode->SplitAxis == axis)
18234 {
18235 // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize().
18236 ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n];
18237 node_to_preserve->WantLockSizeOnce = true;
18238 //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255));
18239 //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100));
18240 }
18241 touching_node = touching_node->ParentNode;
18242 }
18243 }
18244
18245 DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size);
18246 DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size);
18247 MarkIniSettingsDirty();
18248 }
18249 }
18250 PopID();
18251 }
18252 }
18253
18254 if (child_0->IsVisible)
18255 DockNodeTreeUpdateSplitter(child_0);
18256 if (child_1->IsVisible)
18257 DockNodeTreeUpdateSplitter(child_1);
18258}
18259
18260ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node)
18261{
18262 if (node->IsLeafNode())
18263 return node;
18264 if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0]))
18265 return leaf_node;
18266 if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1]))
18267 return leaf_node;
18268 return NULL;
18269}
18270
18271ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos)
18272{
18273 if (!node->IsVisible)
18274 return NULL;
18275
18276 const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE?
18277 ImRect r(node->Pos, node->Pos + node->Size);
18278 r.Expand(dock_spacing * 0.5f);
18279 bool inside = r.Contains(pos);
18280 if (!inside)
18281 return NULL;
18282
18283 if (node->IsLeafNode())
18284 return node;
18285 if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[0], pos))
18286 return hovered_node;
18287 if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[1], pos))
18288 return hovered_node;
18289
18290 // This means we are hovering over the splitter/spacing of a parent node
18291 return node;
18292}
18293
18294//-----------------------------------------------------------------------------
18295// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
18296//-----------------------------------------------------------------------------
18297// - SetWindowDock() [Internal]
18298// - DockSpace()
18299// - DockSpaceOverViewport()
18300//-----------------------------------------------------------------------------
18301
18302// [Internal] Called via SetNextWindowDockID()
18303void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond)
18304{
18305 // Test condition (NB: bit 0 is always true) and clear flags for next time
18306 if (cond && (window->SetWindowDockAllowFlags & cond) == 0)
18307 return;
18308 window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
18309
18310 if (window->DockId == dock_id)
18311 return;
18312
18313 // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot
18314 ImGuiContext& g = *GImGui;
18315 if (ImGuiDockNode* new_node = DockContextFindNodeByID(&g, dock_id))
18316 if (new_node->IsSplitNode())
18317 {
18318 // Policy: Find central node or latest focused node. We first move back to our root node.
18319 new_node = DockNodeGetRootNode(new_node);
18320 if (new_node->CentralNode)
18321 {
18322 IM_ASSERT(new_node->CentralNode->IsCentralNode());
18323 dock_id = new_node->CentralNode->ID;
18324 }
18325 else
18326 {
18327 dock_id = new_node->LastFocusedNodeId;
18328 }
18329 }
18330
18331 if (window->DockId == dock_id)
18332 return;
18333
18334 if (window->DockNode)
18335 DockNodeRemoveWindow(window->DockNode, window, 0);
18336 window->DockId = dock_id;
18337}
18338
18339// Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default.
18340// The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors.
18341// DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app.
18342// When ImGuiDockNodeFlags_KeepAliveOnly is set, nothing is submitted in the current window (function may be called from any location).
18343ImGuiID ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class)
18344{
18345 ImGuiContext& g = *GImGui;
18346 ImGuiWindow* window = GetCurrentWindowRead();
18347 if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
18348 return 0;
18349
18350 // Early out if parent window is hidden/collapsed
18351 // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960.
18352 // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true.
18353 if (window->SkipItems)
18354 flags |= ImGuiDockNodeFlags_KeepAliveOnly;
18355 if ((flags & ImGuiDockNodeFlags_KeepAliveOnly) == 0)
18356 window = GetCurrentWindow(); // call to set window->WriteAccessed = true;
18357
18358 IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0);
18359 IM_ASSERT(id != 0);
18360 ImGuiDockNode* node = DockContextFindNodeByID(&g, id);
18361 if (!node)
18362 {
18363 IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X created\n", id);
18364 node = DockContextAddNode(&g, id);
18365 node->SetLocalFlags(ImGuiDockNodeFlags_CentralNode);
18366 }
18367 if (window_class && window_class->ClassId != node->WindowClass.ClassId)
18368 IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", id, node->WindowClass.ClassId, window_class->ClassId);
18369 node->SharedFlags = flags;
18370 node->WindowClass = window_class ? *window_class : ImGuiWindowClass();
18371
18372 // When a DockSpace transitioned form implicit to explicit this may be called a second time
18373 // It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again.
18374 if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly))
18375 {
18376 IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID");
18377 node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
18378 return id;
18379 }
18380 node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
18381
18382 // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible
18383 if (flags & ImGuiDockNodeFlags_KeepAliveOnly)
18384 {
18385 node->LastFrameAlive = g.FrameCount;
18386 return id;
18387 }
18388
18389 const ImVec2 content_avail = GetContentRegionAvail();
18390 ImVec2 size = ImTrunc(size_arg);
18391 if (size.x <= 0.0f)
18392 size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
18393 if (size.y <= 0.0f)
18394 size.y = ImMax(content_avail.y + size.y, 4.0f);
18395 IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
18396
18397 node->Pos = window->DC.CursorPos;
18398 node->Size = node->SizeRef = size;
18399 SetNextWindowPos(node->Pos);
18400 SetNextWindowSize(node->Size);
18401 g.NextWindowData.PosUndock = false;
18402
18403 // FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window?
18404 // FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented)
18405 ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost;
18406 window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar;
18407 window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
18408 window_flags |= ImGuiWindowFlags_NoBackground;
18409
18410 char title[256];
18411 ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, id);
18412
18413 PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f);
18414 Begin(title, NULL, window_flags);
18415 PopStyleVar();
18416
18417 ImGuiWindow* host_window = g.CurrentWindow;
18418 DockNodeSetupHostWindow(node, host_window);
18419 host_window->ChildId = window->GetID(title);
18420 node->OnlyNodeWithWindows = NULL;
18421
18422 IM_ASSERT(node->IsRootNode());
18423
18424 // We need to handle the rare case were a central node is missing.
18425 // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace.
18426 // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split.
18427 // It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining.
18428 // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property,
18429 // as it doesn't make sense for an empty dockspace to not have this property.
18430 if (node->IsLeafNode() && !node->IsCentralNode())
18431 node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18432
18433 // Update the node
18434 DockNodeUpdate(node);
18435
18436 End();
18437
18438 ImRect bb(node->Pos, node->Pos + size);
18439 ItemSize(size);
18440 ItemAdd(bb, id, NULL, ImGuiItemFlags_NoNav); // Not a nav point (could be, would need to draw the nav rect and replicate/refactor activation from BeginChild(), but seems like CTRL+Tab works better here?)
18441 if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && IsWindowChildOf(g.HoveredWindow, host_window, false, true)) // To fullfill IsItemHovered(), similar to EndChild()
18442 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
18443
18444 return id;
18445}
18446
18447// Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode!
18448// The limitation with this call is that your window won't have a menu bar.
18449// Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function.
18450// But you can also use BeginMainMenuBar(). If you really want a menu bar inside the same window as the one hosting the dockspace, you will need to copy this code somewhere and tweak it.
18451ImGuiID ImGui::DockSpaceOverViewport(const ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class)
18452{
18453 if (viewport == NULL)
18454 viewport = GetMainViewport();
18455
18456 SetNextWindowPos(viewport->WorkPos);
18457 SetNextWindowSize(viewport->WorkSize);
18458 SetNextWindowViewport(viewport->ID);
18459
18460 ImGuiWindowFlags host_window_flags = 0;
18461 host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
18462 host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
18463 if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
18464 host_window_flags |= ImGuiWindowFlags_NoBackground;
18465
18466 char label[32];
18467 ImFormatString(label, IM_ARRAYSIZE(label), "DockSpaceViewport_%08X", viewport->ID);
18468
18469 PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
18470 PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
18471 PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
18472 Begin(label, NULL, host_window_flags);
18473 PopStyleVar(3);
18474
18475 ImGuiID dockspace_id = GetID("DockSpace");
18476 DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class);
18477 End();
18478
18479 return dockspace_id;
18480}
18481
18482//-----------------------------------------------------------------------------
18483// Docking: Builder Functions
18484//-----------------------------------------------------------------------------
18485// Very early end-user API to manipulate dock nodes.
18486// Only available in imgui_internal.h. Expect this API to change/break!
18487// It is expected that those functions are all called _before_ the dockspace node submission.
18488//-----------------------------------------------------------------------------
18489// - DockBuilderDockWindow()
18490// - DockBuilderGetNode()
18491// - DockBuilderSetNodePos()
18492// - DockBuilderSetNodeSize()
18493// - DockBuilderAddNode()
18494// - DockBuilderRemoveNode()
18495// - DockBuilderRemoveNodeChildNodes()
18496// - DockBuilderRemoveNodeDockedWindows()
18497// - DockBuilderSplitNode()
18498// - DockBuilderCopyNodeRec()
18499// - DockBuilderCopyNode()
18500// - DockBuilderCopyWindowSettings()
18501// - DockBuilderCopyDockSpace()
18502// - DockBuilderFinish()
18503//-----------------------------------------------------------------------------
18504
18505void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id)
18506{
18507 // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1)
18508 ImGuiContext& g = *GImGui; IM_UNUSED(g);
18509 IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderDockWindow '%s' to node 0x%08X\n", window_name, node_id);
18510 ImGuiID window_id = ImHashStr(window_name);
18511 if (ImGuiWindow* window = FindWindowByID(window_id))
18512 {
18513 // Apply to created window
18514 ImGuiID prev_node_id = window->DockId;
18515 SetWindowDock(window, node_id, ImGuiCond_Always);
18516 if (window->DockId != prev_node_id)
18517 window->DockOrder = -1;
18518 }
18519 else
18520 {
18521 // Apply to settings
18522 ImGuiWindowSettings* settings = FindWindowSettingsByID(window_id);
18523 if (settings == NULL)
18524 settings = CreateNewWindowSettings(window_name);
18525 if (settings->DockId != node_id)
18526 settings->DockOrder = -1;
18527 settings->DockId = node_id;
18528 }
18529}
18530
18531ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id)
18532{
18533 ImGuiContext& g = *GImGui;
18534 return DockContextFindNodeByID(&g, node_id);
18535}
18536
18537void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos)
18538{
18539 ImGuiContext& g = *GImGui;
18540 ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
18541 if (node == NULL)
18542 return;
18543 node->Pos = pos;
18544 node->AuthorityForPos = ImGuiDataAuthority_DockNode;
18545}
18546
18547void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size)
18548{
18549 ImGuiContext& g = *GImGui;
18550 ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
18551 if (node == NULL)
18552 return;
18553 IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
18554 node->Size = node->SizeRef = size;
18555 node->AuthorityForSize = ImGuiDataAuthority_DockNode;
18556}
18557
18558// Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node!
18559// - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node.
18560// - Dockspace node: calling DockBuilderSetNodePos() is unnecessary.
18561// - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand!
18562// For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect.
18563// - Use (id == 0) to let the system allocate a node identifier.
18564// - Existing node with a same id will be removed.
18565ImGuiID ImGui::DockBuilderAddNode(ImGuiID node_id, ImGuiDockNodeFlags flags)
18566{
18567 ImGuiContext& g = *GImGui; IM_UNUSED(g);
18568 IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderAddNode 0x%08X flags=%08X\n", node_id, flags);
18569
18570 if (node_id != 0)
18571 DockBuilderRemoveNode(node_id);
18572
18573 ImGuiDockNode* node = NULL;
18574 if (flags & ImGuiDockNodeFlags_DockSpace)
18575 {
18576 DockSpace(node_id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly);
18577 node = DockContextFindNodeByID(&g, node_id);
18578 }
18579 else
18580 {
18581 node = DockContextAddNode(&g, node_id);
18582 node->SetLocalFlags(flags);
18583 }
18584 node->LastFrameAlive = g.FrameCount; // Set this otherwise BeginDocked will undock during the same frame.
18585 return node->ID;
18586}
18587
18588void ImGui::DockBuilderRemoveNode(ImGuiID node_id)
18589{
18590 ImGuiContext& g = *GImGui; IM_UNUSED(g);
18591 IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderRemoveNode 0x%08X\n", node_id);
18592
18593 ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
18594 if (node == NULL)
18595 return;
18596 DockBuilderRemoveNodeDockedWindows(node_id, true);
18597 DockBuilderRemoveNodeChildNodes(node_id);
18598 // Node may have moved or deleted if e.g. any merge happened
18599 node = DockContextFindNodeByID(&g, node_id);
18600 if (node == NULL)
18601 return;
18602 if (node->IsCentralNode() && node->ParentNode)
18603 node->ParentNode->SetLocalFlags(node->ParentNode->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18604 DockContextRemoveNode(&g, node, true);
18605}
18606
18607// root_id = 0 to remove all, root_id != 0 to remove child of given node.
18608void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id)
18609{
18610 ImGuiContext& g = *GImGui;
18611 ImGuiDockContext* dc = &g.DockContext;
18612
18613 ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(&g, root_id) : NULL;
18614 if (root_id && root_node == NULL)
18615 return;
18616 bool has_central_node = false;
18617
18618 ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto;
18619 ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto;
18620
18621 // Process active windows
18622 ImVector<ImGuiDockNode*> nodes_to_remove;
18623 for (int n = 0; n < dc->Nodes.Data.Size; n++)
18624 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
18625 {
18626 bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id);
18627 if (want_removal)
18628 {
18629 if (node->IsCentralNode())
18630 has_central_node = true;
18631 if (root_id != 0)
18632 DockContextQueueNotifyRemovedNode(&g, node);
18633 if (root_node)
18634 {
18635 DockNodeMoveWindows(root_node, node);
18636 DockSettingsRenameNodeReferences(node->ID, root_node->ID);
18637 }
18638 nodes_to_remove.push_back(node);
18639 }
18640 }
18641
18642 // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge)
18643 // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead)
18644 if (root_node)
18645 {
18646 root_node->AuthorityForPos = backup_root_node_authority_for_pos;
18647 root_node->AuthorityForSize = backup_root_node_authority_for_size;
18648 }
18649
18650 // Apply to settings
18651 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18652 if (ImGuiID window_settings_dock_id = settings->DockId)
18653 for (int n = 0; n < nodes_to_remove.Size; n++)
18654 if (nodes_to_remove[n]->ID == window_settings_dock_id)
18655 {
18656 settings->DockId = root_id;
18657 break;
18658 }
18659
18660 // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes
18661 if (nodes_to_remove.Size > 1)
18662 ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode*), DockNodeComparerDepthMostFirst);
18663 for (int n = 0; n < nodes_to_remove.Size; n++)
18664 DockContextRemoveNode(&g, nodes_to_remove[n], false);
18665
18666 if (root_id == 0)
18667 {
18668 dc->Nodes.Clear();
18669 dc->Requests.clear();
18670 }
18671 else if (has_central_node)
18672 {
18673 root_node->CentralNode = root_node;
18674 root_node->SetLocalFlags(root_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18675 }
18676}
18677
18678void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs)
18679{
18680 // Clear references in settings
18681 ImGuiContext& g = *GImGui;
18682 if (clear_settings_refs)
18683 {
18684 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18685 {
18686 bool want_removal = (root_id == 0) || (settings->DockId == root_id);
18687 if (!want_removal && settings->DockId != 0)
18688 if (ImGuiDockNode* node = DockContextFindNodeByID(&g, settings->DockId))
18689 if (DockNodeGetRootNode(node)->ID == root_id)
18690 want_removal = true;
18691 if (want_removal)
18692 settings->DockId = 0;
18693 }
18694 }
18695
18696 // Clear references in windows
18697 for (int n = 0; n < g.Windows.Size; n++)
18698 {
18699 ImGuiWindow* window = g.Windows[n];
18700 bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id);
18701 if (want_removal)
18702 {
18703 const ImGuiID backup_dock_id = window->DockId;
18704 IM_UNUSED(backup_dock_id);
18705 DockContextProcessUndockWindow(&g, window, clear_settings_refs);
18706 if (!clear_settings_refs)
18707 IM_ASSERT(window->DockId == backup_dock_id);
18708 }
18709 }
18710}
18711
18712// If 'out_id_at_dir' or 'out_id_at_opposite_dir' are non NULL, the function will write out the ID of the two new nodes created.
18713// Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set.
18714// FIXME-DOCK: We are not exposing nor using split_outer.
18715ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir)
18716{
18717 ImGuiContext& g = *GImGui;
18718 IM_ASSERT(split_dir != ImGuiDir_None);
18719 IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderSplitNode: node 0x%08X, split_dir %d\n", id, split_dir);
18720
18721 ImGuiDockNode* node = DockContextFindNodeByID(&g, id);
18722 if (node == NULL)
18723 {
18724 IM_ASSERT(node != NULL);
18725 return 0;
18726 }
18727
18728 IM_ASSERT(!node->IsSplitNode()); // Assert if already Split
18729
18730 ImGuiDockRequest req;
18732 req.DockTargetWindow = NULL;
18733 req.DockTargetNode = node;
18734 req.DockPayload = NULL;
18735 req.DockSplitDir = split_dir;
18736 req.DockSplitRatio = ImSaturate((split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir);
18737 req.DockSplitOuter = false;
18738 DockContextProcessDock(&g, &req);
18739
18740 ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID;
18741 ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID;
18742 if (out_id_at_dir)
18743 *out_id_at_dir = id_at_dir;
18744 if (out_id_at_opposite_dir)
18745 *out_id_at_opposite_dir = id_at_opposite_dir;
18746 return id_at_dir;
18747}
18748
18749static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector<ImGuiID>* out_node_remap_pairs)
18750{
18751 ImGuiContext& g = *GImGui;
18752 ImGuiDockNode* dst_node = ImGui::DockContextAddNode(&g, dst_node_id_if_known);
18753 dst_node->SharedFlags = src_node->SharedFlags;
18754 dst_node->LocalFlags = src_node->LocalFlags;
18755 dst_node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
18756 dst_node->Pos = src_node->Pos;
18757 dst_node->Size = src_node->Size;
18758 dst_node->SizeRef = src_node->SizeRef;
18759 dst_node->SplitAxis = src_node->SplitAxis;
18760 dst_node->UpdateMergedFlags();
18761
18762 out_node_remap_pairs->push_back(src_node->ID);
18763 out_node_remap_pairs->push_back(dst_node->ID);
18764
18765 for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++)
18766 if (src_node->ChildNodes[child_n])
18767 {
18768 dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs);
18769 dst_node->ChildNodes[child_n]->ParentNode = dst_node;
18770 }
18771
18772 IMGUI_DEBUG_LOG_DOCKING("[docking] Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0);
18773 return dst_node;
18774}
18775
18776void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector<ImGuiID>* out_node_remap_pairs)
18777{
18778 ImGuiContext& g = *GImGui;
18779 IM_ASSERT(src_node_id != 0);
18780 IM_ASSERT(dst_node_id != 0);
18781 IM_ASSERT(out_node_remap_pairs != NULL);
18782
18783 DockBuilderRemoveNode(dst_node_id);
18784
18785 ImGuiDockNode* src_node = DockContextFindNodeByID(&g, src_node_id);
18786 IM_ASSERT(src_node != NULL);
18787
18788 out_node_remap_pairs->clear();
18789 DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs);
18790
18791 IM_ASSERT((out_node_remap_pairs->Size % 2) == 0);
18792}
18793
18794void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name)
18795{
18796 ImGuiWindow* src_window = FindWindowByName(src_name);
18797 if (src_window == NULL)
18798 return;
18799 if (ImGuiWindow* dst_window = FindWindowByName(dst_name))
18800 {
18801 dst_window->Pos = src_window->Pos;
18802 dst_window->Size = src_window->Size;
18803 dst_window->SizeFull = src_window->SizeFull;
18804 dst_window->Collapsed = src_window->Collapsed;
18805 }
18806 else
18807 {
18808 ImGuiWindowSettings* dst_settings = FindWindowSettingsByID(ImHashStr(dst_name));
18809 if (!dst_settings)
18810 dst_settings = CreateNewWindowSettings(dst_name);
18811 ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos);
18812 if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID)
18813 {
18814 dst_settings->ViewportPos = window_pos_2ih;
18815 dst_settings->ViewportId = src_window->ViewportId;
18816 dst_settings->Pos = ImVec2ih(0, 0);
18817 }
18818 else
18819 {
18820 dst_settings->Pos = window_pos_2ih;
18821 }
18822 dst_settings->Size = ImVec2ih(src_window->SizeFull);
18823 dst_settings->Collapsed = src_window->Collapsed;
18824 }
18825}
18826
18827// FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed.
18828void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector<const char*>* in_window_remap_pairs)
18829{
18830 ImGuiContext& g = *GImGui;
18831 IM_ASSERT(src_dockspace_id != 0);
18832 IM_ASSERT(dst_dockspace_id != 0);
18833 IM_ASSERT(in_window_remap_pairs != NULL);
18834 IM_ASSERT((in_window_remap_pairs->Size % 2) == 0);
18835
18836 // Duplicate entire dock
18837 // FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart,
18838 // whereas we could attempt to at least keep them together in a new, same floating node.
18839 ImVector<ImGuiID> node_remap_pairs;
18840 DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs);
18841
18842 // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes
18843 // (The windows associated to src_dockspace_id are staying in place)
18844 ImVector<ImGuiID> src_windows;
18845 for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2)
18846 {
18847 const char* src_window_name = (*in_window_remap_pairs)[remap_window_n];
18848 const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1];
18849 ImGuiID src_window_id = ImHashStr(src_window_name);
18850 src_windows.push_back(src_window_id);
18851
18852 // Search in the remapping tables
18853 ImGuiID src_dock_id = 0;
18854 if (ImGuiWindow* src_window = FindWindowByID(src_window_id))
18855 src_dock_id = src_window->DockId;
18856 else if (ImGuiWindowSettings* src_window_settings = FindWindowSettingsByID(src_window_id))
18857 src_dock_id = src_window_settings->DockId;
18858 ImGuiID dst_dock_id = 0;
18859 for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
18860 if (node_remap_pairs[dock_remap_n] == src_dock_id)
18861 {
18862 dst_dock_id = node_remap_pairs[dock_remap_n + 1];
18863 //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear
18864 break;
18865 }
18866
18867 if (dst_dock_id != 0)
18868 {
18869 // Docked windows gets redocked into the new node hierarchy.
18870 IMGUI_DEBUG_LOG_DOCKING("[docking] Remap live window '%s' 0x%08X -> '%s' 0x%08X\n", src_window_name, src_dock_id, dst_window_name, dst_dock_id);
18871 DockBuilderDockWindow(dst_window_name, dst_dock_id);
18872 }
18873 else
18874 {
18875 // Floating windows gets their settings transferred (regardless of whether the new window already exist or not)
18876 // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together?
18877 IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name);
18878 DockBuilderCopyWindowSettings(src_window_name, dst_window_name);
18879 }
18880 }
18881
18882 // Anything else in the source nodes of 'node_remap_pairs' are windows that are not included in the remapping list.
18883 // Find those windows and move to them to the cloned dock node. This may be optional?
18884 // Dock those are a second step as undocking would invalidate source dock nodes.
18885 struct DockRemainingWindowTask { ImGuiWindow* Window; ImGuiID DockId; DockRemainingWindowTask(ImGuiWindow* window, ImGuiID dock_id) { Window = window; DockId = dock_id; } };
18886 ImVector<DockRemainingWindowTask> dock_remaining_windows;
18887 for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
18888 if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n])
18889 {
18890 ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1];
18891 ImGuiDockNode* node = DockBuilderGetNode(src_dock_id);
18892 for (int window_n = 0; window_n < node->Windows.Size; window_n++)
18893 {
18894 ImGuiWindow* window = node->Windows[window_n];
18895 if (src_windows.contains(window->ID))
18896 continue;
18897
18898 // Docked windows gets redocked into the new node hierarchy.
18899 IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id);
18900 dock_remaining_windows.push_back(DockRemainingWindowTask(window, dst_dock_id));
18901 }
18902 }
18903 for (const DockRemainingWindowTask& task : dock_remaining_windows)
18904 DockBuilderDockWindow(task.Window->Name, task.DockId);
18905}
18906
18907// FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node.
18908void ImGui::DockBuilderFinish(ImGuiID root_id)
18909{
18910 ImGuiContext& g = *GImGui;
18911 //DockContextRebuild(&g);
18912 DockContextBuildAddWindowsToNodes(&g, root_id);
18913}
18914
18915//-----------------------------------------------------------------------------
18916// Docking: Begin/End Support Functions (called from Begin/End)
18917//-----------------------------------------------------------------------------
18918// - GetWindowAlwaysWantOwnTabBar()
18919// - DockContextBindNodeToWindow()
18920// - BeginDocked()
18921// - BeginDockableDragDropSource()
18922// - BeginDockableDragDropTarget()
18923//-----------------------------------------------------------------------------
18924
18925bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window)
18926{
18927 ImGuiContext& g = *GImGui;
18928 if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar)
18929 if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0)
18930 if (!window->IsFallbackWindow) // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise
18931 return true;
18932 return false;
18933}
18934
18935static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window)
18936{
18937 ImGuiContext& g = *ctx;
18938 ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
18939 IM_ASSERT(window->DockNode == NULL);
18940
18941 // We should not be docking into a split node (SetWindowDock should avoid this)
18942 if (node && node->IsSplitNode())
18943 {
18944 DockContextProcessUndockWindow(ctx, window);
18945 return NULL;
18946 }
18947
18948 // Create node
18949 if (node == NULL)
18950 {
18951 node = DockContextAddNode(ctx, window->DockId);
18952 node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
18953 node->LastFrameAlive = g.FrameCount;
18954 }
18955
18956 // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet,
18957 // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node).
18958 // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout.
18959 // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame.
18960 if (!node->IsVisible)
18961 {
18962 ImGuiDockNode* ancestor_node = node;
18963 while (!ancestor_node->IsVisible && ancestor_node->ParentNode)
18964 ancestor_node = ancestor_node->ParentNode;
18965 IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f);
18966 DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(ancestor_node));
18967 DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, node);
18968 }
18969
18970 // Add window to node
18971 bool node_was_visible = node->IsVisible;
18972 DockNodeAddWindow(node, window, true);
18973 node->IsVisible = node_was_visible; // Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see)
18974 IM_ASSERT(node == window->DockNode);
18975 return node;
18976}
18977
18978void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open)
18979{
18980 ImGuiContext& g = *GImGui;
18981
18982 // Clear fields ahead so most early-out paths don't have to do it
18983 window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
18984
18985 const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window);
18986 if (auto_dock_node)
18987 {
18988 if (window->DockId == 0)
18989 {
18990 IM_ASSERT(window->DockNode == NULL);
18991 window->DockId = DockContextGenNodeID(&g);
18992 }
18993 }
18994 else
18995 {
18996 // Calling SetNextWindowPos() undock windows by default (by setting PosUndock)
18997 bool want_undock = false;
18998 want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0;
18999 want_undock |= (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock;
19000 if (want_undock)
19001 {
19002 DockContextProcessUndockWindow(&g, window);
19003 return;
19004 }
19005 }
19006
19007 // Bind to our dock node
19008 ImGuiDockNode* node = window->DockNode;
19009 if (node != NULL)
19010 IM_ASSERT(window->DockId == node->ID);
19011 if (window->DockId != 0 && node == NULL)
19012 {
19013 node = DockContextBindNodeToWindow(&g, window);
19014 if (node == NULL)
19015 return;
19016 }
19017
19018#if 0
19019 // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set
19020 if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode))
19021 {
19022 DockContextProcessUndockWindow(ctx, window);
19023 return;
19024 }
19025#endif
19026
19027 // Undock if our dockspace node disappeared
19028 // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly.
19029 if (node->LastFrameAlive < g.FrameCount)
19030 {
19031 // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking()
19032 ImGuiDockNode* root_node = DockNodeGetRootNode(node);
19033 if (root_node->LastFrameAlive < g.FrameCount)
19034 DockContextProcessUndockWindow(&g, window);
19035 else
19036 window->DockIsActive = true;
19037 return;
19038 }
19039
19040 // Store style overrides
19041 for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
19042 window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
19043
19044 // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window,
19045 // and never create neither a host window neither a tab bar.
19046 // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test)
19047 if (node->HostWindow == NULL)
19048 {
19049 if (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing)
19050 window->DockIsActive = true;
19051 if (node->Windows.Size > 1 && window->Appearing) // Only hide appearing window
19052 DockNodeHideWindowDuringHostWindowCreation(window);
19053 return;
19054 }
19055
19056 // We can have zero-sized nodes (e.g. children of a small-size dockspace)
19057 IM_ASSERT(node->HostWindow);
19058 IM_ASSERT(node->IsLeafNode());
19059 IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f);
19060 node->State = ImGuiDockNodeState_HostWindowVisible;
19061
19062 // Undock if we are submitted earlier than the host window
19063 if (!(node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) && window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext)
19064 {
19065 DockContextProcessUndockWindow(&g, window);
19066 return;
19067 }
19068
19069 // Position/Size window
19070 SetNextWindowPos(node->Pos);
19071 SetNextWindowSize(node->Size);
19072 g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos()
19073 window->DockIsActive = true;
19074 window->DockNodeIsVisible = true;
19075 window->DockTabIsVisible = false;
19076 if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
19077 return;
19078
19079 // When the window is selected we mark it as visible.
19080 if (node->VisibleWindow == window)
19081 window->DockTabIsVisible = true;
19082
19083 // Update window flag
19084 IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0);
19085 window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize;
19086 window->ChildFlags |= ImGuiChildFlags_AlwaysUseWindowPadding;
19087 if (node->IsHiddenTabBar() || node->IsNoTabBar())
19088 window->Flags |= ImGuiWindowFlags_NoTitleBar;
19089 else
19090 window->Flags &= ~ImGuiWindowFlags_NoTitleBar; // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed!
19091
19092 // Save new dock order only if the window has been visible once already
19093 // This allows multiple windows to be created in the same frame and have their respective dock orders preserved.
19094 if (node->TabBar && window->WasActive)
19095 window->DockOrder = (short)DockNodeGetTabOrder(window);
19096
19097 if ((node->WantCloseAll || node->WantCloseTabId == window->TabId) && p_open != NULL)
19098 *p_open = false;
19099
19100 // Update ChildId to allow returning from Child to Parent with Escape
19101 ImGuiWindow* parent_window = window->DockNode->HostWindow;
19102 window->ChildId = parent_window->GetID(window->Name);
19103}
19104
19105void ImGui::BeginDockableDragDropSource(ImGuiWindow* window)
19106{
19107 ImGuiContext& g = *GImGui;
19108 IM_ASSERT(g.ActiveId == window->MoveId);
19109 IM_ASSERT(g.MovingWindow == window);
19110 IM_ASSERT(g.CurrentWindow == window);
19111
19112 // 0: Hold SHIFT to disable docking, 1: Hold SHIFT to enable docking.
19113 if (g.IO.ConfigDockingWithShift != g.IO.KeyShift)
19114 {
19115 // When ConfigDockingWithShift is set, display a tooltip to increase UI affordance.
19116 // We cannot set for HoveredWindowUnderMovingWindow != NULL here, as it is only valid/useful when drag and drop is already active
19117 // (because of the 'is_mouse_dragging_with_an_expected_destination' logic in UpdateViewportsNewFrame() function)
19118 if (g.IO.ConfigDockingWithShift && g.MouseStationaryTimer >= 1.0f && g.ActiveId >= 1.0f)
19119 SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingHoldShiftToDock));
19120 return;
19121 }
19122
19123 g.LastItemData.ID = window->MoveId;
19124 window = window->RootWindowDockTree;
19125 IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
19126 bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(g.ActiveIdClickOffset); // FIXME-DOCKING: Need to make this stateful and explicit
19127 if (is_drag_docking && BeginDragDropSource(ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_SourceAutoExpirePayload))
19128 {
19129 SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window));
19130 EndDragDropSource();
19131
19132 // Store style overrides
19133 for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
19134 window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
19135 }
19136}
19137
19138void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window)
19139{
19140 ImGuiContext& g = *GImGui;
19141
19142 //IM_ASSERT(window->RootWindowDockTree == window); // May also be a DockSpace
19143 IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
19144 if (!g.DragDropActive)
19145 return;
19146 //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
19147 if (!BeginDragDropTargetCustom(window->Rect(), window->ID))
19148 return;
19149
19150 // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering
19151 // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly)
19152 const ImGuiPayload* payload = &g.DragDropPayload;
19153 if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow**)payload->Data))
19154 {
19155 EndDragDropTarget();
19156 return;
19157 }
19158
19159 ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data;
19160 if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
19161 {
19162 // Select target node
19163 // (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation)
19164 bool dock_into_floating_window = false;
19165 ImGuiDockNode* node = NULL;
19166 if (window->DockNodeAsHost)
19167 {
19168 // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos().
19169 node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos);
19170
19171 // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active)
19172 // In this case we need to fallback into any leaf mode, possibly the central node.
19173 // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first.
19174 if (node && node->IsDockSpace() && node->IsRootNode())
19175 node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node);
19176 }
19177 else
19178 {
19179 if (window->DockNode)
19180 node = window->DockNode;
19181 else
19182 dock_into_floating_window = true; // Dock into a regular window
19183 }
19184
19185 const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight()));
19186 const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max);
19187
19188 // Preview docking request and find out split direction/ratio
19189 //const bool do_preview = true; // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window.
19190 const bool do_preview = payload->IsPreview() || payload->IsDelivery();
19191 if (do_preview && (node != NULL || dock_into_floating_window))
19192 {
19193 // If we have a non-leaf node it means we are hovering the border of a parent node, in which case only outer markers will appear.
19194 ImGuiDockPreviewData split_inner;
19195 ImGuiDockPreviewData split_outer;
19196 ImGuiDockPreviewData* split_data = &split_inner;
19197 if (node && (node->ParentNode || node->IsCentralNode() || !node->IsLeafNode()))
19198 if (ImGuiDockNode* root_node = DockNodeGetRootNode(node))
19199 {
19200 DockNodePreviewDockSetup(window, root_node, payload_window, NULL, &split_outer, is_explicit_target, true);
19201 if (split_outer.IsSplitDirExplicit)
19202 split_data = &split_outer;
19203 }
19204 if (!node || node->IsLeafNode())
19205 DockNodePreviewDockSetup(window, node, payload_window, NULL, &split_inner, is_explicit_target, false);
19206 if (split_data == &split_outer)
19207 split_inner.IsDropAllowed = false;
19208
19209 // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes
19210 DockNodePreviewDockRender(window, node, payload_window, &split_inner);
19211 DockNodePreviewDockRender(window, node, payload_window, &split_outer);
19212
19213 // Queue docking request
19214 if (split_data->IsDropAllowed && payload->IsDelivery())
19215 DockContextQueueDock(&g, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer);
19216 }
19217 }
19218 EndDragDropTarget();
19219}
19220
19221//-----------------------------------------------------------------------------
19222// Docking: Settings
19223//-----------------------------------------------------------------------------
19224// - DockSettingsRenameNodeReferences()
19225// - DockSettingsRemoveNodeReferences()
19226// - DockSettingsFindNodeSettings()
19227// - DockSettingsHandler_ApplyAll()
19228// - DockSettingsHandler_ReadOpen()
19229// - DockSettingsHandler_ReadLine()
19230// - DockSettingsHandler_DockNodeToSettings()
19231// - DockSettingsHandler_WriteAll()
19232//-----------------------------------------------------------------------------
19233
19234static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id)
19235{
19236 ImGuiContext& g = *GImGui;
19237 IMGUI_DEBUG_LOG_DOCKING("[docking] DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id);
19238 for (int window_n = 0; window_n < g.Windows.Size; window_n++)
19239 {
19240 ImGuiWindow* window = g.Windows[window_n];
19241 if (window->DockId == old_node_id && window->DockNode == NULL)
19242 window->DockId = new_node_id;
19243 }
19245 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19246 if (settings->DockId == old_node_id)
19247 settings->DockId = new_node_id;
19248}
19249
19250// Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings
19251static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count)
19252{
19253 ImGuiContext& g = *GImGui;
19254 int found = 0;
19256 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19257 for (int node_n = 0; node_n < node_ids_count; node_n++)
19258 if (settings->DockId == node_ids[node_n])
19259 {
19260 settings->DockId = 0;
19261 settings->DockOrder = -1;
19262 if (++found < node_ids_count)
19263 break;
19264 return;
19265 }
19266}
19267
19268static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id)
19269{
19270 // FIXME-OPT
19271 ImGuiDockContext* dc = &ctx->DockContext;
19272 for (int n = 0; n < dc->NodesSettings.Size; n++)
19273 if (dc->NodesSettings[n].ID == id)
19274 return &dc->NodesSettings[n];
19275 return NULL;
19276}
19277
19278// Clear settings data
19279static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
19280{
19281 ImGuiDockContext* dc = &ctx->DockContext;
19282 dc->NodesSettings.clear();
19283 DockContextClearNodes(ctx, 0, true);
19284}
19285
19286// Recreate nodes based on settings data
19287static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
19288{
19289 // Prune settings at boot time only
19290 ImGuiDockContext* dc = &ctx->DockContext;
19291 if (ctx->Windows.Size == 0)
19292 DockContextPruneUnusedSettingsNodes(ctx);
19293 DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
19294 DockContextBuildAddWindowsToNodes(ctx, 0);
19295}
19296
19297static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
19298{
19299 if (strcmp(name, "Data") != 0)
19300 return NULL;
19301 return (void*)1;
19302}
19303
19304static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line)
19305{
19306 char c = 0;
19307 int x = 0, y = 0;
19308 int r = 0;
19309
19310 // Parsing, e.g.
19311 // " DockNode ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 "
19312 // " DockNode ID=0x00000002 Parent=0x00000001 "
19313 // Important: this code expect currently fields in a fixed order.
19315 line = ImStrSkipBlank(line);
19316 if (strncmp(line, "DockNode", 8) == 0) { line = ImStrSkipBlank(line + strlen("DockNode")); }
19317 else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; }
19318 else return;
19319 if (sscanf(line, "ID=0x%08X%n", &node.ID, &r) == 1) { line += r; } else return;
19320 if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1) { line += r; if (node.ParentNodeId == 0) return; }
19321 if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowId, &r) ==1) { line += r; if (node.ParentWindowId == 0) return; }
19322 if (node.ParentNodeId == 0)
19323 {
19324 if (sscanf(line, " Pos=%i,%i%n", &x, &y, &r) == 2) { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return;
19325 if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2) { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return;
19326 }
19327 else
19328 {
19329 if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2) { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); }
19330 }
19331 if (sscanf(line, " Split=%c%n", &c, &r) == 1) { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; }
19332 if (sscanf(line, " NoResize=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; }
19333 if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; }
19334 if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; }
19335 if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; }
19336 if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; }
19337 if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; }
19338 if (sscanf(line, " Selected=0x%08X%n", &node.SelectedTabId,&r) == 1) { line += r; }
19339 if (node.ParentNodeId != 0)
19340 if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId))
19341 node.Depth = parent_settings->Depth + 1;
19342 ctx->DockContext.NodesSettings.push_back(node);
19343}
19344
19345static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth)
19346{
19347 ImGuiDockNodeSettings node_settings;
19348 IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3)));
19349 node_settings.ID = node->ID;
19350 node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0;
19351 node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0;
19352 node_settings.SelectedTabId = node->SelectedTabId;
19353 node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None);
19354 node_settings.Depth = (char)depth;
19355 node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_);
19356 node_settings.Pos = ImVec2ih(node->Pos);
19357 node_settings.Size = ImVec2ih(node->Size);
19358 node_settings.SizeRef = ImVec2ih(node->SizeRef);
19359 dc->NodesSettings.push_back(node_settings);
19360 if (node->ChildNodes[0])
19361 DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1);
19362 if (node->ChildNodes[1])
19363 DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1);
19364}
19365
19366static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
19367{
19368 ImGuiContext& g = *ctx;
19369 ImGuiDockContext* dc = &ctx->DockContext;
19370 if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
19371 return;
19372
19373 // Gather settings data
19374 // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer)
19375 dc->NodesSettings.resize(0);
19376 dc->NodesSettings.reserve(dc->Nodes.Data.Size);
19377 for (int n = 0; n < dc->Nodes.Data.Size; n++)
19378 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
19379 if (node->IsRootNode())
19380 DockSettingsHandler_DockNodeToSettings(dc, node, 0);
19381
19382 int max_depth = 0;
19383 for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
19384 max_depth = ImMax((int)dc->NodesSettings[node_n].Depth, max_depth);
19385
19386 // Write to text buffer
19387 buf->appendf("[%s][Data]\n", handler->TypeName);
19388 for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
19389 {
19390 const int line_start_pos = buf->size(); (void)line_start_pos;
19391 const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[node_n];
19392 buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, ""); // Text align nodes to facilitate looking at .ini file
19393 buf->appendf(" ID=0x%08X", node_settings->ID);
19394 if (node_settings->ParentNodeId)
19395 {
19396 buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y);
19397 }
19398 else
19399 {
19400 if (node_settings->ParentWindowId)
19401 buf->appendf(" Window=0x%08X", node_settings->ParentWindowId);
19402 buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y);
19403 }
19404 if (node_settings->SplitAxis != ImGuiAxis_None)
19405 buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y');
19406 if (node_settings->Flags & ImGuiDockNodeFlags_NoResize)
19407 buf->appendf(" NoResize=1");
19408 if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode)
19409 buf->appendf(" CentralNode=1");
19410 if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar)
19411 buf->appendf(" NoTabBar=1");
19412 if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar)
19413 buf->appendf(" HiddenTabBar=1");
19414 if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton)
19415 buf->appendf(" NoWindowMenuButton=1");
19416 if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton)
19417 buf->appendf(" NoCloseButton=1");
19418 if (node_settings->SelectedTabId)
19419 buf->appendf(" Selected=0x%08X", node_settings->SelectedTabId);
19420
19421 // [DEBUG] Include comments in the .ini file to ease debugging (this makes saving slower!)
19422 if (g.IO.ConfigDebugIniSettings)
19423 if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID))
19424 {
19425 buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), ""); // Align everything
19426 if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow)
19427 buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name);
19428 // Iterate settings so we can give info about windows that didn't exist during the session.
19429 int contains_window = 0;
19430 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19431 if (settings->DockId == node_settings->ID)
19432 {
19433 if (contains_window++ == 0)
19434 buf->appendf(" ; contains ");
19435 buf->appendf("'%s' ", settings->GetName());
19436 }
19437 }
19438
19439 buf->appendf("\n");
19440 }
19441 buf->appendf("\n");
19442}
19443
19444
19445//-----------------------------------------------------------------------------
19446// [SECTION] PLATFORM DEPENDENT HELPERS
19447//-----------------------------------------------------------------------------
19448
19449#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
19450
19451#ifdef _MSC_VER
19452#pragma comment(lib, "user32")
19453#pragma comment(lib, "kernel32")
19454#endif
19455
19456// Win32 clipboard implementation
19457// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
19458static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19459{
19460 ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19461 g.ClipboardHandlerData.clear();
19462 if (!::OpenClipboard(NULL))
19463 return NULL;
19464 HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
19465 if (wbuf_handle == NULL)
19466 {
19467 ::CloseClipboard();
19468 return NULL;
19469 }
19470 if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
19471 {
19472 int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
19473 g.ClipboardHandlerData.resize(buf_len);
19474 ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
19475 }
19476 ::GlobalUnlock(wbuf_handle);
19477 ::CloseClipboard();
19478 return g.ClipboardHandlerData.Data;
19479}
19480
19481static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
19482{
19483 if (!::OpenClipboard(NULL))
19484 return;
19485 const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
19486 HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
19487 if (wbuf_handle == NULL)
19488 {
19489 ::CloseClipboard();
19490 return;
19491 }
19492 WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
19493 ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
19494 ::GlobalUnlock(wbuf_handle);
19495 ::EmptyClipboard();
19496 if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
19497 ::GlobalFree(wbuf_handle);
19498 ::CloseClipboard();
19499}
19500
19501#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
19502
19503#include <Carbon/Carbon.h> // Use old API to avoid need for separate .mm file
19504static PasteboardRef main_clipboard = 0;
19505
19506// OSX clipboard implementation
19507// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
19508static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
19509{
19510 if (!main_clipboard)
19511 PasteboardCreate(kPasteboardClipboard, &main_clipboard);
19512 PasteboardClear(main_clipboard);
19513 CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
19514 if (cf_data)
19515 {
19516 PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
19517 CFRelease(cf_data);
19518 }
19519}
19520
19521static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19522{
19523 ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19524 if (!main_clipboard)
19525 PasteboardCreate(kPasteboardClipboard, &main_clipboard);
19526 PasteboardSynchronize(main_clipboard);
19527
19528 ItemCount item_count = 0;
19529 PasteboardGetItemCount(main_clipboard, &item_count);
19530 for (ItemCount i = 0; i < item_count; i++)
19531 {
19532 PasteboardItemID item_id = 0;
19533 PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
19534 CFArrayRef flavor_type_array = 0;
19535 PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
19536 for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
19537 {
19538 CFDataRef cf_data;
19539 if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
19540 {
19541 g.ClipboardHandlerData.clear();
19542 int length = (int)CFDataGetLength(cf_data);
19543 g.ClipboardHandlerData.resize(length + 1);
19544 CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
19545 g.ClipboardHandlerData[length] = 0;
19546 CFRelease(cf_data);
19547 return g.ClipboardHandlerData.Data;
19548 }
19549 }
19550 }
19551 return NULL;
19552}
19553
19554#else
19555
19556// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
19557static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19558{
19559 ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19560 return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
19561}
19562
19563static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text)
19564{
19565 ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19566 g.ClipboardHandlerData.clear();
19567 const char* text_end = text + strlen(text);
19568 g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
19569 memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
19570 g.ClipboardHandlerData[(int)(text_end - text)] = 0;
19571}
19572
19573#endif
19574
19575// Win32 API IME support (for Asian languages, etc.)
19576#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
19577
19578#include <imm.h>
19579#ifdef _MSC_VER
19580#pragma comment(lib, "imm32")
19581#endif
19582
19583static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data)
19584{
19585 // Notify OS Input Method Editor of text input position
19586 HWND hwnd = (HWND)viewport->PlatformHandleRaw;
19587 if (hwnd == 0)
19588 return;
19589
19590 //::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);
19591 if (HIMC himc = ::ImmGetContext(hwnd))
19592 {
19593 COMPOSITIONFORM composition_form = {};
19594 composition_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
19595 composition_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
19596 composition_form.dwStyle = CFS_FORCE_POSITION;
19597 ::ImmSetCompositionWindow(himc, &composition_form);
19598 CANDIDATEFORM candidate_form = {};
19599 candidate_form.dwStyle = CFS_CANDIDATEPOS;
19600 candidate_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
19601 candidate_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
19602 ::ImmSetCandidateWindow(himc, &candidate_form);
19603 ::ImmReleaseContext(hwnd, himc);
19604 }
19605}
19606
19607#else
19608
19609static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport*, ImGuiPlatformImeData*) {}
19610
19611#endif
19612
19613//-----------------------------------------------------------------------------
19614// [SECTION] METRICS/DEBUGGER WINDOW
19615//-----------------------------------------------------------------------------
19616// - DebugRenderViewportThumbnail() [Internal]
19617// - RenderViewportsThumbnails() [Internal]
19618// - DebugTextEncoding()
19619// - MetricsHelpMarker() [Internal]
19620// - ShowFontAtlas() [Internal]
19621// - ShowMetricsWindow()
19622// - DebugNodeColumns() [Internal]
19623// - DebugNodeDockNode() [Internal]
19624// - DebugNodeDrawList() [Internal]
19625// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
19626// - DebugNodeFont() [Internal]
19627// - DebugNodeFontGlyph() [Internal]
19628// - DebugNodeStorage() [Internal]
19629// - DebugNodeTabBar() [Internal]
19630// - DebugNodeViewport() [Internal]
19631// - DebugNodeWindow() [Internal]
19632// - DebugNodeWindowSettings() [Internal]
19633// - DebugNodeWindowsList() [Internal]
19634// - DebugNodeWindowsListByBeginStackParent() [Internal]
19635//-----------------------------------------------------------------------------
19636
19637#ifndef IMGUI_DISABLE_DEBUG_TOOLS
19638
19639void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
19640{
19641 ImGuiContext& g = *GImGui;
19642 ImGuiWindow* window = g.CurrentWindow;
19643
19644 ImVec2 scale = bb.GetSize() / viewport->Size;
19645 ImVec2 off = bb.Min - viewport->Pos * scale;
19646 float alpha_mul = (viewport->Flags & ImGuiViewportFlags_IsMinimized) ? 0.30f : 1.00f;
19647 window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
19648 for (ImGuiWindow* thumb_window : g.Windows)
19649 {
19650 if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
19651 continue;
19652 if (thumb_window->Viewport != viewport)
19653 continue;
19654
19655 ImRect thumb_r = thumb_window->Rect();
19656 ImRect title_r = thumb_window->TitleBarRect();
19657 thumb_r = ImRect(ImTrunc(off + thumb_r.Min * scale), ImTrunc(off + thumb_r.Max * scale));
19658 title_r = ImRect(ImTrunc(off + title_r.Min * scale), ImTrunc(off + ImVec2(title_r.Max.x, title_r.Min.y + title_r.GetHeight() * 3.0f) * scale)); // Exaggerate title bar height
19659 thumb_r.ClipWithFull(bb);
19660 title_r.ClipWithFull(bb);
19661 const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
19662 window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));
19663 window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
19664 window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
19665 window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));
19666 }
19667 draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
19668 if (viewport->ID == g.DebugMetricsConfig.HighlightViewportID)
19669 window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
19670}
19671
19672static void RenderViewportsThumbnails()
19673{
19674 ImGuiContext& g = *GImGui;
19675 ImGuiWindow* window = g.CurrentWindow;
19676
19677 // Draw monitor and calculate their boundaries
19678 float SCALE = 1.0f / 8.0f;
19679 ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
19680 for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
19681 bb_full.Add(ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize));
19682 ImVec2 p = window->DC.CursorPos;
19683 ImVec2 off = p - bb_full.Min * SCALE;
19684 for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
19685 {
19686 ImRect monitor_draw_bb(off + (monitor.MainPos) * SCALE, off + (monitor.MainPos + monitor.MainSize) * SCALE);
19687 window->DrawList->AddRect(monitor_draw_bb.Min, monitor_draw_bb.Max, (g.DebugMetricsConfig.HighlightMonitorIdx == g.PlatformIO.Monitors.index_from_ptr(&monitor)) ? IM_COL32(255, 255, 0, 255) : ImGui::GetColorU32(ImGuiCol_Border), 4.0f);
19688 window->DrawList->AddRectFilled(monitor_draw_bb.Min, monitor_draw_bb.Max, ImGui::GetColorU32(ImGuiCol_Border, 0.10f), 4.0f);
19689 }
19690
19691 // Draw viewports
19692 for (ImGuiViewportP* viewport : g.Viewports)
19693 {
19694 ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
19695 ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
19696 }
19697 ImGui::Dummy(bb_full.GetSize() * SCALE);
19698}
19699
19700static int IMGUI_CDECL ViewportComparerByLastFocusedStampCount(const void* lhs, const void* rhs)
19701{
19702 const ImGuiViewportP* a = *(const ImGuiViewportP* const*)lhs;
19703 const ImGuiViewportP* b = *(const ImGuiViewportP* const*)rhs;
19704 return b->LastFocusedStampCount - a->LastFocusedStampCount;
19705}
19706
19707// Draw an arbitrary US keyboard layout to visualize translated keys
19708void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list)
19709{
19710 const float scale = ImGui::GetFontSize() / 13.0f;
19711 const ImVec2 key_size = ImVec2(35.0f, 35.0f) * scale;
19712 const float key_rounding = 3.0f * scale;
19713 const ImVec2 key_face_size = ImVec2(25.0f, 25.0f) * scale;
19714 const ImVec2 key_face_pos = ImVec2(5.0f, 3.0f) * scale;
19715 const float key_face_rounding = 2.0f * scale;
19716 const ImVec2 key_label_pos = ImVec2(7.0f, 4.0f) * scale;
19717 const ImVec2 key_step = ImVec2(key_size.x - 1.0f, key_size.y - 1.0f);
19718 const float key_row_offset = 9.0f * scale;
19719
19720 ImVec2 board_min = GetCursorScreenPos();
19721 ImVec2 board_max = ImVec2(board_min.x + 3 * key_step.x + 2 * key_row_offset + 10.0f, board_min.y + 3 * key_step.y + 10.0f);
19722 ImVec2 start_pos = ImVec2(board_min.x + 5.0f - key_step.x, board_min.y);
19723
19724 struct KeyLayoutData { int Row, Col; const char* Label; ImGuiKey Key; };
19725 const KeyLayoutData keys_to_display[] =
19726 {
19727 { 0, 0, "", ImGuiKey_Tab }, { 0, 1, "Q", ImGuiKey_Q }, { 0, 2, "W", ImGuiKey_W }, { 0, 3, "E", ImGuiKey_E }, { 0, 4, "R", ImGuiKey_R },
19728 { 1, 0, "", ImGuiKey_CapsLock }, { 1, 1, "A", ImGuiKey_A }, { 1, 2, "S", ImGuiKey_S }, { 1, 3, "D", ImGuiKey_D }, { 1, 4, "F", ImGuiKey_F },
19729 { 2, 0, "", ImGuiKey_LeftShift },{ 2, 1, "Z", ImGuiKey_Z }, { 2, 2, "X", ImGuiKey_X }, { 2, 3, "C", ImGuiKey_C }, { 2, 4, "V", ImGuiKey_V }
19730 };
19731
19732 // Elements rendered manually via ImDrawList API are not clipped automatically.
19733 // While not strictly necessary, here IsItemVisible() is used to avoid rendering these shapes when they are out of view.
19734 Dummy(board_max - board_min);
19735 if (!IsItemVisible())
19736 return;
19737 draw_list->PushClipRect(board_min, board_max, true);
19738 for (int n = 0; n < IM_ARRAYSIZE(keys_to_display); n++)
19739 {
19740 const KeyLayoutData* key_data = &keys_to_display[n];
19741 ImVec2 key_min = ImVec2(start_pos.x + key_data->Col * key_step.x + key_data->Row * key_row_offset, start_pos.y + key_data->Row * key_step.y);
19742 ImVec2 key_max = key_min + key_size;
19743 draw_list->AddRectFilled(key_min, key_max, IM_COL32(204, 204, 204, 255), key_rounding);
19744 draw_list->AddRect(key_min, key_max, IM_COL32(24, 24, 24, 255), key_rounding);
19745 ImVec2 face_min = ImVec2(key_min.x + key_face_pos.x, key_min.y + key_face_pos.y);
19746 ImVec2 face_max = ImVec2(face_min.x + key_face_size.x, face_min.y + key_face_size.y);
19747 draw_list->AddRect(face_min, face_max, IM_COL32(193, 193, 193, 255), key_face_rounding, ImDrawFlags_None, 2.0f);
19748 draw_list->AddRectFilled(face_min, face_max, IM_COL32(252, 252, 252, 255), key_face_rounding);
19749 ImVec2 label_min = ImVec2(key_min.x + key_label_pos.x, key_min.y + key_label_pos.y);
19750 draw_list->AddText(label_min, IM_COL32(64, 64, 64, 255), key_data->Label);
19751 if (IsKeyDown(key_data->Key))
19752 draw_list->AddRectFilled(key_min, key_max, IM_COL32(255, 0, 0, 128), key_rounding);
19753 }
19754 draw_list->PopClipRect();
19755}
19756
19757// Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct.
19758void ImGui::DebugTextEncoding(const char* str)
19759{
19760 Text("Text: \"%s\"", str);
19761 if (!BeginTable("##DebugTextEncoding", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable))
19762 return;
19763 TableSetupColumn("Offset");
19764 TableSetupColumn("UTF-8");
19765 TableSetupColumn("Glyph");
19766 TableSetupColumn("Codepoint");
19767 TableHeadersRow();
19768 for (const char* p = str; *p != 0; )
19769 {
19770 unsigned int c;
19771 const int c_utf8_len = ImTextCharFromUtf8(&c, p, NULL);
19772 TableNextColumn();
19773 Text("%d", (int)(p - str));
19774 TableNextColumn();
19775 for (int byte_index = 0; byte_index < c_utf8_len; byte_index++)
19776 {
19777 if (byte_index > 0)
19778 SameLine();
19779 Text("0x%02X", (int)(unsigned char)p[byte_index]);
19780 }
19781 TableNextColumn();
19782 if (GetFont()->FindGlyphNoFallback((ImWchar)c))
19783 TextUnformatted(p, p + c_utf8_len);
19784 else
19785 TextUnformatted((c == IM_UNICODE_CODEPOINT_INVALID) ? "[invalid]" : "[missing]");
19786 TableNextColumn();
19787 Text("U+%04X", (int)c);
19788 p += c_utf8_len;
19789 }
19790 EndTable();
19791}
19792
19793static void DebugFlashStyleColorStop()
19794{
19795 ImGuiContext& g = *GImGui;
19796 if (g.DebugFlashStyleColorIdx != ImGuiCol_COUNT)
19797 g.Style.Colors[g.DebugFlashStyleColorIdx] = g.DebugFlashStyleColorBackup;
19798 g.DebugFlashStyleColorIdx = ImGuiCol_COUNT;
19799}
19800
19801// Flash a given style color for some + inhibit modifications of this color via PushStyleColor() calls.
19802void ImGui::DebugFlashStyleColor(ImGuiCol idx)
19803{
19804 ImGuiContext& g = *GImGui;
19805 DebugFlashStyleColorStop();
19806 g.DebugFlashStyleColorTime = 0.5f;
19807 g.DebugFlashStyleColorIdx = idx;
19808 g.DebugFlashStyleColorBackup = g.Style.Colors[idx];
19809}
19810
19811void ImGui::UpdateDebugToolFlashStyleColor()
19812{
19813 ImGuiContext& g = *GImGui;
19814 if (g.DebugFlashStyleColorTime <= 0.0f)
19815 return;
19816 ColorConvertHSVtoRGB(cosf(g.DebugFlashStyleColorTime * 6.0f) * 0.5f + 0.5f, 0.5f, 0.5f, g.Style.Colors[g.DebugFlashStyleColorIdx].x, g.Style.Colors[g.DebugFlashStyleColorIdx].y, g.Style.Colors[g.DebugFlashStyleColorIdx].z);
19817 g.Style.Colors[g.DebugFlashStyleColorIdx].w = 1.0f;
19818 if ((g.DebugFlashStyleColorTime -= g.IO.DeltaTime) <= 0.0f)
19819 DebugFlashStyleColorStop();
19820}
19821
19822// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
19823static void MetricsHelpMarker(const char* desc)
19824{
19825 ImGui::TextDisabled("(?)");
19826 if (ImGui::BeginItemTooltip())
19827 {
19828 ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
19830 ImGui::PopTextWrapPos();
19831 ImGui::EndTooltip();
19832 }
19833}
19834
19835// [DEBUG] List fonts in a font atlas and display its texture
19836void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
19837{
19838 for (ImFont* font : atlas->Fonts)
19839 {
19840 PushID(font);
19841 DebugNodeFont(font);
19842 PopID();
19843 }
19844 if (TreeNode("Font Atlas", "Font Atlas (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
19845 {
19846 ImGuiContext& g = *GImGui;
19847 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
19848 Checkbox("Tint with Text Color", &cfg->ShowAtlasTintedWithTextColor); // Using text color ensure visibility of core atlas data, but will alter custom colored icons
19849 ImVec4 tint_col = cfg->ShowAtlasTintedWithTextColor ? GetStyleColorVec4(ImGuiCol_Text) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
19850 ImVec4 border_col = GetStyleColorVec4(ImGuiCol_Border);
19851 Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), tint_col, border_col);
19852 TreePop();
19853 }
19854}
19855
19856void ImGui::ShowMetricsWindow(bool* p_open)
19857{
19858 ImGuiContext& g = *GImGui;
19859 ImGuiIO& io = g.IO;
19860 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
19861 if (cfg->ShowDebugLog)
19862 ShowDebugLogWindow(&cfg->ShowDebugLog);
19863 if (cfg->ShowIDStackTool)
19864 ShowIDStackToolWindow(&cfg->ShowIDStackTool);
19865
19866 if (!Begin("Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
19867 {
19868 End();
19869 return;
19870 }
19871
19872 // [DEBUG] Clear debug breaks hooks after exactly one cycle.
19873 DebugBreakClearData();
19874
19875 // Basic info
19876 Text("Dear ImGui %s", GetVersion());
19877 Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
19878 Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
19879 Text("%d visible windows, %d current allocations", io.MetricsRenderWindows, g.DebugAllocInfo.TotalAllocCount - g.DebugAllocInfo.TotalFreeCount);
19880 //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
19881
19882 Separator();
19883
19884 // Debugging enums
19885 enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
19886 const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
19887 enum { TRT_OuterRect, TRT_InnerRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsWorkRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentFrozen, TRT_ColumnsContentUnfrozen, TRT_Count }; // Tables Rect Type
19888 const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
19889 if (cfg->ShowWindowsRectsType < 0)
19890 cfg->ShowWindowsRectsType = WRT_WorkRect;
19891 if (cfg->ShowTablesRectsType < 0)
19892 cfg->ShowTablesRectsType = TRT_WorkRect;
19893
19894 struct Funcs
19895 {
19896 static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
19897 {
19898 ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); // Always using last submitted instance
19899 if (rect_type == TRT_OuterRect) { return table->OuterRect; }
19900 else if (rect_type == TRT_InnerRect) { return table->InnerRect; }
19901 else if (rect_type == TRT_WorkRect) { return table->WorkRect; }
19902 else if (rect_type == TRT_HostClipRect) { return table->HostClipRect; }
19903 else if (rect_type == TRT_InnerClipRect) { return table->InnerClipRect; }
19904 else if (rect_type == TRT_BackgroundClipRect) { return table->BgClipRect; }
19905 else if (rect_type == TRT_ColumnsRect) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table_instance->LastOuterHeight); }
19906 else if (rect_type == TRT_ColumnsWorkRect) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->WorkRect.Min.y, c->WorkMaxX, table->WorkRect.Max.y); }
19907 else if (rect_type == TRT_ColumnsClipRect) { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
19908 else if (rect_type == TRT_ColumnsContentHeadersUsed){ ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersUsed, table->InnerClipRect.Min.y + table_instance->LastTopHeadersRowHeight); } // Note: y1/y2 not always accurate
19909 else if (rect_type == TRT_ColumnsContentHeadersIdeal){ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersIdeal, table->InnerClipRect.Min.y + table_instance->LastTopHeadersRowHeight); }
19910 else if (rect_type == TRT_ColumnsContentFrozen) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXFrozen, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight); }
19911 else if (rect_type == TRT_ColumnsContentUnfrozen) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); }
19912 IM_ASSERT(0);
19913 return ImRect();
19914 }
19915
19916 static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
19917 {
19918 if (rect_type == WRT_OuterRect) { return window->Rect(); }
19919 else if (rect_type == WRT_OuterRectClipped) { return window->OuterRectClipped; }
19920 else if (rect_type == WRT_InnerRect) { return window->InnerRect; }
19921 else if (rect_type == WRT_InnerClipRect) { return window->InnerClipRect; }
19922 else if (rect_type == WRT_WorkRect) { return window->WorkRect; }
19923 else if (rect_type == WRT_Content) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
19924 else if (rect_type == WRT_ContentIdeal) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
19925 else if (rect_type == WRT_ContentRegionRect) { return window->ContentRegionRect; }
19926 IM_ASSERT(0);
19927 return ImRect();
19928 }
19929 };
19930
19931 // Tools
19932 if (TreeNode("Tools"))
19933 {
19934 // Debug Break features
19935 // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
19936 SeparatorTextEx(0, "Debug breaks", NULL, CalcTextSize("(?)").x + g.Style.SeparatorTextPadding.x);
19937 SameLine();
19938 MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
19939 if (Checkbox("Show Item Picker", &g.DebugItemPickerActive) && g.DebugItemPickerActive)
19940 DebugStartItemPicker();
19941 Checkbox("Show \"Debug Break\" buttons in other sections (io.ConfigDebugIsDebuggerPresent)", &g.IO.ConfigDebugIsDebuggerPresent);
19942
19943 SeparatorText("Visualize");
19944
19945 Checkbox("Show Debug Log", &cfg->ShowDebugLog);
19946 SameLine();
19947 MetricsHelpMarker("You can also call ImGui::ShowDebugLogWindow() from your code.");
19948
19949 Checkbox("Show ID Stack Tool", &cfg->ShowIDStackTool);
19950 SameLine();
19951 MetricsHelpMarker("You can also call ImGui::ShowIDStackToolWindow() from your code.");
19952
19953 Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
19954 Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
19955 SameLine();
19956 SetNextItemWidth(GetFontSize() * 12);
19957 cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
19958 if (cfg->ShowWindowsRects && g.NavWindow != NULL)
19959 {
19960 BulletText("'%s':", g.NavWindow->Name);
19961 Indent();
19962 for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
19963 {
19964 ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
19965 Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
19966 }
19967 Unindent();
19968 }
19969
19970 Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
19971 SameLine();
19972 SetNextItemWidth(GetFontSize() * 12);
19973 cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
19974 if (cfg->ShowTablesRects && g.NavWindow != NULL)
19975 {
19976 for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
19977 {
19978 ImGuiTable* table = g.Tables.TryGetMapData(table_n);
19979 if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
19980 continue;
19981
19982 BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
19983 if (IsItemHovered())
19984 GetForegroundDrawList()->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
19985 Indent();
19986 char buf[128];
19987 for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
19988 {
19989 if (rect_n >= TRT_ColumnsRect)
19990 {
19991 if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
19992 continue;
19993 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
19994 {
19995 ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
19996 ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]);
19997 Selectable(buf);
19998 if (IsItemHovered())
19999 GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
20000 }
20001 }
20002 else
20003 {
20004 ImRect r = Funcs::GetTableRect(table, rect_n, -1);
20005 ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]);
20006 Selectable(buf);
20007 if (IsItemHovered())
20008 GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
20009 }
20010 }
20011 Unindent();
20012 }
20013 }
20014 Checkbox("Show groups rectangles", &g.DebugShowGroupRects); // Storing in context as this is used by group code and prefers to be in hot-data
20015
20016 SeparatorText("Validate");
20017
20018 Checkbox("Debug Begin/BeginChild return value", &io.ConfigDebugBeginReturnValueLoop);
20019 SameLine();
20020 MetricsHelpMarker("Some calls to Begin()/BeginChild() will return false.\n\nWill cycle through window depths then repeat. Windows should be flickering while running.");
20021
20022 Checkbox("UTF-8 Encoding viewer", &cfg->ShowTextEncodingViewer);
20023 SameLine();
20024 MetricsHelpMarker("You can also call ImGui::DebugTextEncoding() from your code with a given string to test that your UTF-8 encoding settings are correct.");
20025 if (cfg->ShowTextEncodingViewer)
20026 {
20027 static char buf[64] = "";
20028 SetNextItemWidth(-FLT_MIN);
20029 InputText("##DebugTextEncodingBuf", buf, IM_ARRAYSIZE(buf));
20030 if (buf[0] != 0)
20031 DebugTextEncoding(buf);
20032 }
20033
20034 TreePop();
20035 }
20036
20037 // Windows
20038 if (TreeNode("Windows", "Windows (%d)", g.Windows.Size))
20039 {
20040 //SetNextItemOpen(true, ImGuiCond_Once);
20041 DebugNodeWindowsList(&g.Windows, "By display order");
20042 DebugNodeWindowsList(&g.WindowsFocusOrder, "By focus order (root windows)");
20043 if (TreeNode("By submission order (begin stack)"))
20044 {
20045 // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!
20046 ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;
20047 temp_buffer.resize(0);
20048 for (ImGuiWindow* window : g.Windows)
20049 if (window->LastFrameActive + 1 >= g.FrameCount)
20050 temp_buffer.push_back(window);
20051 struct Func { static int IMGUI_CDECL WindowComparerByBeginOrder(const void* lhs, const void* rhs) { return ((int)(*(const ImGuiWindow* const *)lhs)->BeginOrderWithinContext - (*(const ImGuiWindow* const*)rhs)->BeginOrderWithinContext); } };
20052 ImQsort(temp_buffer.Data, (size_t)temp_buffer.Size, sizeof(ImGuiWindow*), Func::WindowComparerByBeginOrder);
20053 DebugNodeWindowsListByBeginStackParent(temp_buffer.Data, temp_buffer.Size, NULL);
20054 TreePop();
20055 }
20056
20057 TreePop();
20058 }
20059
20060 // DrawLists
20061 int drawlist_count = 0;
20062 for (ImGuiViewportP* viewport : g.Viewports)
20063 drawlist_count += viewport->DrawDataP.CmdLists.Size;
20064 if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count))
20065 {
20066 Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
20067 Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
20068 for (ImGuiViewportP* viewport : g.Viewports)
20069 {
20070 bool viewport_has_drawlist = false;
20071 for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
20072 {
20073 if (!viewport_has_drawlist)
20074 Text("Active DrawLists in Viewport #%d, ID: 0x%08X", viewport->Idx, viewport->ID);
20075 viewport_has_drawlist = true;
20076 DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
20077 }
20078 }
20079 TreePop();
20080 }
20081
20082 // Viewports
20083 if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size))
20084 {
20085 cfg->HighlightMonitorIdx = -1;
20086 bool open = TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size);
20087 SameLine();
20088 MetricsHelpMarker("Dear ImGui uses monitor data:\n- to query DPI settings on a per monitor basis\n- to position popup/tooltips so they don't straddle monitors.");
20089 if (open)
20090 {
20091 for (int i = 0; i < g.PlatformIO.Monitors.Size; i++)
20092 {
20093 const ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[i];
20094 BulletText("Monitor #%d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)",
20095 i, mon.DpiScale * 100.0f,
20096 mon.MainPos.x, mon.MainPos.y, mon.MainPos.x + mon.MainSize.x, mon.MainPos.y + mon.MainSize.y, mon.MainSize.x, mon.MainSize.y,
20097 mon.WorkPos.x, mon.WorkPos.y, mon.WorkPos.x + mon.WorkSize.x, mon.WorkPos.y + mon.WorkSize.y, mon.WorkSize.x, mon.WorkSize.y);
20098 if (IsItemHovered())
20099 cfg->HighlightMonitorIdx = i;
20100 }
20101 TreePop();
20102 }
20103
20104 SetNextItemOpen(true, ImGuiCond_Once);
20105 if (TreeNode("Windows Minimap"))
20106 {
20107 RenderViewportsThumbnails();
20108 TreePop();
20109 }
20110 cfg->HighlightViewportID = 0;
20111
20112 BulletText("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport ? g.MouseViewport->ID : 0, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
20113 if (TreeNode("Inferred Z order (front-to-back)"))
20114 {
20115 static ImVector<ImGuiViewportP*> viewports;
20116 viewports.resize(g.Viewports.Size);
20117 memcpy(viewports.Data, g.Viewports.Data, g.Viewports.size_in_bytes());
20118 if (viewports.Size > 1)
20119 ImQsort(viewports.Data, viewports.Size, sizeof(ImGuiViewport*), ViewportComparerByLastFocusedStampCount);
20120 for (ImGuiViewportP* viewport : viewports)
20121 {
20122 BulletText("Viewport #%d, ID: 0x%08X, LastFocused = %08d, PlatformFocused = %s, Window: \"%s\"",
20123 viewport->Idx, viewport->ID, viewport->LastFocusedStampCount,
20124 (g.PlatformIO.Platform_GetWindowFocus && viewport->PlatformWindowCreated) ? (g.PlatformIO.Platform_GetWindowFocus(viewport) ? "1" : "0") : "N/A",
20125 viewport->Window ? viewport->Window->Name : "N/A");
20126 if (IsItemHovered())
20127 cfg->HighlightViewportID = viewport->ID;
20128 }
20129 TreePop();
20130 }
20131
20132 for (ImGuiViewportP* viewport : g.Viewports)
20133 DebugNodeViewport(viewport);
20134 TreePop();
20135 }
20136
20137 // Details for Popups
20138 if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
20139 {
20140 for (const ImGuiPopupData& popup_data : g.OpenPopupStack)
20141 {
20142 // As it's difficult to interact with tree nodes while popups are open, we display everything inline.
20143 ImGuiWindow* window = popup_data.Window;
20144 BulletText("PopupID: %08x, Window: '%s' (%s%s), RestoreNavWindow '%s', ParentWindow '%s'",
20145 popup_data.PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? "Child;" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? "Menu;" : "",
20146 popup_data.RestoreNavWindow ? popup_data.RestoreNavWindow->Name : "NULL", window && window->ParentWindow ? window->ParentWindow->Name : "NULL");
20147 }
20148 TreePop();
20149 }
20150
20151 // Details for TabBars
20152 if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetAliveCount()))
20153 {
20154 for (int n = 0; n < g.TabBars.GetMapSize(); n++)
20155 if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
20156 {
20157 PushID(tab_bar);
20158 DebugNodeTabBar(tab_bar, "TabBar");
20159 PopID();
20160 }
20161 TreePop();
20162 }
20163
20164 // Details for Tables
20165 if (TreeNode("Tables", "Tables (%d)", g.Tables.GetAliveCount()))
20166 {
20167 for (int n = 0; n < g.Tables.GetMapSize(); n++)
20168 if (ImGuiTable* table = g.Tables.TryGetMapData(n))
20169 DebugNodeTable(table);
20170 TreePop();
20171 }
20172
20173 // Details for Fonts
20174 ImFontAtlas* atlas = g.IO.Fonts;
20175 if (TreeNode("Fonts", "Fonts (%d)", atlas->Fonts.Size))
20176 {
20177 ShowFontAtlas(atlas);
20178 TreePop();
20179 }
20180
20181 // Details for InputText
20182 if (TreeNode("InputText"))
20183 {
20184 DebugNodeInputTextState(&g.InputTextState);
20185 TreePop();
20186 }
20187
20188 // Details for TypingSelect
20189 if (TreeNode("TypingSelect", "TypingSelect (%d)", g.TypingSelectState.SearchBuffer[0] != 0 ? 1 : 0))
20190 {
20191 DebugNodeTypingSelectState(&g.TypingSelectState);
20192 TreePop();
20193 }
20194
20195 // Details for Docking
20196#ifdef IMGUI_HAS_DOCK
20197 if (TreeNode("Docking"))
20198 {
20199 static bool root_nodes_only = true;
20200 ImGuiDockContext* dc = &g.DockContext;
20201 Checkbox("List root nodes", &root_nodes_only);
20202 Checkbox("Ctrl shows window dock info", &cfg->ShowDockingNodes);
20203 if (SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); }
20204 SameLine();
20205 if (SmallButton("Rebuild all")) { dc->WantFullRebuild = true; }
20206 for (int n = 0; n < dc->Nodes.Data.Size; n++)
20207 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
20208 if (!root_nodes_only || node->IsRootNode())
20209 DebugNodeDockNode(node, "Node");
20210 TreePop();
20211 }
20212#endif // #ifdef IMGUI_HAS_DOCK
20213
20214 // Settings
20215 if (TreeNode("Settings"))
20216 {
20217 if (SmallButton("Clear"))
20218 ClearIniSettings();
20219 SameLine();
20220 if (SmallButton("Save to memory"))
20221 SaveIniSettingsToMemory();
20222 SameLine();
20223 if (SmallButton("Save to disk"))
20224 SaveIniSettingsToDisk(g.IO.IniFilename);
20225 SameLine();
20226 if (g.IO.IniFilename)
20227 Text("\"%s\"", g.IO.IniFilename);
20228 else
20229 TextUnformatted("<NULL>");
20230 Checkbox("io.ConfigDebugIniSettings", &io.ConfigDebugIniSettings);
20231 Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
20232 if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
20233 {
20234 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
20235 BulletText("\"%s\"", handler.TypeName);
20236 TreePop();
20237 }
20238 if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
20239 {
20240 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
20241 DebugNodeWindowSettings(settings);
20242 TreePop();
20243 }
20244
20245 if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
20246 {
20247 for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
20248 DebugNodeTableSettings(settings);
20249 TreePop();
20250 }
20251
20252#ifdef IMGUI_HAS_DOCK
20253 if (TreeNode("SettingsDocking", "Settings packed data: Docking"))
20254 {
20255 ImGuiDockContext* dc = &g.DockContext;
20256 Text("In SettingsWindows:");
20257 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
20258 if (settings->DockId != 0)
20259 BulletText("Window '%s' -> DockId %08X DockOrder=%d", settings->GetName(), settings->DockId, settings->DockOrder);
20260 Text("In SettingsNodes:");
20261 for (int n = 0; n < dc->NodesSettings.Size; n++)
20262 {
20263 ImGuiDockNodeSettings* settings = &dc->NodesSettings[n];
20264 const char* selected_tab_name = NULL;
20265 if (settings->SelectedTabId)
20266 {
20267 if (ImGuiWindow* window = FindWindowByID(settings->SelectedTabId))
20268 selected_tab_name = window->Name;
20269 else if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->SelectedTabId))
20270 selected_tab_name = window_settings->GetName();
20271 }
20272 BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedTabId, selected_tab_name ? selected_tab_name : settings->SelectedTabId ? "N/A" : "");
20273 }
20274 TreePop();
20275 }
20276#endif // #ifdef IMGUI_HAS_DOCK
20277
20278 if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
20279 {
20280 InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
20281 TreePop();
20282 }
20283 TreePop();
20284 }
20285
20286 // Settings
20287 if (TreeNode("Memory allocations"))
20288 {
20289 ImGuiDebugAllocInfo* info = &g.DebugAllocInfo;
20290 Text("%d current allocations", info->TotalAllocCount - info->TotalFreeCount);
20291 if (SmallButton("GC now")) { g.GcCompactAll = true; }
20292 Text("Recent frames with allocations:");
20293 int buf_size = IM_ARRAYSIZE(info->LastEntriesBuf);
20294 for (int n = buf_size - 1; n >= 0; n--)
20295 {
20296 ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[(info->LastEntriesIdx - n + buf_size) % buf_size];
20297 BulletText("Frame %06d: %+3d ( %2d malloc, %2d free )%s", entry->FrameCount, entry->AllocCount - entry->FreeCount, entry->AllocCount, entry->FreeCount, (n == 0) ? " (most recent)" : "");
20298 }
20299 TreePop();
20300 }
20301
20302 if (TreeNode("Inputs"))
20303 {
20304 Text("KEYBOARD/GAMEPAD/MOUSE KEYS");
20305 {
20306 // We iterate both legacy native range and named ImGuiKey ranges, which is a little odd but this allows displaying the data for old/new backends.
20307 // User code should never have to go through such hoops! You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END.
20308 Indent();
20309#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
20310 struct funcs { static bool IsLegacyNativeDupe(ImGuiKey) { return false; } };
20311#else
20312 struct funcs { static bool IsLegacyNativeDupe(ImGuiKey key) { return key >= 0 && key < 512 && GetIO().KeyMap[key] != -1; } }; // Hide Native<>ImGuiKey duplicates when both exists in the array
20313 //Text("Legacy raw:"); for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key++) { if (io.KeysDown[key]) { SameLine(); Text("\"%s\" %d", GetKeyName(key), key); } }
20314#endif
20315 Text("Keys down:"); for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyDown(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text("(%.02f)", GetKeyData(key)->DownDuration); }
20316 Text("Keys pressed:"); for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyPressed(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
20317 Text("Keys released:"); for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyReleased(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
20318 Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
20319 Text("Chars queue:"); for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; SameLine(); Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.
20320 DebugRenderKeyboardPreview(GetWindowDrawList());
20321 Unindent();
20322 }
20323
20324 Text("MOUSE STATE");
20325 {
20326 Indent();
20327 if (IsMousePosValid())
20328 Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
20329 else
20330 Text("Mouse pos: <INVALID>");
20331 Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y);
20332 int count = IM_ARRAYSIZE(io.MouseDown);
20333 Text("Mouse down:"); for (int i = 0; i < count; i++) if (IsMouseDown(i)) { SameLine(); Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); }
20334 Text("Mouse clicked:"); for (int i = 0; i < count; i++) if (IsMouseClicked(i)) { SameLine(); Text("b%d (%d)", i, io.MouseClickedCount[i]); }
20335 Text("Mouse released:"); for (int i = 0; i < count; i++) if (IsMouseReleased(i)) { SameLine(); Text("b%d", i); }
20336 Text("Mouse wheel: %.1f", io.MouseWheel);
20337 Text("MouseStationaryTimer: %.2f", g.MouseStationaryTimer);
20338 Text("Mouse source: %s", GetMouseSourceName(io.MouseSource));
20339 Text("Pen Pressure: %.1f", io.PenPressure); // Note: currently unused
20340 Unindent();
20341 }
20342
20343 Text("MOUSE WHEELING");
20344 {
20345 Indent();
20346 Text("WheelingWindow: '%s'", g.WheelingWindow ? g.WheelingWindow->Name : "NULL");
20347 Text("WheelingWindowReleaseTimer: %.2f", g.WheelingWindowReleaseTimer);
20348 Text("WheelingAxisAvg[] = { %.3f, %.3f }, Main Axis: %s", g.WheelingAxisAvg.x, g.WheelingAxisAvg.y, (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? "X" : (g.WheelingAxisAvg.x < g.WheelingAxisAvg.y) ? "Y" : "<none>");
20349 Unindent();
20350 }
20351
20352 Text("KEY OWNERS");
20353 {
20354 Indent();
20355 if (BeginChild("##owners", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings))
20356 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
20357 {
20358 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
20359 if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
20360 continue;
20361 Text("%s: 0x%08X%s", GetKeyName(key), owner_data->OwnerCurr,
20362 owner_data->LockUntilRelease ? " LockUntilRelease" : owner_data->LockThisFrame ? " LockThisFrame" : "");
20363 DebugLocateItemOnHover(owner_data->OwnerCurr);
20364 }
20365 EndChild();
20366 Unindent();
20367 }
20368 Text("SHORTCUT ROUTING");
20369 SameLine();
20370 MetricsHelpMarker("Declared shortcut routes automatically set key owner when mods matches.");
20371 {
20372 Indent();
20373 if (BeginChild("##routes", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings))
20374 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
20375 {
20376 ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
20377 for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; )
20378 {
20379 ImGuiKeyRoutingData* routing_data = &rt->Entries[idx];
20380 ImGuiKeyChord key_chord = key | routing_data->Mods;
20381 Text("%s: 0x%08X (scored %d)", GetKeyChordName(key_chord), routing_data->RoutingCurr, routing_data->RoutingCurrScore);
20382 DebugLocateItemOnHover(routing_data->RoutingCurr);
20383 if (g.IO.ConfigDebugIsDebuggerPresent)
20384 {
20385 SameLine();
20386 if (DebugBreakButton("**DebugBreak**", "in SetShortcutRouting() for this KeyChord"))
20387 g.DebugBreakInShortcutRouting = key_chord;
20388 }
20389 idx = routing_data->NextEntryIndex;
20390 }
20391 }
20392 EndChild();
20393 Text("(ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: 0x%X)", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
20394 Unindent();
20395 }
20396 TreePop();
20397 }
20398
20399 if (TreeNode("Internal state"))
20400 {
20401 Text("WINDOWING");
20402 Indent();
20403 Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
20404 Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindowDockTree->Name : "NULL");
20405 Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
20406 Text("HoveredDockNode: 0x%08X", g.DebugHoveredDockNode ? g.DebugHoveredDockNode->ID : 0);
20407 Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
20408 Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
20409 Unindent();
20410
20411 Text("ITEMS");
20412 Indent();
20413 Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(g.ActiveIdSource));
20414 DebugLocateItemOnHover(g.ActiveId);
20415 Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
20416 Text("ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: %X", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
20417 Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame
20418 Text("HoverItemDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverItemDelayId, g.HoverItemDelayTimer, g.HoverItemDelayClearTimer);
20419 Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
20420 DebugLocateItemOnHover(g.DragDropPayload.SourceId);
20421 Unindent();
20422
20423 Text("NAV,FOCUS");
20424 Indent();
20425 Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
20426 Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
20427 DebugLocateItemOnHover(g.NavId);
20428 Text("NavInputSource: %s", GetInputSourceName(g.NavInputSource));
20429 Text("NavLastValidSelectionUserData = %" IM_PRId64 " (0x%" IM_PRIX64 ")", g.NavLastValidSelectionUserData, g.NavLastValidSelectionUserData);
20430 Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
20431 Text("NavActivateId/DownId/PressedId: %08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId);
20432 Text("NavActivateFlags: %04X", g.NavActivateFlags);
20433 Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
20434 Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
20435 Text("NavFocusRoute[] = ");
20436 for (int path_n = g.NavFocusRoute.Size - 1; path_n >= 0; path_n--)
20437 {
20438 const ImGuiFocusScopeData& focus_scope = g.NavFocusRoute[path_n];
20439 SameLine(0.0f, 0.0f);
20440 Text("0x%08X/", focus_scope.ID);
20441 SetItemTooltip("In window \"%s\"", FindWindowByID(focus_scope.WindowID)->Name);
20442 }
20443 Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
20444 Unindent();
20445
20446 TreePop();
20447 }
20448
20449 // Overlay: Display windows Rectangles and Begin Order
20450 if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
20451 {
20452 for (ImGuiWindow* window : g.Windows)
20453 {
20454 if (!window->WasActive)
20455 continue;
20456 ImDrawList* draw_list = GetForegroundDrawList(window);
20457 if (cfg->ShowWindowsRects)
20458 {
20459 ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
20460 draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
20461 }
20462 if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
20463 {
20464 char buf[32];
20465 ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
20466 float font_size = GetFontSize();
20467 draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
20468 draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
20469 }
20470 }
20471 }
20472
20473 // Overlay: Display Tables Rectangles
20474 if (cfg->ShowTablesRects)
20475 {
20476 for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
20477 {
20478 ImGuiTable* table = g.Tables.TryGetMapData(table_n);
20479 if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
20480 continue;
20481 ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
20482 if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
20483 {
20484 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
20485 {
20486 ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
20487 ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
20488 float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
20489 draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness);
20490 }
20491 }
20492 else
20493 {
20494 ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
20495 draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
20496 }
20497 }
20498 }
20499
20500#ifdef IMGUI_HAS_DOCK
20501 // Overlay: Display Docking info
20502 if (cfg->ShowDockingNodes && g.IO.KeyCtrl && g.DebugHoveredDockNode)
20503 {
20504 char buf[64] = "";
20505 char* p = buf;
20506 ImGuiDockNode* node = g.DebugHoveredDockNode;
20507 ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
20508 p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : "");
20509 p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId);
20510 p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y);
20511 p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y);
20512 int depth = DockNodeGetDepth(node);
20513 overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255));
20514 ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth;
20515 overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255));
20516 overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf);
20517 }
20518#endif // #ifdef IMGUI_HAS_DOCK
20519
20520 End();
20521}
20522
20523void ImGui::DebugBreakClearData()
20524{
20525 // Those fields are scattered in their respective subsystem to stay in hot-data locations
20526 ImGuiContext& g = *GImGui;
20527 g.DebugBreakInWindow = 0;
20528 g.DebugBreakInTable = 0;
20529 g.DebugBreakInShortcutRouting = ImGuiKey_None;
20530}
20531
20532void ImGui::DebugBreakButtonTooltip(bool keyboard_only, const char* description_of_location)
20533{
20534 if (!BeginItemTooltip())
20535 return;
20536 Text("To call IM_DEBUG_BREAK() %s:", description_of_location);
20537 Separator();
20538 TextUnformatted(keyboard_only ? "- Press 'Pause/Break' on keyboard." : "- Press 'Pause/Break' on keyboard.\n- or Click (may alter focus/active id).\n- or navigate using keyboard and press space.");
20539 Separator();
20540 TextUnformatted("Choose one way that doesn't interfere with what you are trying to debug!\nYou need a debugger attached or this will crash!");
20541 EndTooltip();
20542}
20543
20544// Special button that doesn't take focus, doesn't take input owner, and can be activated without a click etc.
20545// In order to reduce interferences with the contents we are trying to debug into.
20546bool ImGui::DebugBreakButton(const char* label, const char* description_of_location)
20547{
20548 ImGuiWindow* window = GetCurrentWindow();
20549 if (window->SkipItems)
20550 return false;
20551
20552 ImGuiContext& g = *GImGui;
20553 const ImGuiID id = window->GetID(label);
20554 const ImVec2 label_size = CalcTextSize(label, NULL, true);
20555 ImVec2 pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrLineTextBaseOffset);
20556 ImVec2 size = ImVec2(label_size.x + g.Style.FramePadding.x * 2.0f, label_size.y);
20557
20558 const ImRect bb(pos, pos + size);
20559 ItemSize(size, 0.0f);
20560 if (!ItemAdd(bb, id))
20561 return false;
20562
20563 // WE DO NOT USE ButtonEx() or ButtonBehavior() in order to reduce our side-effects.
20564 bool hovered = ItemHoverable(bb, id, g.CurrentItemFlags);
20565 bool pressed = hovered && (IsKeyChordPressed(g.DebugBreakKeyChord) || IsMouseClicked(0) || g.NavActivateId == id);
20566 DebugBreakButtonTooltip(false, description_of_location);
20567
20568 ImVec4 col4f = GetStyleColorVec4(hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
20569 ImVec4 hsv;
20570 ColorConvertRGBtoHSV(col4f.x, col4f.y, col4f.z, hsv.x, hsv.y, hsv.z);
20571 ColorConvertHSVtoRGB(hsv.x + 0.20f, hsv.y, hsv.z, col4f.x, col4f.y, col4f.z);
20572
20573 RenderNavHighlight(bb, id);
20574 RenderFrame(bb.Min, bb.Max, GetColorU32(col4f), true, g.Style.FrameRounding);
20575 RenderTextClipped(bb.Min, bb.Max, label, NULL, &label_size, g.Style.ButtonTextAlign, &bb);
20576
20577 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
20578 return pressed;
20579}
20580
20581// [DEBUG] Display contents of Columns
20582void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
20583{
20584 if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
20585 return;
20586 BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
20587 for (ImGuiOldColumnData& column : columns->Columns)
20588 BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", (int)columns->Columns.index_from_ptr(&column), column.OffsetNorm, GetColumnOffsetFromNorm(columns, column.OffsetNorm));
20589 TreePop();
20590}
20591
20592static void DebugNodeDockNodeFlags(ImGuiDockNodeFlags* p_flags, const char* label, bool enabled)
20593{
20594 using namespace ImGui;
20595 PushID(label);
20596 PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f));
20597 Text("%s:", label);
20598 if (!enabled)
20599 BeginDisabled();
20600 CheckboxFlags("NoResize", p_flags, ImGuiDockNodeFlags_NoResize);
20601 CheckboxFlags("NoResizeX", p_flags, ImGuiDockNodeFlags_NoResizeX);
20602 CheckboxFlags("NoResizeY",p_flags, ImGuiDockNodeFlags_NoResizeY);
20603 CheckboxFlags("NoTabBar", p_flags, ImGuiDockNodeFlags_NoTabBar);
20604 CheckboxFlags("HiddenTabBar", p_flags, ImGuiDockNodeFlags_HiddenTabBar);
20605 CheckboxFlags("NoWindowMenuButton", p_flags, ImGuiDockNodeFlags_NoWindowMenuButton);
20606 CheckboxFlags("NoCloseButton", p_flags, ImGuiDockNodeFlags_NoCloseButton);
20607 CheckboxFlags("DockedWindowsInFocusRoute", p_flags, ImGuiDockNodeFlags_DockedWindowsInFocusRoute);
20608 CheckboxFlags("NoDocking", p_flags, ImGuiDockNodeFlags_NoDocking); // Multiple flags
20609 CheckboxFlags("NoDockingSplit", p_flags, ImGuiDockNodeFlags_NoDockingSplit);
20610 CheckboxFlags("NoDockingSplitOther", p_flags, ImGuiDockNodeFlags_NoDockingSplitOther);
20611 CheckboxFlags("NoDockingOver", p_flags, ImGuiDockNodeFlags_NoDockingOverMe);
20612 CheckboxFlags("NoDockingOverOther", p_flags, ImGuiDockNodeFlags_NoDockingOverOther);
20613 CheckboxFlags("NoDockingOverEmpty", p_flags, ImGuiDockNodeFlags_NoDockingOverEmpty);
20614 CheckboxFlags("NoUndocking", p_flags, ImGuiDockNodeFlags_NoUndocking);
20615 if (!enabled)
20616 EndDisabled();
20617 PopStyleVar();
20618 PopID();
20619}
20620
20621// [DEBUG] Display contents of ImDockNode
20622void ImGui::DebugNodeDockNode(ImGuiDockNode* node, const char* label)
20623{
20624 ImGuiContext& g = *GImGui;
20625 const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2); // Submitted with ImGuiDockNodeFlags_KeepAliveOnly
20626 const bool is_active = (g.FrameCount - node->LastFrameActive < 2); // Submitted
20627 if (!is_alive) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
20628 bool open;
20629 ImGuiTreeNodeFlags tree_node_flags = node->IsFocused ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
20630 if (node->Windows.Size > 0)
20631 open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
20632 else
20633 open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %s (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal split" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical split" : "empty", node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
20634 if (!is_alive) { PopStyleColor(); }
20635 if (is_active && IsItemHovered())
20636 if (ImGuiWindow* window = node->HostWindow ? node->HostWindow : node->VisibleWindow)
20637 GetForegroundDrawList(window)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255));
20638 if (open)
20639 {
20640 IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node);
20641 IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node);
20642 BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)",
20643 node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y);
20644 DebugNodeWindow(node->HostWindow, "HostWindow");
20645 DebugNodeWindow(node->VisibleWindow, "VisibleWindow");
20646 BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId);
20647 BulletText("Misc:%s%s%s%s%s%s%s",
20648 node->IsDockSpace() ? " IsDockSpace" : "",
20649 node->IsCentralNode() ? " IsCentralNode" : "",
20650 is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", node->IsFocused ? " IsFocused" : "",
20651 node->WantLockSizeOnce ? " WantLockSizeOnce" : "",
20652 node->HasCentralNodeChild ? " HasCentralNodeChild" : "");
20653 if (TreeNode("flags", "Flags Merged: 0x%04X, Local: 0x%04X, InWindows: 0x%04X, Shared: 0x%04X", node->MergedFlags, node->LocalFlags, node->LocalFlagsInWindows, node->SharedFlags))
20654 {
20655 if (BeginTable("flags", 4))
20656 {
20657 TableNextColumn(); DebugNodeDockNodeFlags(&node->MergedFlags, "MergedFlags", false);
20658 TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlags, "LocalFlags", true);
20659 TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlagsInWindows, "LocalFlagsInWindows", false);
20660 TableNextColumn(); DebugNodeDockNodeFlags(&node->SharedFlags, "SharedFlags", true);
20661 EndTable();
20662 }
20663 TreePop();
20664 }
20665 if (node->ParentNode)
20666 DebugNodeDockNode(node->ParentNode, "ParentNode");
20667 if (node->ChildNodes[0])
20668 DebugNodeDockNode(node->ChildNodes[0], "Child[0]");
20669 if (node->ChildNodes[1])
20670 DebugNodeDockNode(node->ChildNodes[1], "Child[1]");
20671 if (node->TabBar)
20672 DebugNodeTabBar(node->TabBar, "TabBar");
20673 DebugNodeWindowsList(&node->Windows, "Windows");
20674
20675 TreePop();
20676 }
20677}
20678
20679static void FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTextureID tex_id)
20680{
20681 union { void* ptr; int integer; } tex_id_opaque;
20682 memcpy(&tex_id_opaque, &tex_id, ImMin(sizeof(void*), sizeof(tex_id)));
20683 if (sizeof(tex_id) >= sizeof(void*))
20684 ImFormatString(buf, buf_size, "0x%p", tex_id_opaque.ptr);
20685 else
20686 ImFormatString(buf, buf_size, "0x%04X", tex_id_opaque.integer);
20687}
20688
20689// [DEBUG] Display contents of ImDrawList
20690// Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport.
20691void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
20692{
20693 ImGuiContext& g = *GImGui;
20694 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
20695 int cmd_count = draw_list->CmdBuffer.Size;
20696 if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
20697 cmd_count--;
20698 bool node_open = TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count);
20699 if (draw_list == GetWindowDrawList())
20700 {
20701 SameLine();
20702 TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
20703 if (node_open)
20704 TreePop();
20705 return;
20706 }
20707
20708 ImDrawList* fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list
20709 if (window && IsItemHovered() && fg_draw_list)
20710 fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
20711 if (!node_open)
20712 return;
20713
20714 if (window && !window->WasActive)
20715 TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
20716
20717 for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
20718 {
20719 if (pcmd->UserCallback)
20720 {
20721 BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
20722 continue;
20723 }
20724
20725 char texid_desc[20];
20726 FormatTextureIDForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), pcmd->TextureId);
20727 char buf[300];
20728 ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex %s, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
20729 pcmd->ElemCount / 3, texid_desc, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
20730 bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
20731 if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
20732 DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
20733 if (!pcmd_node_open)
20734 continue;
20735
20736 // Calculate approximate coverage area (touched pixel count)
20737 // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
20738 const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
20739 const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
20740 float total_area = 0.0f;
20741 for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
20742 {
20743 ImVec2 triangle[3];
20744 for (int n = 0; n < 3; n++, idx_n++)
20745 triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
20746 total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
20747 }
20748
20749 // Display vertex information summary. Hover to get all triangles drawn in wire-frame
20750 ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
20751 Selectable(buf);
20752 if (IsItemHovered() && fg_draw_list)
20753 DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);
20754
20755 // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
20756 ImGuiListClipper clipper;
20757 clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
20758 while (clipper.Step())
20759 for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
20760 {
20761 char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
20762 ImVec2 triangle[3];
20763 for (int n = 0; n < 3; n++, idx_i++)
20764 {
20765 const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
20766 triangle[n] = v.pos;
20767 buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
20768 (n == 0) ? "Vert:" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
20769 }
20770
20771 Selectable(buf, false);
20772 if (fg_draw_list && IsItemHovered())
20773 {
20774 ImDrawListFlags backup_flags = fg_draw_list->Flags;
20775 fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
20776 fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f);
20777 fg_draw_list->Flags = backup_flags;
20778 }
20779 }
20780 TreePop();
20781 }
20782 TreePop();
20783}
20784
20785// [DEBUG] Display mesh/aabb of a ImDrawCmd
20786void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
20787{
20788 IM_ASSERT(show_mesh || show_aabb);
20789
20790 // Draw wire-frame version of all triangles
20791 ImRect clip_rect = draw_cmd->ClipRect;
20792 ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
20793 ImDrawListFlags backup_flags = out_draw_list->Flags;
20794 out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
20795 for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
20796 {
20797 ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // We don't hold on those pointers past iterations as ->AddPolyline() may invalidate them if out_draw_list==draw_list
20798 ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
20799
20800 ImVec2 triangle[3];
20801 for (int n = 0; n < 3; n++, idx_n++)
20802 vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
20803 if (show_mesh)
20804 out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles
20805 }
20806 // Draw bounding boxes
20807 if (show_aabb)
20808 {
20809 out_draw_list->AddRect(ImTrunc(clip_rect.Min), ImTrunc(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
20810 out_draw_list->AddRect(ImTrunc(vtxs_rect.Min), ImTrunc(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
20811 }
20812 out_draw_list->Flags = backup_flags;
20813}
20814
20815// [DEBUG] Display details for a single font, called by ShowStyleEditor().
20816void ImGui::DebugNodeFont(ImFont* font)
20817{
20818 bool opened = TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)",
20819 font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
20820 SameLine();
20821 if (SmallButton("Set as default"))
20822 GetIO().FontDefault = font;
20823 if (!opened)
20824 return;
20825
20826 // Display preview text
20827 PushFont(font);
20828 Text("The quick brown fox jumps over the lazy dog");
20829 PopFont();
20830
20831 // Display details
20832 SetNextItemWidth(GetFontSize() * 8);
20833 DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f");
20834 SameLine(); MetricsHelpMarker(
20835 "Note that the default embedded font is NOT meant to be scaled.\n\n"
20836 "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
20837 "You may oversample them to get some flexibility with scaling. "
20838 "You can also render at multiple sizes and select which one to use at runtime.\n\n"
20839 "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");
20840 Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
20841 char c_str[5];
20842 Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar);
20843 Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar);
20844 const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface);
20845 Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);
20846 for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
20847 if (font->ConfigData)
20848 if (const ImFontConfig* cfg = &font->ConfigData[config_i])
20849 BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
20850 config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);
20851
20852 // Display all glyphs of the fonts in separate pages of 256 characters
20853 if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
20854 {
20855 ImDrawList* draw_list = GetWindowDrawList();
20856 const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
20857 const float cell_size = font->FontSize * 1;
20858 const float cell_spacing = GetStyle().ItemSpacing.y;
20859 for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
20860 {
20861 // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
20862 // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
20863 // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
20864 if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095))
20865 {
20866 base += 4096 - 256;
20867 continue;
20868 }
20869
20870 int count = 0;
20871 for (unsigned int n = 0; n < 256; n++)
20872 if (font->FindGlyphNoFallback((ImWchar)(base + n)))
20873 count++;
20874 if (count <= 0)
20875 continue;
20876 if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
20877 continue;
20878
20879 // Draw a 16x16 grid of glyphs
20880 ImVec2 base_pos = GetCursorScreenPos();
20881 for (unsigned int n = 0; n < 256; n++)
20882 {
20883 // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
20884 // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
20885 ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
20886 ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
20887 const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n));
20888 draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
20889 if (!glyph)
20890 continue;
20891 font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
20892 if (IsMouseHoveringRect(cell_p1, cell_p2) && BeginTooltip())
20893 {
20894 DebugNodeFontGlyph(font, glyph);
20895 EndTooltip();
20896 }
20897 }
20898 Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
20899 TreePop();
20900 }
20901 TreePop();
20902 }
20903 TreePop();
20904}
20905
20906void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph)
20907{
20908 Text("Codepoint: U+%04X", glyph->Codepoint);
20909 Separator();
20910 Text("Visible: %d", glyph->Visible);
20911 Text("AdvanceX: %.1f", glyph->AdvanceX);
20912 Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
20913 Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
20914}
20915
20916// [DEBUG] Display contents of ImGuiStorage
20917void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
20918{
20919 if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
20920 return;
20921 for (const ImGuiStorage::ImGuiStoragePair& p : storage->Data)
20922 BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
20923 TreePop();
20924}
20925
20926// [DEBUG] Display contents of ImGuiTabBar
20927void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
20928{
20929 // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
20930 char buf[256];
20931 char* p = buf;
20932 const char* buf_end = buf + IM_ARRAYSIZE(buf);
20933 const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
20934 p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s {", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
20935 for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
20936 {
20937 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
20938 p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", TabBarGetTabName(tab_bar, tab));
20939 }
20940 p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
20941 if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
20942 bool open = TreeNode(label, "%s", buf);
20943 if (!is_active) { PopStyleColor(); }
20944 if (is_active && IsItemHovered())
20945 {
20946 ImDrawList* draw_list = GetForegroundDrawList();
20947 draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
20948 draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
20949 draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
20950 }
20951 if (open)
20952 {
20953 for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
20954 {
20955 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
20956 PushID(tab);
20957 if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
20958 if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
20959 Text("%02d%c Tab 0x%08X '%s' Offset: %.2f, Width: %.2f/%.2f",
20960 tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, TabBarGetTabName(tab_bar, tab), tab->Offset, tab->Width, tab->ContentWidth);
20961 PopID();
20962 }
20963 TreePop();
20964 }
20965}
20966
20967void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
20968{
20969 ImGuiContext& g = *GImGui;
20970 SetNextItemOpen(true, ImGuiCond_Once);
20971 bool open = TreeNode((void*)(intptr_t)viewport->ID, "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A");
20972 if (IsItemHovered())
20973 g.DebugMetricsConfig.HighlightViewportID = viewport->ID;
20974 if (open)
20975 {
20976 ImGuiWindowFlags flags = viewport->Flags;
20977 BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%",
20978 viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
20979 viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y,
20980 viewport->PlatformMonitor, viewport->DpiScale * 100.0f);
20981 if (viewport->Idx > 0) { SameLine(); if (SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200, 200); viewport->UpdateWorkRect(); if (viewport->Window) viewport->Window->Pos = viewport->Pos; } }
20982 BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags,
20983 //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is the standard
20984 (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
20985 (flags & ImGuiViewportFlags_IsMinimized) ? " IsMinimized" : "",
20986 (flags & ImGuiViewportFlags_IsFocused) ? " IsFocused" : "",
20987 (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "",
20988 (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "",
20989 (flags & ImGuiViewportFlags_NoTaskBarIcon) ? " NoTaskBarIcon" : "",
20990 (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "",
20991 (flags & ImGuiViewportFlags_NoFocusOnClick) ? " NoFocusOnClick" : "",
20992 (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "",
20993 (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "",
20994 (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "",
20995 (flags & ImGuiViewportFlags_TopMost) ? " TopMost" : "",
20996 (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "");
20997 for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
20998 DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
20999 TreePop();
21000 }
21001}
21002
21003void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
21004{
21005 if (window == NULL)
21006 {
21007 BulletText("%s: NULL", label);
21008 return;
21009 }
21010
21011 ImGuiContext& g = *GImGui;
21012 const bool is_active = window->WasActive;
21013 ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
21014 if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
21015 const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
21016 if (!is_active) { PopStyleColor(); }
21017 if (IsItemHovered() && is_active)
21018 GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
21019 if (!open)
21020 return;
21021
21022 if (window->MemoryCompacted)
21023 TextDisabled("Note: some memory buffers have been compacted/freed.");
21024
21025 if (g.IO.ConfigDebugIsDebuggerPresent && DebugBreakButton("**DebugBreak**", "in Begin()"))
21026 g.DebugBreakInWindow = window->ID;
21027
21028 ImGuiWindowFlags flags = window->Flags;
21029 DebugNodeDrawList(window, window->Viewport, window->DrawList, "DrawList");
21030 BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y);
21031 BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
21032 (flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
21033 (flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
21034 (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
21035 BulletText("WindowClassId: 0x%08X", window->WindowClass.ClassId);
21036 BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
21037 BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
21038 BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
21039 for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
21040 {
21041 ImRect r = window->NavRectRel[layer];
21042 if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)
21043 BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
21044 else
21045 BulletText("NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y);
21046 DebugLocateItemOnHover(window->NavLastIds[layer]);
21047 }
21048 const ImVec2* pr = window->NavPreferredScoringPosRel;
21049 for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
21050 BulletText("NavPreferredScoringPosRel[%d] = {%.1f,%.1f)", layer, (pr[layer].x == FLT_MAX ? -99999.0f : pr[layer].x), (pr[layer].y == FLT_MAX ? -99999.0f : pr[layer].y)); // Display as 99999.0f so it looks neater.
21051 BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
21052
21053 BulletText("Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y);
21054 BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1);
21055 BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible);
21056 if (window->DockNode || window->DockNodeAsHost)
21057 DebugNodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode");
21058
21059 if (window->RootWindow != window) { DebugNodeWindow(window->RootWindow, "RootWindow"); }
21060 if (window->RootWindowDockTree != window->RootWindow) { DebugNodeWindow(window->RootWindowDockTree, "RootWindowDockTree"); }
21061 if (window->ParentWindow != NULL) { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
21062 if (window->ParentWindowForFocusRoute != NULL) { DebugNodeWindow(window->ParentWindowForFocusRoute, "ParentWindowForFocusRoute"); }
21063 if (window->DC.ChildWindows.Size > 0) { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
21064 if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
21065 {
21066 for (ImGuiOldColumns& columns : window->ColumnsStorage)
21067 DebugNodeColumns(&columns);
21068 TreePop();
21069 }
21070 DebugNodeStorage(&window->StateStorage, "Storage");
21071 TreePop();
21072}
21073
21074void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
21075{
21076 if (settings->WantDelete)
21077 BeginDisabled();
21078 Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
21079 settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
21080 if (settings->WantDelete)
21081 EndDisabled();
21082}
21083
21084void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
21085{
21086 if (!TreeNode(label, "%s (%d)", label, windows->Size))
21087 return;
21088 for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
21089 {
21090 PushID((*windows)[i]);
21091 DebugNodeWindow((*windows)[i], "Window");
21092 PopID();
21093 }
21094 TreePop();
21095}
21096
21097// FIXME-OPT: This is technically suboptimal, but it is simpler this way.
21098void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)
21099{
21100 for (int i = 0; i < windows_size; i++)
21101 {
21102 ImGuiWindow* window = windows[i];
21103 if (window->ParentWindowInBeginStack != parent_in_begin_stack)
21104 continue;
21105 char buf[20];
21106 ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext);
21107 //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
21108 DebugNodeWindow(window, buf);
21109 Indent();
21110 DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window);
21111 Unindent();
21112 }
21113}
21114
21115//-----------------------------------------------------------------------------
21116// [SECTION] DEBUG LOG WINDOW
21117//-----------------------------------------------------------------------------
21118
21119void ImGui::DebugLog(const char* fmt, ...)
21120{
21121 va_list args;
21122 va_start(args, fmt);
21123 DebugLogV(fmt, args);
21124 va_end(args);
21125}
21126
21127void ImGui::DebugLogV(const char* fmt, va_list args)
21128{
21129 ImGuiContext& g = *GImGui;
21130 const int old_size = g.DebugLogBuf.size();
21131 g.DebugLogBuf.appendf("[%05d] ", g.FrameCount);
21132 g.DebugLogBuf.appendfv(fmt, args);
21133 g.DebugLogIndex.append(g.DebugLogBuf.c_str(), old_size, g.DebugLogBuf.size());
21134 if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY)
21135 IMGUI_DEBUG_PRINTF("%s", g.DebugLogBuf.begin() + old_size);
21136#ifdef IMGUI_ENABLE_TEST_ENGINE
21137 if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTestEngine)
21138 IMGUI_TEST_ENGINE_LOG("%s", g.DebugLogBuf.begin() + old_size);
21139#endif
21140}
21141
21142// FIXME-LAYOUT: To be done automatically via layout mode once we rework ItemSize/ItemAdd into ItemLayout.
21143static void SameLineOrWrap(const ImVec2& size)
21144{
21145 ImGuiContext& g = *GImGui;
21146 ImGuiWindow* window = g.CurrentWindow;
21147 ImVec2 pos(window->DC.CursorPosPrevLine.x + g.Style.ItemSpacing.x, window->DC.CursorPosPrevLine.y);
21148 if (window->ClipRect.Contains(ImRect(pos, pos + size)))
21149 ImGui::SameLine();
21150}
21151
21152static void ShowDebugLogFlag(const char* name, ImGuiDebugLogFlags flags)
21153{
21154 ImGuiContext& g = *GImGui;
21155 ImVec2 size(ImGui::GetFrameHeight() + g.Style.ItemInnerSpacing.x + ImGui::CalcTextSize(name).x, ImGui::GetFrameHeight());
21156 SameLineOrWrap(size); // FIXME-LAYOUT: To be done automatically once we rework ItemSize/ItemAdd into ItemLayout.
21157 if (ImGui::CheckboxFlags(name, &g.DebugLogFlags, flags) && g.IO.KeyShift && (g.DebugLogFlags & flags) != 0)
21158 {
21159 g.DebugLogAutoDisableFrames = 2;
21160 g.DebugLogAutoDisableFlags |= flags;
21161 }
21162 ImGui::SetItemTooltip("Hold SHIFT when clicking to enable for 2 frames only (useful for spammy log entries)");
21163}
21164
21165void ImGui::ShowDebugLogWindow(bool* p_open)
21166{
21167 ImGuiContext& g = *GImGui;
21168 if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
21169 SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 12.0f), ImGuiCond_FirstUseEver);
21170 if (!Begin("Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1)
21171 {
21172 End();
21173 return;
21174 }
21175
21176 ImGuiDebugLogFlags all_enable_flags = ImGuiDebugLogFlags_EventMask_ & ~ImGuiDebugLogFlags_EventInputRouting;
21177 CheckboxFlags("All", &g.DebugLogFlags, all_enable_flags);
21178 SetItemTooltip("(except InputRouting which is spammy)");
21179
21180 ShowDebugLogFlag("ActiveId", ImGuiDebugLogFlags_EventActiveId);
21181 ShowDebugLogFlag("Clipper", ImGuiDebugLogFlags_EventClipper);
21182 ShowDebugLogFlag("Docking", ImGuiDebugLogFlags_EventDocking);
21183 ShowDebugLogFlag("Focus", ImGuiDebugLogFlags_EventFocus);
21184 ShowDebugLogFlag("IO", ImGuiDebugLogFlags_EventIO);
21185 ShowDebugLogFlag("Nav", ImGuiDebugLogFlags_EventNav);
21186 ShowDebugLogFlag("Popup", ImGuiDebugLogFlags_EventPopup);
21187 //ShowDebugLogFlag("Selection", ImGuiDebugLogFlags_EventSelection);
21188 ShowDebugLogFlag("Viewport", ImGuiDebugLogFlags_EventViewport);
21189 ShowDebugLogFlag("InputRouting", ImGuiDebugLogFlags_EventInputRouting);
21190
21191 if (SmallButton("Clear"))
21192 {
21193 g.DebugLogBuf.clear();
21194 g.DebugLogIndex.clear();
21195 }
21196 SameLine();
21197 if (SmallButton("Copy"))
21198 SetClipboardText(g.DebugLogBuf.c_str());
21199 BeginChild("##log", ImVec2(0.0f, 0.0f), ImGuiChildFlags_Border, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
21200
21201 const ImGuiDebugLogFlags backup_log_flags = g.DebugLogFlags;
21202 g.DebugLogFlags &= ~ImGuiDebugLogFlags_EventClipper;
21203
21204 ImGuiListClipper clipper;
21205 clipper.Begin(g.DebugLogIndex.size());
21206 while (clipper.Step())
21207 for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
21208 {
21209 const char* line_begin = g.DebugLogIndex.get_line_begin(g.DebugLogBuf.c_str(), line_no);
21210 const char* line_end = g.DebugLogIndex.get_line_end(g.DebugLogBuf.c_str(), line_no);
21211 TextUnformatted(line_begin, line_end); // Display line
21212 ImRect text_rect = g.LastItemData.Rect;
21213 if (IsItemHovered())
21214 for (const char* p = line_begin; p <= line_end - 10; p++) // Search for 0x???????? identifiers
21215 {
21216 ImGuiID id = 0;
21217 if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(p + 2, "%X", &id) != 1)
21218 continue;
21219 ImVec2 p0 = CalcTextSize(line_begin, p);
21220 ImVec2 p1 = CalcTextSize(p, p + 10);
21221 g.LastItemData.Rect = ImRect(text_rect.Min + ImVec2(p0.x, 0.0f), text_rect.Min + ImVec2(p0.x + p1.x, p1.y));
21222 if (IsMouseHoveringRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, true))
21223 DebugLocateItemOnHover(id);
21224 p += 10;
21225 }
21226 }
21227 g.DebugLogFlags = backup_log_flags;
21228 if (GetScrollY() >= GetScrollMaxY())
21229 SetScrollHereY(1.0f);
21230 EndChild();
21231
21232 End();
21233}
21234
21235//-----------------------------------------------------------------------------
21236// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
21237//-----------------------------------------------------------------------------
21238
21239// Draw a small cross at current CursorPos in current window's DrawList
21240void ImGui::DebugDrawCursorPos(ImU32 col)
21241{
21242 ImGuiContext& g = *GImGui;
21243 ImGuiWindow* window = g.CurrentWindow;
21244 ImVec2 pos = window->DC.CursorPos;
21245 window->DrawList->AddLine(ImVec2(pos.x, pos.y - 3.0f), ImVec2(pos.x, pos.y + 4.0f), col, 1.0f);
21246 window->DrawList->AddLine(ImVec2(pos.x - 3.0f, pos.y), ImVec2(pos.x + 4.0f, pos.y), col, 1.0f);
21247}
21248
21249// Draw a 10px wide rectangle around CurposPos.x using Line Y1/Y2 in current window's DrawList
21250void ImGui::DebugDrawLineExtents(ImU32 col)
21251{
21252 ImGuiContext& g = *GImGui;
21253 ImGuiWindow* window = g.CurrentWindow;
21254 float curr_x = window->DC.CursorPos.x;
21255 float line_y1 = (window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y);
21256 float line_y2 = line_y1 + (window->DC.IsSameLine ? window->DC.PrevLineSize.y : window->DC.CurrLineSize.y);
21257 window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y1), ImVec2(curr_x + 5.0f, line_y1), col, 1.0f);
21258 window->DrawList->AddLine(ImVec2(curr_x - 0.5f, line_y1), ImVec2(curr_x - 0.5f, line_y2), col, 1.0f);
21259 window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y2), ImVec2(curr_x + 5.0f, line_y2), col, 1.0f);
21260}
21261
21262// Draw last item rect in ForegroundDrawList (so it is always visible)
21263void ImGui::DebugDrawItemRect(ImU32 col)
21264{
21265 ImGuiContext& g = *GImGui;
21266 ImGuiWindow* window = g.CurrentWindow;
21267 GetForegroundDrawList(window)->AddRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, col);
21268}
21269
21270// [DEBUG] Locate item position/rectangle given an ID.
21271static const ImU32 DEBUG_LOCATE_ITEM_COLOR = IM_COL32(0, 255, 0, 255); // Green
21272
21273void ImGui::DebugLocateItem(ImGuiID target_id)
21274{
21275 ImGuiContext& g = *GImGui;
21276 g.DebugLocateId = target_id;
21277 g.DebugLocateFrames = 2;
21278 g.DebugBreakInLocateId = false;
21279}
21280
21281// FIXME: Doesn't work over through a modal window, because they clear HoveredWindow.
21282void ImGui::DebugLocateItemOnHover(ImGuiID target_id)
21283{
21284 if (target_id == 0 || !IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenBlockedByPopup))
21285 return;
21286 ImGuiContext& g = *GImGui;
21287 DebugLocateItem(target_id);
21288 GetForegroundDrawList(g.CurrentWindow)->AddRect(g.LastItemData.Rect.Min - ImVec2(3.0f, 3.0f), g.LastItemData.Rect.Max + ImVec2(3.0f, 3.0f), DEBUG_LOCATE_ITEM_COLOR);
21289
21290 // Can't easily use a context menu here because it will mess with focus, active id etc.
21291 if (g.IO.ConfigDebugIsDebuggerPresent && g.MouseStationaryTimer > 1.0f)
21292 {
21293 DebugBreakButtonTooltip(false, "in ItemAdd()");
21294 if (IsKeyChordPressed(g.DebugBreakKeyChord))
21295 g.DebugBreakInLocateId = true;
21296 }
21297}
21298
21299void ImGui::DebugLocateItemResolveWithLastItem()
21300{
21301 ImGuiContext& g = *GImGui;
21302
21303 // [DEBUG] Debug break requested by user
21304 if (g.DebugBreakInLocateId)
21305 IM_DEBUG_BREAK();
21306
21307 ImGuiLastItemData item_data = g.LastItemData;
21308 g.DebugLocateId = 0;
21309 ImDrawList* draw_list = GetForegroundDrawList(g.CurrentWindow);
21310 ImRect r = item_data.Rect;
21311 r.Expand(3.0f);
21312 ImVec2 p1 = g.IO.MousePos;
21313 ImVec2 p2 = ImVec2((p1.x < r.Min.x) ? r.Min.x : (p1.x > r.Max.x) ? r.Max.x : p1.x, (p1.y < r.Min.y) ? r.Min.y : (p1.y > r.Max.y) ? r.Max.y : p1.y);
21314 draw_list->AddRect(r.Min, r.Max, DEBUG_LOCATE_ITEM_COLOR);
21315 draw_list->AddLine(p1, p2, DEBUG_LOCATE_ITEM_COLOR);
21316}
21317
21318void ImGui::DebugStartItemPicker()
21319{
21320 ImGuiContext& g = *GImGui;
21321 g.DebugItemPickerActive = true;
21322}
21323
21324// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
21325void ImGui::UpdateDebugToolItemPicker()
21326{
21327 ImGuiContext& g = *GImGui;
21328 g.DebugItemPickerBreakId = 0;
21329 if (!g.DebugItemPickerActive)
21330 return;
21331
21332 const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
21333 SetMouseCursor(ImGuiMouseCursor_Hand);
21334 if (IsKeyPressed(ImGuiKey_Escape))
21335 g.DebugItemPickerActive = false;
21336 const bool change_mapping = g.IO.KeyMods == (ImGuiMod_Ctrl | ImGuiMod_Shift);
21337 if (!change_mapping && IsMouseClicked(g.DebugItemPickerMouseButton) && hovered_id)
21338 {
21339 g.DebugItemPickerBreakId = hovered_id;
21340 g.DebugItemPickerActive = false;
21341 }
21342 for (int mouse_button = 0; mouse_button < 3; mouse_button++)
21343 if (change_mapping && IsMouseClicked(mouse_button))
21344 g.DebugItemPickerMouseButton = (ImU8)mouse_button;
21345 SetNextWindowBgAlpha(0.70f);
21346 if (!BeginTooltip())
21347 return;
21348 Text("HoveredId: 0x%08X", hovered_id);
21349 Text("Press ESC to abort picking.");
21350 const char* mouse_button_names[] = { "Left", "Right", "Middle" };
21351 if (change_mapping)
21352 Text("Remap w/ Ctrl+Shift: click anywhere to select new mouse button.");
21353 else
21354 TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click %s Button to break in debugger! (remap w/ Ctrl+Shift)", mouse_button_names[g.DebugItemPickerMouseButton]);
21355 EndTooltip();
21356}
21357
21358// [DEBUG] ID Stack Tool: update queries. Called by NewFrame()
21359void ImGui::UpdateDebugToolStackQueries()
21360{
21361 ImGuiContext& g = *GImGui;
21362 ImGuiIDStackTool* tool = &g.DebugIDStackTool;
21363
21364 // Clear hook when id stack tool is not visible
21365 g.DebugHookIdInfo = 0;
21366 if (g.FrameCount != tool->LastActiveFrame + 1)
21367 return;
21368
21369 // Update queries. The steps are: -1: query Stack, >= 0: query each stack item
21370 // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
21371 const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
21372 if (tool->QueryId != query_id)
21373 {
21374 tool->QueryId = query_id;
21375 tool->StackLevel = -1;
21376 tool->Results.resize(0);
21377 }
21378 if (query_id == 0)
21379 return;
21380
21381 // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
21382 int stack_level = tool->StackLevel;
21383 if (stack_level >= 0 && stack_level < tool->Results.Size)
21384 if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)
21385 tool->StackLevel++;
21386
21387 // Update hook
21388 stack_level = tool->StackLevel;
21389 if (stack_level == -1)
21390 g.DebugHookIdInfo = query_id;
21391 if (stack_level >= 0 && stack_level < tool->Results.Size)
21392 {
21393 g.DebugHookIdInfo = tool->Results[stack_level].ID;
21394 tool->Results[stack_level].QueryFrameCount++;
21395 }
21396}
21397
21398// [DEBUG] ID Stack tool: hooks called by GetID() family functions
21399void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
21400{
21401 ImGuiContext& g = *GImGui;
21402 ImGuiWindow* window = g.CurrentWindow;
21403 ImGuiIDStackTool* tool = &g.DebugIDStackTool;
21404
21405 // Step 0: stack query
21406 // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget.
21407 if (tool->StackLevel == -1)
21408 {
21409 tool->StackLevel++;
21410 tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo());
21411 for (int n = 0; n < window->IDStack.Size + 1; n++)
21412 tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
21413 return;
21414 }
21415
21416 // Step 1+: query for individual level
21417 IM_ASSERT(tool->StackLevel >= 0);
21418 if (tool->StackLevel != window->IDStack.Size)
21419 return;
21420 ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
21421 IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
21422
21423 switch (data_type)
21424 {
21425 case ImGuiDataType_S32:
21426 ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%d", (int)(intptr_t)data_id);
21427 break;
21428 case ImGuiDataType_String:
21429 ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)strlen((const char*)data_id), (const char*)data_id);
21430 break;
21431 case ImGuiDataType_Pointer:
21432 ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "(void*)0x%p", data_id);
21433 break;
21434 case ImGuiDataType_ID:
21435 if (info->Desc[0] != 0) // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one.
21436 return;
21437 ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "0x%08X [override]", id);
21438 break;
21439 default:
21440 IM_ASSERT(0);
21441 }
21442 info->QuerySuccess = true;
21443 info->DataType = data_type;
21444}
21445
21446static int StackToolFormatLevelInfo(ImGuiIDStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size)
21447{
21448 ImGuiStackLevelInfo* info = &tool->Results[n];
21449 ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL;
21450 if (window) // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
21451 return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", window->Name);
21452 if (info->QuerySuccess) // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
21453 return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", info->Desc);
21454 if (tool->StackLevel < tool->Results.Size) // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
21455 return (*buf = 0);
21456#ifdef IMGUI_ENABLE_TEST_ENGINE
21457 if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID)) // Source: ImGuiTestEngine's ItemInfo()
21458 return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", label);
21459#endif
21460 return ImFormatString(buf, buf_size, "???");
21461}
21462
21463// ID Stack Tool: Display UI
21464void ImGui::ShowIDStackToolWindow(bool* p_open)
21465{
21466 ImGuiContext& g = *GImGui;
21467 if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
21468 SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver);
21469 if (!Begin("Dear ImGui ID Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
21470 {
21471 End();
21472 return;
21473 }
21474
21475 // Display hovered/active status
21476 ImGuiIDStackTool* tool = &g.DebugIDStackTool;
21477 const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
21478 const ImGuiID active_id = g.ActiveId;
21479#ifdef IMGUI_ENABLE_TEST_ENGINE
21480 Text("HoveredId: 0x%08X (\"%s\"), ActiveId: 0x%08X (\"%s\")", hovered_id, hovered_id ? ImGuiTestEngine_FindItemDebugLabel(&g, hovered_id) : "", active_id, active_id ? ImGuiTestEngine_FindItemDebugLabel(&g, active_id) : "");
21481#else
21482 Text("HoveredId: 0x%08X, ActiveId: 0x%08X", hovered_id, active_id);
21483#endif
21484 SameLine();
21485 MetricsHelpMarker("Hover an item with the mouse to display elements of the ID Stack leading to the item's final ID.\nEach level of the stack correspond to a PushID() call.\nAll levels of the stack are hashed together to make the final ID of a widget (ID displayed at the bottom level of the stack).\nRead FAQ entry about the ID stack for details.");
21486
21487 // CTRL+C to copy path
21488 const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime;
21489 Checkbox("Ctrl+C: copy path to clipboard", &tool->CopyToClipboardOnCtrlC);
21490 SameLine();
21491 TextColored((time_since_copy >= 0.0f && time_since_copy < 0.75f && ImFmod(time_since_copy, 0.25f) < 0.25f * 0.5f) ? ImVec4(1.f, 1.f, 0.3f, 1.f) : ImVec4(), "*COPIED*");
21492 if (tool->CopyToClipboardOnCtrlC && Shortcut(ImGuiMod_Ctrl | ImGuiKey_C, 0, ImGuiInputFlags_RouteGlobal))
21493 {
21494 tool->CopyToClipboardLastTime = (float)g.Time;
21495 char* p = g.TempBuffer.Data;
21496 char* p_end = p + g.TempBuffer.Size;
21497 for (int stack_n = 0; stack_n < tool->Results.Size && p + 3 < p_end; stack_n++)
21498 {
21499 *p++ = '/';
21500 char level_desc[256];
21501 StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc));
21502 for (int n = 0; level_desc[n] && p + 2 < p_end; n++)
21503 {
21504 if (level_desc[n] == '/')
21505 *p++ = '\\';
21506 *p++ = level_desc[n];
21507 }
21508 }
21509 *p = '\0';
21510 SetClipboardText(g.TempBuffer.Data);
21511 }
21512
21513 // Display decorated stack
21514 tool->LastActiveFrame = g.FrameCount;
21515 if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders))
21516 {
21517 const float id_width = CalcTextSize("0xDDDDDDDD").x;
21518 TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width);
21519 TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch);
21520 TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width);
21521 TableHeadersRow();
21522 for (int n = 0; n < tool->Results.Size; n++)
21523 {
21524 ImGuiStackLevelInfo* info = &tool->Results[n];
21525 TableNextColumn();
21526 Text("0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0);
21527 TableNextColumn();
21528 StackToolFormatLevelInfo(tool, n, true, g.TempBuffer.Data, g.TempBuffer.Size);
21529 TextUnformatted(g.TempBuffer.Data);
21530 TableNextColumn();
21531 Text("0x%08X", info->ID);
21532 if (n == tool->Results.Size - 1)
21533 TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header));
21534 }
21535 EndTable();
21536 }
21537 End();
21538}
21539
21540#else
21541
21542void ImGui::ShowMetricsWindow(bool*) {}
21543void ImGui::ShowFontAtlas(ImFontAtlas*) {}
21544void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
21545void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {}
21546void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
21547void ImGui::DebugNodeFont(ImFont*) {}
21548void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
21549void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
21550void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
21551void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
21552void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
21553void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
21554
21555void ImGui::DebugLog(const char*, ...) {}
21556void ImGui::DebugLogV(const char*, va_list) {}
21557void ImGui::ShowDebugLogWindow(bool*) {}
21558void ImGui::ShowIDStackToolWindow(bool*) {}
21559void ImGui::DebugStartItemPicker() {}
21560void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
21561
21562#endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
21563
21564//-----------------------------------------------------------------------------
21565
21566// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
21567// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
21568#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
21569#include "imgui_user.inl"
21570#endif
21571
21572//-----------------------------------------------------------------------------
21573
21574#endif // #ifndef IMGUI_DISABLE
uintptr_t id
int g
TclObject t
mat4 p4(vec4(1, 2, 3, 4), vec4(3, 4, 5, 6), vec4(5, 0, 7, 8), vec4(7, 8, 9, 0))
mat3 p3(vec3(1, 2, 3), vec3(4, 5, 6), vec3(7, 0, 9))
const char * ImStreolRange(const char *str, const char *str_end)
Definition imgui.cc:1889
char * ImStrdupcpy(char *dst, size_t *p_dst_size, const char *src)
Definition imgui.cc:1860
#define va_copy(dest, src)
Definition imgui.cc:2719
char * ImStrdup(const char *str)
Definition imgui.cc:1853
ImGuiContext * GImGui
Definition imgui.cc:1185
int ImFormatStringV(char *buf, size_t buf_size, const char *fmt, va_list args)
Definition imgui.cc:1989
ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2 &p1, const ImVec2 &p2, const ImVec2 &p3, const ImVec2 &p4, const ImVec2 &p, float tess_tol)
Definition imgui.cc:1767
const ImWchar * ImStrbolW(const ImWchar *buf_mid_line, const ImWchar *buf_begin)
Definition imgui.cc:1895
void ImTriangleBarycentricCoords(const ImVec2 &a, const ImVec2 &b, const ImVec2 &c, const ImVec2 &p, float &out_u, float &out_v, float &out_w)
Definition imgui.cc:1798
void ImFormatStringToTempBuffer(const char **out_buf, const char **out_buf_end, const char *fmt,...)
Definition imgui.cc:2005
int ImTextStrToUtf8(char *out_buf, int out_buf_size, const ImWchar *in_text, const ImWchar *in_text_end)
Definition imgui.cc:2342
int ImStrnicmp(const char *str1, const char *str2, size_t count)
Definition imgui.cc:1837
int ImStrlenW(const ImWchar *str)
Definition imgui.cc:1880
const char * ImStrchrRange(const char *str, const char *str_end, char c)
Definition imgui.cc:1874
int ImFormatString(char *buf, size_t buf_size, const char *fmt,...)
Definition imgui.cc:1971
ImVec2 ImLineClosestPoint(const ImVec2 &a, const ImVec2 &b, const ImVec2 &p)
Definition imgui.cc:1777
void ImStrTrimBlanks(char *buf)
Definition imgui.cc:1925
void ImFormatStringToTempBufferV(const char **out_buf, const char **out_buf_end, const char *fmt, va_list args)
Definition imgui.cc:2013
IM_MSVC_RUNTIME_CHECKS_RESTORE IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
Definition imgui.cc:2390
const char * ImStrSkipBlank(const char *str)
Definition imgui.cc:1940
const char * ImTextCharToUtf8(char out_buf[5], unsigned int c)
Definition imgui.cc:2319
bool ImTriangleContainsPoint(const ImVec2 &a, const ImVec2 &b, const ImVec2 &c, const ImVec2 &p)
Definition imgui.cc:1790
ImU64 ImFileWrite(const void *data, ImU64 sz, ImU64 count, ImFileHandle f)
Definition imgui.cc:2149
#define IMGUI_DEBUG_NAV_SCORING
Definition imgui.cc:1055
int ImTextCountUtf8BytesFromStr(const ImWchar *in_text, const ImWchar *in_text_end)
Definition imgui.cc:2358
ImU64 ImFileRead(void *data, ImU64 sz, ImU64 count, ImFileHandle f)
Definition imgui.cc:2148
ImGuiID ImHashStr(const char *data_p, size_t data_size, ImGuiID seed)
Definition imgui.cc:2086
const char * ImTextFindPreviousUtf8Codepoint(const char *in_text_start, const char *in_text_curr)
Definition imgui.cc:2372
IM_MSVC_RUNTIME_CHECKS_OFF int ImTextCharFromUtf8(unsigned int *out_char, const char *in_text, const char *in_text_end)
Definition imgui.cc:2203
int ImTextCountCharsFromUtf8(const char *in_text, const char *in_text_end)
Definition imgui.cc:2271
ImGuiDockRequestType
Definition imgui.cc:15581
@ ImGuiDockRequestType_Split
Definition imgui.cc:15585
@ ImGuiDockRequestType_Dock
Definition imgui.cc:15583
@ ImGuiDockRequestType_None
Definition imgui.cc:15582
@ ImGuiDockRequestType_Undock
Definition imgui.cc:15584
bool ImFileClose(ImFileHandle f)
Definition imgui.cc:2146
void * ImFileLoadToMemory(const char *filename, const char *mode, size_t *out_file_size, int padding_bytes)
Definition imgui.cc:2155
const char * ImStristr(const char *haystack, const char *haystack_end, const char *needle, const char *needle_end)
Definition imgui.cc:1902
ImVec2 ImBezierCubicClosestPoint(const ImVec2 &p1, const ImVec2 &p2, const ImVec2 &p3, const ImVec2 &p4, const ImVec2 &p, int num_segments)
Definition imgui.cc:1709
ImGuiID ImHashData(const void *data_p, size_t data_size, ImGuiID seed)
Definition imgui.cc:2070
ImU64 ImFileGetSize(ImFileHandle f)
Definition imgui.cc:2147
int ImStricmp(const char *str1, const char *str2)
Definition imgui.cc:1830
int ImTextCountUtf8BytesFromChar(const char *in_text, const char *in_text_end)
Definition imgui.cc:2327
ImFileHandle ImFileOpen(const char *filename, const char *mode)
Definition imgui.cc:2121
IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT==IM_ARRAYSIZE(GKeyNames))
int ImTextStrFromUtf8(ImWchar *buf, int buf_size, const char *in_text, const char *in_text_end, const char **in_text_remaining)
Definition imgui.cc:2255
void ImStrncpy(char *dst, const char *src, size_t count)
Definition imgui.cc:1844
ImVec2 ImTriangleClosestPoint(const ImVec2 &a, const ImVec2 &b, const ImVec2 &c, const ImVec2 &p)
Definition imgui.cc:1809
#define IM_NEWLINE
#define IMGUI_CDECL
ImVec2 ImBezierCubicCalc(const ImVec2 &p1, const ImVec2 &p2, const ImVec2 &p3, const ImVec2 &p4, float t)
IMGUI_API void ShowFontAtlas(ImFontAtlas *atlas)
Definition imgui.cc:19836
auto CalcTextSize(std::string_view str)
Definition ImGuiUtils.hh:37
const ImGuiID IMGUI_VIEWPORT_DEFAULT_ID
Definition imgui.cc:1144
void TextUnformatted(const std::string &str)
Definition ImGuiUtils.hh:24
ALWAYS_INLINE unsigned count(const uint8_t *pIn, const uint8_t *pMatch, const uint8_t *pInLimit)
Definition lz4.cc:146
constexpr double e
Definition Math.hh:21
T length(const vecN< N, T > &x)
Definition gl_vec.hh:376
constexpr vecN< N, T > min(const vecN< N, T > &x, const vecN< N, T > &y)
Definition gl_vec.hh:302
constexpr mat4 scale(const vec3 &xyz)
void Window(const char *name, bool *p_open, ImGuiWindowFlags flags, std::invocable<> auto next)
Definition ImGuiCpp.hh:63
void ID(const char *str_id, std::invocable<> auto next)
Definition ImGuiCpp.hh:244
void TabBar(const char *str_id, ImGuiTabBarFlags flags, std::invocable<> auto next)
Definition ImGuiCpp.hh:480
bool TreeNode(const char *label, ImGuiTreeNodeFlags flags, std::invocable<> auto next)
Definition ImGuiCpp.hh:306
void Combo(const char *label, const char *preview_value, ImGuiComboFlags flags, std::invocable<> auto next)
Definition ImGuiCpp.hh:293
void Indent(float indent_w, std::invocable<> auto next)
Definition ImGuiCpp.hh:224
bool Checkbox(const HotKey &hotKey, BooleanSetting &setting)
Definition ImGuiUtils.cc:81
bool SliderInt(IntegerSetting &setting, ImGuiSliderFlags flags)
bool InputText(Setting &setting)
auto remove(ForwardRange &&range, const T &value)
Definition ranges.hh:283
size_t size(std::string_view utf8)
auto distance(octet_iterator first, octet_iterator last)
signed char SplitAxis
Definition imgui.cc:15633
ImGuiDockNodeFlags Flags
Definition imgui.cc:15635
ImGuiDockNode * CentralNode
Definition imgui.cc:16639
ImGuiDockNode * FirstNodeWithWindows
Definition imgui.cc:16640
ImGuiDockNode * SplitNode
Definition imgui.cc:15618
ImRect DropRectsDraw[ImGuiDir_COUNT+1]
Definition imgui.cc:15621
ImGuiDockNode FutureNode
Definition imgui.cc:15613
ImGuiDockNode * UndockTargetNode
Definition imgui.cc:15598
ImGuiWindow * DockPayload
Definition imgui.cc:15593
ImGuiDir DockSplitDir
Definition imgui.cc:15594
ImGuiDockNode * DockTargetNode
Definition imgui.cc:15592
ImGuiWindow * UndockTargetWindow
Definition imgui.cc:15597
ImGuiDockRequestType Type
Definition imgui.cc:15590
ImGuiWindow * DockTargetWindow
Definition imgui.cc:15591
float DockSplitRatio
Definition imgui.cc:15595
constexpr void repeat(T n, Op op)
Repeat the given operation 'op' 'n' times.
Definition xrange.hh:147