• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // dear imgui, v1.85
2 // (main code and documentation)
3 
4 // Help:
5 // - Read FAQ at http://dearimgui.org/faq
6 // - Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.
7 // - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
8 // Read imgui.cpp for details, links and comments.
9 
10 // Resources:
11 // - FAQ                   http://dearimgui.org/faq
12 // - Homepage & latest     https://github.com/ocornut/imgui
13 // - Releases & changelog  https://github.com/ocornut/imgui/releases
14 // - Gallery               https://github.com/ocornut/imgui/issues/4451 (please post your screenshots/video there!)
15 // - Wiki                  https://github.com/ocornut/imgui/wiki (lots of good stuff there)
16 // - Glossary              https://github.com/ocornut/imgui/wiki/Glossary
17 // - Issues & support      https://github.com/ocornut/imgui/issues
18 
19 // Getting Started?
20 // - For first-time users having issues compiling/linking/running or issues loading fonts:
21 //   please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
22 
23 // Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
24 // See LICENSE.txt for copyright and licensing details (standard MIT License).
25 // This library is free but needs your support to sustain development and maintenance.
26 // Businesses: you can support continued development via invoiced technical support, maintenance and sponsoring contracts. Please reach out to "contact AT dearimgui.com".
27 // Individuals: you can support continued development via donations. See docs/README or web page.
28 
29 // It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
30 // Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
31 // modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
32 // come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
33 // to a better solution or official support for them.
34 
35 /*
36 
37 Index of this file:
38 
39 DOCUMENTATION
40 
41 - MISSION STATEMENT
42 - END-USER GUIDE
43 - PROGRAMMER GUIDE
44   - READ FIRST
45   - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
46   - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
47   - HOW A SIMPLE APPLICATION MAY LOOK LIKE
48   - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
49   - USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
50 - API BREAKING CHANGES (read me when you update!)
51 - FREQUENTLY ASKED QUESTIONS (FAQ)
52   - Read all answers online: https://www.dearimgui.org/faq, or in docs/FAQ.md (with a Markdown viewer)
53 
54 CODE
55 (search for "[SECTION]" in the code to find them)
56 
57 // [SECTION] INCLUDES
58 // [SECTION] FORWARD DECLARATIONS
59 // [SECTION] CONTEXT AND MEMORY ALLOCATORS
60 // [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
61 // [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
62 // [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
63 // [SECTION] MISC HELPERS/UTILITIES (File functions)
64 // [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
65 // [SECTION] MISC HELPERS/UTILITIES (Color functions)
66 // [SECTION] ImGuiStorage
67 // [SECTION] ImGuiTextFilter
68 // [SECTION] ImGuiTextBuffer
69 // [SECTION] ImGuiListClipper
70 // [SECTION] STYLING
71 // [SECTION] RENDER HELPERS
72 // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
73 // [SECTION] ERROR CHECKING
74 // [SECTION] LAYOUT
75 // [SECTION] SCROLLING
76 // [SECTION] TOOLTIPS
77 // [SECTION] POPUPS
78 // [SECTION] KEYBOARD/GAMEPAD NAVIGATION
79 // [SECTION] DRAG AND DROP
80 // [SECTION] LOGGING/CAPTURING
81 // [SECTION] SETTINGS
82 // [SECTION] VIEWPORTS
83 // [SECTION] PLATFORM DEPENDENT HELPERS
84 // [SECTION] METRICS/DEBUGGER WINDOW
85 // [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, STACK TOOL)
86 
87 */
88 
89 //-----------------------------------------------------------------------------
90 // DOCUMENTATION
91 //-----------------------------------------------------------------------------
92 
93 /*
94 
95  MISSION STATEMENT
96  =================
97 
98  - Easy to use to create code-driven and data-driven tools.
99  - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
100  - Easy to hack and improve.
101  - Minimize setup and maintenance.
102  - Minimize state storage on user side.
103  - Portable, minimize dependencies, run on target (consoles, phones, etc.).
104  - Efficient runtime and memory consumption.
105 
106  Designed for developers and content-creators, not the typical end-user! Some of the current weaknesses includes:
107 
108  - Doesn't look fancy, doesn't animate.
109  - Limited layout features, intricate layouts are typically crafted in code.
110 
111 
112  END-USER GUIDE
113  ==============
114 
115  - Double-click on title bar to collapse window.
116  - Click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin().
117  - Click and drag on lower right corner to resize window (double-click to auto fit window to its contents).
118  - Click and drag on any empty space to move window.
119  - TAB/SHIFT+TAB to cycle through keyboard editable fields.
120  - CTRL+Click on a slider or drag box to input value as text.
121  - Use mouse wheel to scroll.
122  - Text editor:
123    - Hold SHIFT or use mouse to select text.
124    - CTRL+Left/Right to word jump.
125    - CTRL+Shift+Left/Right to select words.
126    - CTRL+A our Double-Click to select all.
127    - CTRL+X,CTRL+C,CTRL+V to use OS clipboard/
128    - CTRL+Z,CTRL+Y to undo/redo.
129    - ESCAPE to revert text to its original value.
130    - You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!)
131    - Controls are automatically adjusted for OSX to match standard OSX text editing operations.
132  - General Keyboard controls: enable with ImGuiConfigFlags_NavEnableKeyboard.
133  - General Gamepad controls: enable with ImGuiConfigFlags_NavEnableGamepad. See suggested mappings in imgui.h ImGuiNavInput_ + download PNG/PSD at http://dearimgui.org/controls_sheets
134 
135 
136  PROGRAMMER GUIDE
137  ================
138 
139  READ FIRST
140  ----------
141  - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
142  - Your code creates the UI, if your code doesn't run the UI is gone! The UI can be highly dynamic, there are no construction or
143    destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, fewer bugs.
144  - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
145  - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
146  - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
147    You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
148  - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
149    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,
150    where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
151  - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
152  - This codebase is also optimized to yield decent performances with typical "Debug" builds settings.
153  - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
154    If you get an assert, read the messages and comments around the assert.
155  - C++: this is a very C-ish codebase: we don't rely on C++11, we don't include any C++ headers, and ImGui:: is a namespace.
156  - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
157    See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
158    However, imgui_internal.h can optionally export math operators for ImVec2/ImVec4, which we use in this codebase.
159  - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (avoid using it in your code!).
160 
161 
162  HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
163  ----------------------------------------------
164  - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
165  - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
166  - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
167  - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
168    If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
169    from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
170    likely be a comment about it. Please report any issue to the GitHub page!
171  - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
172  - Try to keep your copy of Dear ImGui reasonably up to date.
173 
174 
175  GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
176  ---------------------------------------------------------------
177  - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
178  - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
179  - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
180    It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
181  - 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.
182  - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
183  - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
184    Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
185    phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
186  - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
187  - 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.
188 
189 
190  HOW A SIMPLE APPLICATION MAY LOOK LIKE
191  --------------------------------------
192  EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
193  The sub-folders in examples/ contain examples applications following this structure.
194 
195      // Application init: create a dear imgui context, setup some options, load fonts
196      ImGui::CreateContext();
197      ImGuiIO& io = ImGui::GetIO();
198      // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
199      // TODO: Fill optional fields of the io structure later.
200      // TODO: Load TTF/OTF fonts if you don't want to use the default font.
201 
202      // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
203      ImGui_ImplWin32_Init(hwnd);
204      ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
205 
206      // Application main loop
207      while (true)
208      {
209          // Feed inputs to dear imgui, start new frame
210          ImGui_ImplDX11_NewFrame();
211          ImGui_ImplWin32_NewFrame();
212          ImGui::NewFrame();
213 
214          // Any application code here
215          ImGui::Text("Hello, world!");
216 
217          // Render dear imgui into screen
218          ImGui::Render();
219          ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
220          g_pSwapChain->Present(1, 0);
221      }
222 
223      // Shutdown
224      ImGui_ImplDX11_Shutdown();
225      ImGui_ImplWin32_Shutdown();
226      ImGui::DestroyContext();
227 
228  EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
229 
230      // Application init: create a dear imgui context, setup some options, load fonts
231      ImGui::CreateContext();
232      ImGuiIO& io = ImGui::GetIO();
233      // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
234      // TODO: Fill optional fields of the io structure later.
235      // TODO: Load TTF/OTF fonts if you don't want to use the default font.
236 
237      // Build and load the texture atlas into a texture
238      // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
239      int width, height;
240      unsigned char* pixels = NULL;
241      io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
242 
243      // At this point you've got the texture data and you need to upload that to your graphic system:
244      // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
245      // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
246      MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
247      io.Fonts->SetTexID((void*)texture);
248 
249      // Application main loop
250      while (true)
251      {
252         // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
253         // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
254         io.DeltaTime = 1.0f/60.0f;              // set the time elapsed since the previous frame (in seconds)
255         io.DisplaySize.x = 1920.0f;             // set the current display width
256         io.DisplaySize.y = 1280.0f;             // set the current display height here
257         io.MousePos = my_mouse_pos;             // set the mouse position
258         io.MouseDown[0] = my_mouse_buttons[0];  // set the mouse button states
259         io.MouseDown[1] = my_mouse_buttons[1];
260 
261         // Call NewFrame(), after this point you can use ImGui::* functions anytime
262         // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
263         ImGui::NewFrame();
264 
265         // Most of your application code here
266         ImGui::Text("Hello, world!");
267         MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
268         MyGameRender(); // may use any Dear ImGui functions as well!
269 
270         // Render dear imgui, swap buffers
271         // (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)
272         ImGui::EndFrame();
273         ImGui::Render();
274         ImDrawData* draw_data = ImGui::GetDrawData();
275         MyImGuiRenderFunction(draw_data);
276         SwapBuffers();
277      }
278 
279      // Shutdown
280      ImGui::DestroyContext();
281 
282  To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
283  you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
284  Please read the FAQ and example applications for details about this!
285 
286 
287  HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
288  ---------------------------------------------
289  The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
290 
291     void void MyImGuiRenderFunction(ImDrawData* draw_data)
292     {
293        // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
294        // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
295        // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
296        // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
297        for (int n = 0; n < draw_data->CmdListsCount; n++)
298        {
299           const ImDrawList* cmd_list = draw_data->CmdLists[n];
300           const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;  // vertex buffer generated by Dear ImGui
301           const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;   // index buffer generated by Dear ImGui
302           for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
303           {
304              const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
305              if (pcmd->UserCallback)
306              {
307                  pcmd->UserCallback(cmd_list, pcmd);
308              }
309              else
310              {
311                  // The texture for the draw call is specified by pcmd->GetTexID().
312                  // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
313                  MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
314 
315                  // We are using scissoring to clip some objects. All low-level graphics API should support it.
316                  // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
317                  //   (some elements visible outside their bounds) but you can fix that once everything else works!
318                  // - Clipping coordinates are provided in imgui coordinates space:
319                  //   - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
320                  //   - 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.
321                  //   - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
322                  //     always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
323                  // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
324                  ImVec2 pos = draw_data->DisplayPos;
325                  MyEngineScissor((int)(pcmd->ClipRect.x - pos.x), (int)(pcmd->ClipRect.y - pos.y), (int)(pcmd->ClipRect.z - pos.x), (int)(pcmd->ClipRect.w - pos.y));
326 
327                  // Render 'pcmd->ElemCount/3' indexed triangles.
328                  // 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.
329                  MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer, vtx_buffer);
330              }
331              idx_buffer += pcmd->ElemCount;
332           }
333        }
334     }
335 
336 
337  USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
338  ------------------------------------------
339  - The gamepad/keyboard navigation is fairly functional and keeps being improved.
340  - Gamepad support is particularly useful to use Dear ImGui on a console system (e.g. PS4, Switch, XB1) without a mouse!
341  - You can ask questions and report issues at https://github.com/ocornut/imgui/issues/787
342  - The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable.
343  - Keyboard:
344     - Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable.
345       NewFrame() will automatically fill io.NavInputs[] based on your io.KeysDown[] + io.KeyMap[] arrays.
346     - When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard), the io.WantCaptureKeyboard flag
347       will be set. For more advanced uses, you may want to read from:
348        - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
349        - io.NavVisible: true when the navigation cursor is visible (and usually goes false when mouse is used).
350        - or query focus information with e.g. IsWindowFocused(ImGuiFocusedFlags_AnyWindow), IsItemFocused() etc. functions.
351       Please reach out if you think the game vs navigation input sharing could be improved.
352  - Gamepad:
353     - Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable.
354     - Backend: Set io.BackendFlags |= ImGuiBackendFlags_HasGamepad + fill the io.NavInputs[] fields before calling NewFrame().
355       Note that io.NavInputs[] is cleared by EndFrame().
356     - See 'enum ImGuiNavInput_' in imgui.h for a description of inputs. For each entry of io.NavInputs[], set the following values:
357          0.0f= not held. 1.0f= fully held. Pass intermediate 0.0f..1.0f values for analog triggers/sticks.
358     - We use a simple >0.0f test for activation testing, and won't attempt to test for a dead-zone.
359       Your 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.).
360     - You can download PNG/PSD files depicting the gamepad controls for common controllers at: http://dearimgui.org/controls_sheets
361     - If you need to share inputs between your game and the imgui parts, the easiest approach is to go all-or-nothing, with a buttons combo
362       to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
363  - Mouse:
364     - PS4 users: Consider emulating a mouse cursor with DualShock4 touch pad or a spare analog stick as a mouse-emulation fallback.
365     - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + uSynergy.c (on your console/tablet/phone app) to share your PC mouse/keyboard.
366     - 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.
367       Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs dear imgui to move your mouse cursor along with navigation movements.
368       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.
369       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.
370       (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, imgui will misbehave as it will see your mouse moving back and forth!)
371       (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
372        to set a boolean to ignore your other external mouse positions until the external source is moved again.)
373 
374 
375  API BREAKING CHANGES
376  ====================
377 
378  Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
379  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.
380  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.
381  You can read releases logs https://github.com/ocornut/imgui/releases for more details.
382 
383  - 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.
384  - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
385                         - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
386                         - ImFont::GlyphRangesBuilder  -> use ImFontGlyphRangesBuilder
387  - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
388                         - if you are using official backends from the source tree: you have nothing to do.
389                         - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
390  - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
391                         - ImDrawCornerFlags_TopLeft  -> use ImDrawFlags_RoundCornersTopLeft
392                         - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
393                         - ImDrawCornerFlags_None     -> use ImDrawFlags_RoundCornersNone etc.
394                        flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
395                        breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
396                         - rounding == 0.0f + flags == 0 --> meant no rounding  --> unchanged (common use)
397                         - rounding  > 0.0f + flags != 0 --> meant rounding     --> unchanged (common use)
398                         - rounding == 0.0f + flags != 0 --> meant no rounding  --> unchanged (unlikely use)
399                         - rounding  > 0.0f + flags == 0 --> meant no rounding  --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
400                        this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
401                        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.
402                        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).
403  - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
404                         - ImGui::SetScrollHere()              -> use ImGui::SetScrollHereY()
405  - 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.
406  - 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.
407  - 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'.
408  - 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.
409  - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
410                      - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
411                      - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
412  - 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.
413                      - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
414                      - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
415  - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
416                         - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
417                         - ImGuiCol_ModalWindowDarkening       -> use ImGuiCol_ModalWindowDimBg
418                         - ImGuiInputTextCallback              -> use ImGuiTextEditCallback
419                         - ImGuiInputTextCallbackData          -> use ImGuiTextEditCallbackData
420  - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
421  - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
422  - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
423  - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
424  - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
425  - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
426                         - io.RenderDrawListsFn pointer        -> use ImGui::GetDrawData() value and call the render function of your backend
427                         - ImGui::IsAnyWindowFocused()         -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
428                         - ImGui::IsAnyWindowHovered()         -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
429                         - ImGuiStyleVar_Count_                -> use ImGuiStyleVar_COUNT
430                         - ImGuiMouseCursor_Count_             -> use ImGuiMouseCursor_COUNT
431                       - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
432                         - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
433                         - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
434  - 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).
435  - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
436  - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
437  - 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.
438  - 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.
439  - 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!
440  - 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().
441                        replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
442                        worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
443                        - if you omitted the 'power' parameter (likely!), you are not affected.
444                        - 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.
445                        - 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.
446                        see https://github.com/ocornut/imgui/issues/3361 for all details.
447                        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.
448                        for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
449                      - 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.
450  - 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.
451  - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
452  - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
453  - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
454  - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
455  - 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.
456  - 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.
457  - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
458                        - ShowTestWindow()                    -> use ShowDemoWindow()
459                        - IsRootWindowFocused()               -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
460                        - IsRootWindowOrAnyChildFocused()     -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
461                        - SetNextWindowContentWidth(w)        -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
462                        - GetItemsLineHeightWithSpacing()     -> use GetFrameHeightWithSpacing()
463                        - ImGuiCol_ChildWindowBg              -> use ImGuiCol_ChildBg
464                        - ImGuiStyleVar_ChildWindowRounding   -> use ImGuiStyleVar_ChildRounding
465                        - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
466                        - IMGUI_DISABLE_TEST_WINDOWS          -> use IMGUI_DISABLE_DEMO_WINDOWS
467  - 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.
468  - 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).
469  - 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.
470  - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
471  - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
472  - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
473                        - Begin() [old 5 args version]        -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
474                        - IsRootWindowOrAnyChildHovered()     -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
475                        - AlignFirstTextHeightToWidgets()     -> use AlignTextToFramePadding()
476                        - SetNextWindowPosCenter()            -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
477                        - ImFont::Glyph                       -> use ImFontGlyph
478  - 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.
479                        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.
480                        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).
481                        If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
482  - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
483  - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
484  - 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.
485  - 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
486                        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.
487                        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.
488                        Please reach out if you are affected.
489  - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
490  - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
491  - 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.
492  - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
493  - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
494  - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
495  - 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!
496  - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
497  - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
498  - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
499  - 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.
500  - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
501  - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
502  - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
503  - 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.
504                        If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
505  - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
506  - 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.
507                        NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
508                        Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
509  - 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).
510  - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
511  - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
512  - 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.
513  - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
514  - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
515  - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
516  - 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.).
517                        old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
518                        when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
519                        in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
520  - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
521  - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
522  - 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.
523                        If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
524                        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.
525                        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.
526  - 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",
527                        consistent with other functions. Kept redirection functions (will obsolete).
528  - 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.
529  - 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).
530  - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
531  - 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.
532  - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
533  - 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.
534  - 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.
535  - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
536                        - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
537                        - removed Shutdown() function, as DestroyContext() serve this purpose.
538                        - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
539                        - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
540                        - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
541  - 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.
542  - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
543  - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
544  - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
545  - 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.
546  - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
547  - 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
548  - 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.
549  - 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.
550  - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
551  - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
552                      - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
553  - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
554  - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
555  - 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.
556  - 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.
557                        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.
558  - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
559  - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
560  - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
561  - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
562  - 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.
563  - 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.
564  - 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.
565                        removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
566                          IsItemHoveredRect()        --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
567                          IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
568                          IsMouseHoveringWindow()    --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
569  - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
570  - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
571  - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
572  - 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).
573  - 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)".
574  - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
575                      - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
576                      - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
577  - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
578  - 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.
579  - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
580  - 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.
581  - 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).
582  - 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).
583  - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
584  - 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.
585                      - 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.
586                      - 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))'
587  - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
588  - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
589  - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
590  - 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().
591  - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
592  - 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.
593  - 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.
594  - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
595                        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.
596                        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:
597                        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); }
598                        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.
599  - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
600  - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
601  - 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).
602  - 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.
603  - 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).
604  - 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)
605  - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
606  - 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.
607  - 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.
608  - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
609  - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
610  - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
611                        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.
612                        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!
613  - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
614  - 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.
615  - 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
616  - 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.
617                        you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
618  - 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.
619                        this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
620                      - 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.
621                      - the signature of the io.RenderDrawListsFn handler has changed!
622                        old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
623                        new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
624                          parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
625                          ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
626                          ImDrawCmd:  'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
627                      - 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.
628                      - 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!
629                      - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
630  - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
631  - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
632  - 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.
633  - 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
634  - 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!
635  - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
636  - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
637  - 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.
638  - 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.
639  - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
640  - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
641  - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
642  - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
643  - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
644  - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
645  - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
646  - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
647  - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
648  - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
649  - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
650  - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
651  - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
652  - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
653  - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
654  - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
655  - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
656  - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
657                        - old:  const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
658                        - new:  unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
659                        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.
660  - 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()
661  - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
662  - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
663  - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
664  - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
665  - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
666  - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
667  - 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)
668  - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
669  - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
670  - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
671  - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
672  - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
673  - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
674 
675 
676  FREQUENTLY ASKED QUESTIONS (FAQ)
677  ================================
678 
679  Read all answers online:
680    https://www.dearimgui.org/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
681  Read all answers locally (with a text editor or ideally a Markdown viewer):
682    docs/FAQ.md
683  Some answers are copied down here to facilitate searching in code.
684 
685  Q&A: Basics
686  ===========
687 
688  Q: Where is the documentation?
689  A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
690     - Run the examples/ and explore them.
691     - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
692     - The demo covers most features of Dear ImGui, so you can read the code and see its output.
693     - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
694     - Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the
695       examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
696     - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
697     - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
698     - Your programming IDE is your friend, find the type or function declaration to find comments
699       associated with it.
700 
701  Q: What is this library called?
702  Q: Which version should I get?
703  >> This library is called "Dear ImGui", please don't call it "ImGui" :)
704  >> See https://www.dearimgui.org/faq for details.
705 
706  Q&A: Integration
707  ================
708 
709  Q: How to get started?
710  A: Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
711 
712  Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
713  A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
714  >> See https://www.dearimgui.org/faq for a fully detailed answer. You really want to read this.
715 
716  Q. How can I enable keyboard controls?
717  Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display)
718  Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
719  Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
720  Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
721  >> See https://www.dearimgui.org/faq
722 
723  Q&A: Usage
724  ----------
725 
726  Q: Why is my widget not reacting when I click on it?
727  Q: How can I have widgets with an empty label?
728  Q: How can I have multiple widgets with the same label?
729  Q: How can I display an image? What is ImTextureID, how does it works?
730  Q: How can I use my own math types instead of ImVec2/ImVec4?
731  Q: How can I interact with standard C++ types (such as std::string and std::vector)?
732  Q: How can I display custom shapes? (using low-level ImDrawList API)
733  >> See https://www.dearimgui.org/faq
734 
735  Q&A: Fonts, Text
736  ================
737 
738  Q: How should I handle DPI in my application?
739  Q: How can I load a different font than the default?
740  Q: How can I easily use icons in my application?
741  Q: How can I load multiple fonts?
742  Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
743  >> See https://www.dearimgui.org/faq and https://github.com/ocornut/imgui/edit/master/docs/FONTS.md
744 
745  Q&A: Concerns
746  =============
747 
748  Q: Who uses Dear ImGui?
749  Q: Can you create elaborate/serious tools with Dear ImGui?
750  Q: Can you reskin the look of Dear ImGui?
751  Q: Why using C++ (as opposed to C)?
752  >> See https://www.dearimgui.org/faq
753 
754  Q&A: Community
755  ==============
756 
757  Q: How can I help?
758  A: - Businesses: please reach out to "contact AT dearimgui.com" if you work in a place using Dear ImGui!
759       We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
760       This is among the most useful thing you can do for Dear ImGui. With increased funding, we can hire more people working on this project.
761     - Individuals: you can support continued development via PayPal donations. See README.
762     - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, read docs/TODO.txt
763       and see how you want to help and can help!
764     - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
765       You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
766       But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
767     - 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).
768 
769 */
770 
771 //-------------------------------------------------------------------------
772 // [SECTION] INCLUDES
773 //-------------------------------------------------------------------------
774 
775 #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
776 #define _CRT_SECURE_NO_WARNINGS
777 #endif
778 
779 #include "imgui.h"
780 #ifndef IMGUI_DISABLE
781 
782 #ifndef IMGUI_DEFINE_MATH_OPERATORS
783 #define IMGUI_DEFINE_MATH_OPERATORS
784 #endif
785 #include "imgui_internal.h"
786 
787 // System includes
788 #include <ctype.h>      // toupper
789 #include <stdio.h>      // vsnprintf, sscanf, printf
790 #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
791 #include <stddef.h>     // intptr_t
792 #else
793 #include <stdint.h>     // intptr_t
794 #endif
795 
796 // [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
797 #if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
798 #define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
799 #endif
800 
801 // [Windows] OS specific includes (optional)
802 #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)
803 #define IMGUI_DISABLE_WIN32_FUNCTIONS
804 #endif
805 #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
806 #ifndef WIN32_LEAN_AND_MEAN
807 #define WIN32_LEAN_AND_MEAN
808 #endif
809 #ifndef NOMINMAX
810 #define NOMINMAX
811 #endif
812 #ifndef __MINGW32__
813 #include <Windows.h>        // _wfopen, OpenClipboard
814 #else
815 #include <windows.h>
816 #endif
817 #if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have all Win32 functions
818 #define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
819 #define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
820 #endif
821 #endif
822 
823 // [Apple] OS specific includes
824 #if defined(__APPLE__)
825 #include <TargetConditionals.h>
826 #endif
827 
828 // Visual Studio warnings
829 #ifdef _MSC_VER
830 #pragma warning (disable: 4127)             // condition expression is constant
831 #pragma warning (disable: 4996)             // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
832 #if defined(_MSC_VER) && _MSC_VER >= 1922   // MSVC 2019 16.2 or later
833 #pragma warning (disable: 5054)             // operator '|': deprecated between enumerations of different types
834 #endif
835 #pragma warning (disable: 26451)            // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
836 #pragma warning (disable: 26495)            // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
837 #pragma warning (disable: 26812)            // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
838 #endif
839 
840 // Clang/GCC warnings with -Weverything
841 #if defined(__clang__)
842 #if __has_warning("-Wunknown-warning-option")
843 #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!
844 #endif
845 #pragma clang diagnostic ignored "-Wunknown-pragmas"                // warning: unknown warning group 'xxx'
846 #pragma clang diagnostic ignored "-Wold-style-cast"                 // warning: use of old-style cast                            // yes, they are more terse.
847 #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.
848 #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.
849 #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.
850 #pragma clang diagnostic ignored "-Wglobal-constructors"            // warning: declaration requires a global destructor         // similar to above, not sure what the exact difference is.
851 #pragma clang diagnostic ignored "-Wsign-conversion"                // warning: implicit conversion changes signedness
852 #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.
853 #pragma clang diagnostic ignored "-Wint-to-void-pointer-cast"       // warning: cast to 'void *' from smaller integer type 'int'
854 #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"  // warning: zero as null pointer constant                    // some standard header variations use #define NULL 0
855 #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.
856 #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion"  // warning: implicit conversion from 'xxx' to 'float' may lose precision
857 #elif defined(__GNUC__)
858 // We disable -Wpragmas because GCC doesn't provide an has_warning equivalent and some forks/patches may not following the warning/version association.
859 #pragma GCC diagnostic ignored "-Wpragmas"                  // warning: unknown option after '#pragma GCC diagnostic' kind
860 #pragma GCC diagnostic ignored "-Wunused-function"          // warning: 'xxxx' defined but not used
861 #pragma GCC diagnostic ignored "-Wint-to-pointer-cast"      // warning: cast to pointer from integer of different size
862 #pragma GCC diagnostic ignored "-Wformat"                   // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
863 #pragma GCC diagnostic ignored "-Wdouble-promotion"         // warning: implicit conversion from 'float' to 'double' when passing argument to function
864 #pragma GCC diagnostic ignored "-Wconversion"               // warning: conversion to 'xxxx' from 'xxxx' may alter its value
865 #pragma GCC diagnostic ignored "-Wformat-nonliteral"        // warning: format not a string literal, format string not checked
866 #pragma GCC diagnostic ignored "-Wstrict-overflow"          // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
867 #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
868 #endif
869 
870 // Debug options
871 #define IMGUI_DEBUG_NAV_SCORING     0   // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
872 #define IMGUI_DEBUG_NAV_RECTS       0   // Display the reference navigation rectangle for each window
873 #define IMGUI_DEBUG_INI_SETTINGS    0   // Save additional comments in .ini file (particularly helps for Docking, but makes saving slower)
874 
875 // 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.
876 static const float NAV_WINDOWING_HIGHLIGHT_DELAY            = 0.20f;    // Time before the highlight and screen dimming starts fading in
877 static const float NAV_WINDOWING_LIST_APPEAR_DELAY          = 0.15f;    // Time before the window list starts to appear
878 
879 // Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
880 static const float WINDOWS_HOVER_PADDING                    = 4.0f;     // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
881 static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f;    // Reduce visual noise by only highlighting the border after a certain time.
882 static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER    = 2.00f;    // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
883 
884 //-------------------------------------------------------------------------
885 // [SECTION] FORWARD DECLARATIONS
886 //-------------------------------------------------------------------------
887 
888 static void             SetCurrentWindow(ImGuiWindow* window);
889 static void             FindHoveredWindow();
890 static ImGuiWindow*     CreateNewWindow(const char* name, ImGuiWindowFlags flags);
891 static ImVec2           CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
892 
893 static void             AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list);
894 static void             AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
895 
896 // Settings
897 static void             WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
898 static void*            WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
899 static void             WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
900 static void             WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
901 static void             WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
902 
903 // Platform Dependents default implementation for IO functions
904 static const char*      GetClipboardTextFn_DefaultImpl(void* user_data);
905 static void             SetClipboardTextFn_DefaultImpl(void* user_data, const char* text);
906 static void             ImeSetInputScreenPosFn_DefaultImpl(int x, int y);
907 
908 namespace ImGui
909 {
910 // Navigation
911 static void             NavUpdate();
912 static void             NavUpdateWindowing();
913 static void             NavUpdateWindowingOverlay();
914 static void             NavUpdateCancelRequest();
915 static void             NavUpdateCreateMoveRequest();
916 static float            NavUpdatePageUpPageDown();
917 static inline void      NavUpdateAnyRequestFlag();
918 static void             NavEndFrame();
919 static bool             NavScoreItem(ImGuiNavItemData* result);
920 static void             NavApplyItemToResult(ImGuiNavItemData* result);
921 static void             NavProcessItem();
922 static ImVec2           NavCalcPreferredRefPos();
923 static void             NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
924 static ImGuiWindow*     NavRestoreLastChildNavWindow(ImGuiWindow* window);
925 static void             NavRestoreLayer(ImGuiNavLayer layer);
926 static int              FindWindowFocusIndex(ImGuiWindow* window);
927 
928 // Error Checking and Debug Tools
929 static void             ErrorCheckNewFrameSanityChecks();
930 static void             ErrorCheckEndFrameSanityChecks();
931 static void             UpdateDebugToolItemPicker();
932 static void             UpdateDebugToolStackQueries();
933 
934 // Misc
935 static void             UpdateSettings();
936 static void             UpdateMouseInputs();
937 static void             UpdateMouseWheel();
938 static void             UpdateTabFocus();
939 static bool             UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
940 static void             RenderWindowOuterBorders(ImGuiWindow* window);
941 static void             RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
942 static void             RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
943 
944 // Viewports
945 static void             UpdateViewportsNewFrame();
946 
947 }
948 
949 //-----------------------------------------------------------------------------
950 // [SECTION] CONTEXT AND MEMORY ALLOCATORS
951 //-----------------------------------------------------------------------------
952 
953 // DLL users:
954 // - Heaps and globals are not shared across DLL boundaries!
955 // - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
956 // - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
957 // - 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.
958 // - 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).
959 
960 // Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
961 // - ImGui::CreateContext() will automatically set this pointer if it is NULL.
962 //   Change to a different context by calling ImGui::SetCurrentContext().
963 // - Important: Dear ImGui functions are not thread-safe because of this pointer.
964 //   If you want thread-safety to allow N threads to access N different contexts:
965 //   - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
966 //         struct ImGuiContext;
967 //         extern thread_local ImGuiContext* MyImGuiTLS;
968 //         #define GImGui MyImGuiTLS
969 //     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.
970 //   - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
971 //   - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
972 // - DLL users: read comments above.
973 #ifndef GImGui
974 ImGuiContext*   GImGui = NULL;
975 #endif
976 
977 // Memory Allocator functions. Use SetAllocatorFunctions() to change them.
978 // - 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.
979 // - DLL users: read comments above.
980 #ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
MallocWrapper(size_t size,void * user_data)981 static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); return malloc(size); }
FreeWrapper(void * ptr,void * user_data)982 static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); free(ptr); }
983 #else
MallocWrapper(size_t size,void * user_data)984 static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
FreeWrapper(void * ptr,void * user_data)985 static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
986 #endif
987 static ImGuiMemAllocFunc    GImAllocatorAllocFunc = MallocWrapper;
988 static ImGuiMemFreeFunc     GImAllocatorFreeFunc = FreeWrapper;
989 static void*                GImAllocatorUserData = NULL;
990 
991 //-----------------------------------------------------------------------------
992 // [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
993 //-----------------------------------------------------------------------------
994 
ImGuiStyle()995 ImGuiStyle::ImGuiStyle()
996 {
997     Alpha                   = 1.0f;             // Global alpha applies to everything in Dear ImGui.
998     DisabledAlpha           = 0.60f;            // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
999     WindowPadding           = ImVec2(8,8);      // Padding within a window
1000     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.
1001     WindowBorderSize        = 1.0f;             // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1002     WindowMinSize           = ImVec2(32,32);    // Minimum window size
1003     WindowTitleAlign        = ImVec2(0.0f,0.5f);// Alignment for title bar text
1004     WindowMenuButtonPosition= ImGuiDir_Left;    // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1005     ChildRounding           = 0.0f;             // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1006     ChildBorderSize         = 1.0f;             // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1007     PopupRounding           = 0.0f;             // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1008     PopupBorderSize         = 1.0f;             // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1009     FramePadding            = ImVec2(4,3);      // Padding within a framed rectangle (used by most widgets)
1010     FrameRounding           = 0.0f;             // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1011     FrameBorderSize         = 0.0f;             // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1012     ItemSpacing             = ImVec2(8,4);      // Horizontal and vertical spacing between widgets/lines
1013     ItemInnerSpacing        = ImVec2(4,4);      // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1014     CellPadding             = ImVec2(4,2);      // Padding within a table cell
1015     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!
1016     IndentSpacing           = 21.0f;            // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1017     ColumnsMinSpacing       = 6.0f;             // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1018     ScrollbarSize           = 14.0f;            // Width of the vertical scrollbar, Height of the horizontal scrollbar
1019     ScrollbarRounding       = 9.0f;             // Radius of grab corners rounding for scrollbar
1020     GrabMinSize             = 10.0f;            // Minimum width/height of a grab box for slider/scrollbar
1021     GrabRounding            = 0.0f;             // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1022     LogSliderDeadzone       = 4.0f;             // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1023     TabRounding             = 4.0f;             // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1024     TabBorderSize           = 0.0f;             // Thickness of border around tabs.
1025     TabMinWidthForCloseButton = 0.0f;           // Minimum width for close button to appears 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.
1026     ColorButtonPosition     = ImGuiDir_Right;   // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1027     ButtonTextAlign         = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1028     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.
1029     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.
1030     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.
1031     MouseCursorScale        = 1.0f;             // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1032     AntiAliasedLines        = true;             // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1033     AntiAliasedLinesUseTex  = true;             // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering.
1034     AntiAliasedFill         = true;             // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1035     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.
1036     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.
1037 
1038     // Default theme
1039     ImGui::StyleColorsDark(this);
1040 }
1041 
1042 // 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.
1043 // 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.
ScaleAllSizes(float scale_factor)1044 void ImGuiStyle::ScaleAllSizes(float scale_factor)
1045 {
1046     WindowPadding = ImFloor(WindowPadding * scale_factor);
1047     WindowRounding = ImFloor(WindowRounding * scale_factor);
1048     WindowMinSize = ImFloor(WindowMinSize * scale_factor);
1049     ChildRounding = ImFloor(ChildRounding * scale_factor);
1050     PopupRounding = ImFloor(PopupRounding * scale_factor);
1051     FramePadding = ImFloor(FramePadding * scale_factor);
1052     FrameRounding = ImFloor(FrameRounding * scale_factor);
1053     ItemSpacing = ImFloor(ItemSpacing * scale_factor);
1054     ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor);
1055     CellPadding = ImFloor(CellPadding * scale_factor);
1056     TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor);
1057     IndentSpacing = ImFloor(IndentSpacing * scale_factor);
1058     ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor);
1059     ScrollbarSize = ImFloor(ScrollbarSize * scale_factor);
1060     ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor);
1061     GrabMinSize = ImFloor(GrabMinSize * scale_factor);
1062     GrabRounding = ImFloor(GrabRounding * scale_factor);
1063     LogSliderDeadzone = ImFloor(LogSliderDeadzone * scale_factor);
1064     TabRounding = ImFloor(TabRounding * scale_factor);
1065     TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImFloor(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
1066     DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);
1067     DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);
1068     MouseCursorScale = ImFloor(MouseCursorScale * scale_factor);
1069 }
1070 
ImGuiIO()1071 ImGuiIO::ImGuiIO()
1072 {
1073     // Most fields are initialized with zero
1074     memset(this, 0, sizeof(*this));
1075     IM_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT); // Our pre-C++11 IM_STATIC_ASSERT() macros triggers warning on modern compilers so we don't use it here.
1076 
1077     // Settings
1078     ConfigFlags = ImGuiConfigFlags_None;
1079     BackendFlags = ImGuiBackendFlags_None;
1080     DisplaySize = ImVec2(-1.0f, -1.0f);
1081     DeltaTime = 1.0f / 60.0f;
1082     IniSavingRate = 5.0f;
1083     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).
1084     LogFilename = "imgui_log.txt";
1085     MouseDoubleClickTime = 0.30f;
1086     MouseDoubleClickMaxDist = 6.0f;
1087     for (int i = 0; i < ImGuiKey_COUNT; i++)
1088         KeyMap[i] = -1;
1089     KeyRepeatDelay = 0.275f;
1090     KeyRepeatRate = 0.050f;
1091     UserData = NULL;
1092 
1093     Fonts = NULL;
1094     FontGlobalScale = 1.0f;
1095     FontDefault = NULL;
1096     FontAllowUserScaling = false;
1097     DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1098 
1099     // Miscellaneous options
1100     MouseDrawCursor = false;
1101 #ifdef __APPLE__
1102     ConfigMacOSXBehaviors = true;  // Set Mac OS X style defaults based on __APPLE__ compile time flag
1103 #else
1104     ConfigMacOSXBehaviors = false;
1105 #endif
1106     ConfigInputTextCursorBlink = true;
1107     ConfigWindowsResizeFromEdges = true;
1108     ConfigWindowsMoveFromTitleBarOnly = false;
1109     ConfigMemoryCompactTimer = 60.0f;
1110 
1111     // Platform Functions
1112     BackendPlatformName = BackendRendererName = NULL;
1113     BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1114     GetClipboardTextFn = GetClipboardTextFn_DefaultImpl;   // Platform dependent default implementations
1115     SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
1116     ClipboardUserData = NULL;
1117     ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl;
1118     ImeWindowHandle = NULL;
1119 
1120     // Input (NB: we already have memset zero the entire structure!)
1121     MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1122     MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1123     MouseDragThreshold = 6.0f;
1124     for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1125     for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++) KeysDownDuration[i]  = KeysDownDurationPrev[i] = -1.0f;
1126     for (int i = 0; i < IM_ARRAYSIZE(NavInputsDownDuration); i++) NavInputsDownDuration[i] = -1.0f;
1127 }
1128 
1129 // Pass in translated ASCII characters for text input.
1130 // - with glfw you can get those from the callback set in glfwSetCharCallback()
1131 // - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
AddInputCharacter(unsigned int c)1132 void ImGuiIO::AddInputCharacter(unsigned int c)
1133 {
1134     if (c != 0)
1135         InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
1136 }
1137 
1138 // UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1139 // we should save the high surrogate.
AddInputCharacterUTF16(ImWchar16 c)1140 void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1141 {
1142     if (c == 0 && InputQueueSurrogate == 0)
1143         return;
1144 
1145     if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1146     {
1147         if (InputQueueSurrogate != 0)
1148             InputQueueCharacters.push_back(IM_UNICODE_CODEPOINT_INVALID);
1149         InputQueueSurrogate = c;
1150         return;
1151     }
1152 
1153     ImWchar cp = c;
1154     if (InputQueueSurrogate != 0)
1155     {
1156         if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1157         {
1158             InputQueueCharacters.push_back(IM_UNICODE_CODEPOINT_INVALID);
1159         }
1160         else
1161         {
1162 #if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1163             cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1164 #else
1165             cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1166 #endif
1167         }
1168 
1169         InputQueueSurrogate = 0;
1170     }
1171     InputQueueCharacters.push_back(cp);
1172 }
1173 
AddInputCharactersUTF8(const char * utf8_chars)1174 void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1175 {
1176     while (*utf8_chars != 0)
1177     {
1178         unsigned int c = 0;
1179         utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
1180         if (c != 0)
1181             InputQueueCharacters.push_back((ImWchar)c);
1182     }
1183 }
1184 
ClearInputCharacters()1185 void ImGuiIO::ClearInputCharacters()
1186 {
1187     InputQueueCharacters.resize(0);
1188 }
1189 
ClearInputKeys()1190 void ImGuiIO::ClearInputKeys()
1191 {
1192     memset(KeysDown, 0, sizeof(KeysDown));
1193     for (int n = 0; n < IM_ARRAYSIZE(KeysDownDuration); n++)
1194         KeysDownDuration[n] = KeysDownDurationPrev[n] = -1.0f;
1195     KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1196     KeyMods = KeyModsPrev = ImGuiKeyModFlags_None;
1197     for (int n = 0; n < IM_ARRAYSIZE(NavInputsDownDuration); n++)
1198         NavInputsDownDuration[n] = NavInputsDownDurationPrev[n] = -1.0f;
1199 }
1200 
AddFocusEvent(bool focused)1201 void ImGuiIO::AddFocusEvent(bool focused)
1202 {
1203     // We intentionally overwrite this and process in NewFrame(), in order to give a chance
1204     // to multi-viewports backends to queue AddFocusEvent(false),AddFocusEvent(true) in same frame.
1205     AppFocusLost = !focused;
1206 }
1207 
1208 //-----------------------------------------------------------------------------
1209 // [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
1210 //-----------------------------------------------------------------------------
1211 
ImBezierCubicClosestPoint(const ImVec2 & p1,const ImVec2 & p2,const ImVec2 & p3,const ImVec2 & p4,const ImVec2 & p,int num_segments)1212 ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
1213 {
1214     IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
1215     ImVec2 p_last = p1;
1216     ImVec2 p_closest;
1217     float p_closest_dist2 = FLT_MAX;
1218     float t_step = 1.0f / (float)num_segments;
1219     for (int i_step = 1; i_step <= num_segments; i_step++)
1220     {
1221         ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
1222         ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1223         float dist2 = ImLengthSqr(p - p_line);
1224         if (dist2 < p_closest_dist2)
1225         {
1226             p_closest = p_line;
1227             p_closest_dist2 = dist2;
1228         }
1229         p_last = p_current;
1230     }
1231     return p_closest;
1232 }
1233 
1234 // Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
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)1235 static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
1236 {
1237     float dx = x4 - x1;
1238     float dy = y4 - y1;
1239     float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
1240     float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
1241     d2 = (d2 >= 0) ? d2 : -d2;
1242     d3 = (d3 >= 0) ? d3 : -d3;
1243     if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
1244     {
1245         ImVec2 p_current(x4, y4);
1246         ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1247         float dist2 = ImLengthSqr(p - p_line);
1248         if (dist2 < p_closest_dist2)
1249         {
1250             p_closest = p_line;
1251             p_closest_dist2 = dist2;
1252         }
1253         p_last = p_current;
1254     }
1255     else if (level < 10)
1256     {
1257         float x12 = (x1 + x2)*0.5f,       y12 = (y1 + y2)*0.5f;
1258         float x23 = (x2 + x3)*0.5f,       y23 = (y2 + y3)*0.5f;
1259         float x34 = (x3 + x4)*0.5f,       y34 = (y3 + y4)*0.5f;
1260         float x123 = (x12 + x23)*0.5f,    y123 = (y12 + y23)*0.5f;
1261         float x234 = (x23 + x34)*0.5f,    y234 = (y23 + y34)*0.5f;
1262         float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
1263         ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
1264         ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
1265     }
1266 }
1267 
1268 // tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
1269 // Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
ImBezierCubicClosestPointCasteljau(const ImVec2 & p1,const ImVec2 & p2,const ImVec2 & p3,const ImVec2 & p4,const ImVec2 & p,float tess_tol)1270 ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
1271 {
1272     IM_ASSERT(tess_tol > 0.0f);
1273     ImVec2 p_last = p1;
1274     ImVec2 p_closest;
1275     float p_closest_dist2 = FLT_MAX;
1276     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);
1277     return p_closest;
1278 }
1279 
ImLineClosestPoint(const ImVec2 & a,const ImVec2 & b,const ImVec2 & p)1280 ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
1281 {
1282     ImVec2 ap = p - a;
1283     ImVec2 ab_dir = b - a;
1284     float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
1285     if (dot < 0.0f)
1286         return a;
1287     float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
1288     if (dot > ab_len_sqr)
1289         return b;
1290     return a + ab_dir * dot / ab_len_sqr;
1291 }
1292 
ImTriangleContainsPoint(const ImVec2 & a,const ImVec2 & b,const ImVec2 & c,const ImVec2 & p)1293 bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1294 {
1295     bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
1296     bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
1297     bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
1298     return ((b1 == b2) && (b2 == b3));
1299 }
1300 
ImTriangleBarycentricCoords(const ImVec2 & a,const ImVec2 & b,const ImVec2 & c,const ImVec2 & p,float & out_u,float & out_v,float & out_w)1301 void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
1302 {
1303     ImVec2 v0 = b - a;
1304     ImVec2 v1 = c - a;
1305     ImVec2 v2 = p - a;
1306     const float denom = v0.x * v1.y - v1.x * v0.y;
1307     out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
1308     out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
1309     out_u = 1.0f - out_v - out_w;
1310 }
1311 
ImTriangleClosestPoint(const ImVec2 & a,const ImVec2 & b,const ImVec2 & c,const ImVec2 & p)1312 ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1313 {
1314     ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
1315     ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
1316     ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
1317     float dist2_ab = ImLengthSqr(p - proj_ab);
1318     float dist2_bc = ImLengthSqr(p - proj_bc);
1319     float dist2_ca = ImLengthSqr(p - proj_ca);
1320     float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
1321     if (m == dist2_ab)
1322         return proj_ab;
1323     if (m == dist2_bc)
1324         return proj_bc;
1325     return proj_ca;
1326 }
1327 
1328 //-----------------------------------------------------------------------------
1329 // [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
1330 //-----------------------------------------------------------------------------
1331 
1332 // Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
ImStricmp(const char * str1,const char * str2)1333 int ImStricmp(const char* str1, const char* str2)
1334 {
1335     int d;
1336     while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; }
1337     return d;
1338 }
1339 
ImStrnicmp(const char * str1,const char * str2,size_t count)1340 int ImStrnicmp(const char* str1, const char* str2, size_t count)
1341 {
1342     int d = 0;
1343     while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
1344     return d;
1345 }
1346 
ImStrncpy(char * dst,const char * src,size_t count)1347 void ImStrncpy(char* dst, const char* src, size_t count)
1348 {
1349     if (count < 1)
1350         return;
1351     if (count > 1)
1352         strncpy(dst, src, count - 1);
1353     dst[count - 1] = 0;
1354 }
1355 
ImStrdup(const char * str)1356 char* ImStrdup(const char* str)
1357 {
1358     size_t len = strlen(str);
1359     void* buf = IM_ALLOC(len + 1);
1360     return (char*)memcpy(buf, (const void*)str, len + 1);
1361 }
1362 
ImStrdupcpy(char * dst,size_t * p_dst_size,const char * src)1363 char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
1364 {
1365     size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
1366     size_t src_size = strlen(src) + 1;
1367     if (dst_buf_size < src_size)
1368     {
1369         IM_FREE(dst);
1370         dst = (char*)IM_ALLOC(src_size);
1371         if (p_dst_size)
1372             *p_dst_size = src_size;
1373     }
1374     return (char*)memcpy(dst, (const void*)src, src_size);
1375 }
1376 
ImStrchrRange(const char * str,const char * str_end,char c)1377 const char* ImStrchrRange(const char* str, const char* str_end, char c)
1378 {
1379     const char* p = (const char*)memchr(str, (int)c, str_end - str);
1380     return p;
1381 }
1382 
ImStrlenW(const ImWchar * str)1383 int ImStrlenW(const ImWchar* str)
1384 {
1385     //return (int)wcslen((const wchar_t*)str);  // FIXME-OPT: Could use this when wchar_t are 16-bit
1386     int n = 0;
1387     while (*str++) n++;
1388     return n;
1389 }
1390 
1391 // Find end-of-line. Return pointer will point to either first \n, either str_end.
ImStreolRange(const char * str,const char * str_end)1392 const char* ImStreolRange(const char* str, const char* str_end)
1393 {
1394     const char* p = (const char*)memchr(str, '\n', str_end - str);
1395     return p ? p : str_end;
1396 }
1397 
ImStrbolW(const ImWchar * buf_mid_line,const ImWchar * buf_begin)1398 const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
1399 {
1400     while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
1401         buf_mid_line--;
1402     return buf_mid_line;
1403 }
1404 
ImStristr(const char * haystack,const char * haystack_end,const char * needle,const char * needle_end)1405 const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
1406 {
1407     if (!needle_end)
1408         needle_end = needle + strlen(needle);
1409 
1410     const char un0 = (char)toupper(*needle);
1411     while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
1412     {
1413         if (toupper(*haystack) == un0)
1414         {
1415             const char* b = needle + 1;
1416             for (const char* a = haystack + 1; b < needle_end; a++, b++)
1417                 if (toupper(*a) != toupper(*b))
1418                     break;
1419             if (b == needle_end)
1420                 return haystack;
1421         }
1422         haystack++;
1423     }
1424     return NULL;
1425 }
1426 
1427 // 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.
ImStrTrimBlanks(char * buf)1428 void ImStrTrimBlanks(char* buf)
1429 {
1430     char* p = buf;
1431     while (p[0] == ' ' || p[0] == '\t')     // Leading blanks
1432         p++;
1433     char* p_start = p;
1434     while (*p != 0)                         // Find end of string
1435         p++;
1436     while (p > p_start && (p[-1] == ' ' || p[-1] == '\t'))  // Trailing blanks
1437         p--;
1438     if (p_start != buf)                     // Copy memory if we had leading blanks
1439         memmove(buf, p_start, p - p_start);
1440     buf[p - p_start] = 0;                   // Zero terminate
1441 }
1442 
ImStrSkipBlank(const char * str)1443 const char* ImStrSkipBlank(const char* str)
1444 {
1445     while (str[0] == ' ' || str[0] == '\t')
1446         str++;
1447     return str;
1448 }
1449 
1450 // A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
1451 // 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.
1452 // B) When buf==NULL vsnprintf() will return the output size.
1453 #ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1454 
1455 // We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
1456 // You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1457 // and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
1458 // designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
1459 #ifdef IMGUI_USE_STB_SPRINTF
1460 #define STB_SPRINTF_IMPLEMENTATION
1461 #include "stb_sprintf.h"
1462 #endif
1463 
1464 #if defined(_MSC_VER) && !defined(vsnprintf)
1465 #define vsnprintf _vsnprintf
1466 #endif
1467 
ImFormatString(char * buf,size_t buf_size,const char * fmt,...)1468 int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
1469 {
1470     va_list args;
1471     va_start(args, fmt);
1472 #ifdef IMGUI_USE_STB_SPRINTF
1473     int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1474 #else
1475     int w = vsnprintf(buf, buf_size, fmt, args);
1476 #endif
1477     va_end(args);
1478     if (buf == NULL)
1479         return w;
1480     if (w == -1 || w >= (int)buf_size)
1481         w = (int)buf_size - 1;
1482     buf[w] = 0;
1483     return w;
1484 }
1485 
ImFormatStringV(char * buf,size_t buf_size,const char * fmt,va_list args)1486 int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
1487 {
1488 #ifdef IMGUI_USE_STB_SPRINTF
1489     int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1490 #else
1491     int w = vsnprintf(buf, buf_size, fmt, args);
1492 #endif
1493     if (buf == NULL)
1494         return w;
1495     if (w == -1 || w >= (int)buf_size)
1496         w = (int)buf_size - 1;
1497     buf[w] = 0;
1498     return w;
1499 }
1500 #endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1501 
1502 // CRC32 needs a 1KB lookup table (not cache friendly)
1503 // Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
1504 // - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
1505 static const ImU32 GCrc32LookupTable[256] =
1506 {
1507     0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
1508     0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
1509     0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
1510     0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
1511     0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
1512     0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
1513     0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
1514     0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
1515     0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
1516     0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
1517     0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
1518     0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
1519     0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
1520     0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
1521     0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
1522     0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
1523 };
1524 
1525 // Known size hash
1526 // It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
1527 // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
ImHashData(const void * data_p,size_t data_size,ImU32 seed)1528 ImGuiID ImHashData(const void* data_p, size_t data_size, ImU32 seed)
1529 {
1530     ImU32 crc = ~seed;
1531     const unsigned char* data = (const unsigned char*)data_p;
1532     const ImU32* crc32_lut = GCrc32LookupTable;
1533     while (data_size-- != 0)
1534         crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
1535     return ~crc;
1536 }
1537 
1538 // Zero-terminated string hash, with support for ### to reset back to seed value
1539 // We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
1540 // Because this syntax is rarely used we are optimizing for the common case.
1541 // - If we reach ### in the string we discard the hash so far and reset to the seed.
1542 // - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
1543 // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
ImHashStr(const char * data_p,size_t data_size,ImU32 seed)1544 ImGuiID ImHashStr(const char* data_p, size_t data_size, ImU32 seed)
1545 {
1546     seed = ~seed;
1547     ImU32 crc = seed;
1548     const unsigned char* data = (const unsigned char*)data_p;
1549     const ImU32* crc32_lut = GCrc32LookupTable;
1550     if (data_size != 0)
1551     {
1552         while (data_size-- != 0)
1553         {
1554             unsigned char c = *data++;
1555             if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
1556                 crc = seed;
1557             crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
1558         }
1559     }
1560     else
1561     {
1562         while (unsigned char c = *data++)
1563         {
1564             if (c == '#' && data[0] == '#' && data[1] == '#')
1565                 crc = seed;
1566             crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
1567         }
1568     }
1569     return ~crc;
1570 }
1571 
1572 //-----------------------------------------------------------------------------
1573 // [SECTION] MISC HELPERS/UTILITIES (File functions)
1574 //-----------------------------------------------------------------------------
1575 
1576 // Default file functions
1577 #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
1578 
ImFileOpen(const char * filename,const char * mode)1579 ImFileHandle ImFileOpen(const char* filename, const char* mode)
1580 {
1581 #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
1582     // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
1583     // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
1584     const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
1585     const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
1586     ImVector<ImWchar> buf;
1587     buf.resize(filename_wsize + mode_wsize);
1588     ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, (wchar_t*)&buf[0], filename_wsize);
1589     ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, (wchar_t*)&buf[filename_wsize], mode_wsize);
1590     return ::_wfopen((const wchar_t*)&buf[0], (const wchar_t*)&buf[filename_wsize]);
1591 #else
1592     return fopen(filename, mode);
1593 #endif
1594 }
1595 
1596 // 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.
ImFileClose(ImFileHandle f)1597 bool    ImFileClose(ImFileHandle f)     { return fclose(f) == 0; }
ImFileGetSize(ImFileHandle f)1598 ImU64   ImFileGetSize(ImFileHandle f)   { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
ImFileRead(void * data,ImU64 sz,ImU64 count,ImFileHandle f)1599 ImU64   ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f)           { return fread(data, (size_t)sz, (size_t)count, f); }
ImFileWrite(const void * data,ImU64 sz,ImU64 count,ImFileHandle f)1600 ImU64   ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f)    { return fwrite(data, (size_t)sz, (size_t)count, f); }
1601 #endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
1602 
1603 // Helper: Load file content into memory
1604 // Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
1605 // This can't really be used with "rt" because fseek size won't match read size.
ImFileLoadToMemory(const char * filename,const char * mode,size_t * out_file_size,int padding_bytes)1606 void*   ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
1607 {
1608     IM_ASSERT(filename && mode);
1609     if (out_file_size)
1610         *out_file_size = 0;
1611 
1612     ImFileHandle f;
1613     if ((f = ImFileOpen(filename, mode)) == NULL)
1614         return NULL;
1615 
1616     size_t file_size = (size_t)ImFileGetSize(f);
1617     if (file_size == (size_t)-1)
1618     {
1619         ImFileClose(f);
1620         return NULL;
1621     }
1622 
1623     void* file_data = IM_ALLOC(file_size + padding_bytes);
1624     if (file_data == NULL)
1625     {
1626         ImFileClose(f);
1627         return NULL;
1628     }
1629     if (ImFileRead(file_data, 1, file_size, f) != file_size)
1630     {
1631         ImFileClose(f);
1632         IM_FREE(file_data);
1633         return NULL;
1634     }
1635     if (padding_bytes > 0)
1636         memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
1637 
1638     ImFileClose(f);
1639     if (out_file_size)
1640         *out_file_size = file_size;
1641 
1642     return file_data;
1643 }
1644 
1645 //-----------------------------------------------------------------------------
1646 // [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
1647 //-----------------------------------------------------------------------------
1648 
1649 // Convert UTF-8 to 32-bit character, process single character input.
1650 // A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
1651 // We handle UTF-8 decoding error by skipping forward.
ImTextCharFromUtf8(unsigned int * out_char,const char * in_text,const char * in_text_end)1652 int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
1653 {
1654     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 };
1655     static const int masks[]  = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
1656     static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
1657     static const int shiftc[] = { 0, 18, 12, 6, 0 };
1658     static const int shifte[] = { 0, 6, 4, 2, 0 };
1659     int len = lengths[*(const unsigned char*)in_text >> 3];
1660     int wanted = len + !len;
1661 
1662     if (in_text_end == NULL)
1663         in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
1664 
1665     // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
1666     // so it is fast even with excessive branching.
1667     unsigned char s[4];
1668     s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
1669     s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
1670     s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
1671     s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
1672 
1673     // Assume a four-byte character and load four bytes. Unused bits are shifted out.
1674     *out_char  = (uint32_t)(s[0] & masks[len]) << 18;
1675     *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
1676     *out_char |= (uint32_t)(s[2] & 0x3f) <<  6;
1677     *out_char |= (uint32_t)(s[3] & 0x3f) <<  0;
1678     *out_char >>= shiftc[len];
1679 
1680     // Accumulate the various error conditions.
1681     int e = 0;
1682     e  = (*out_char < mins[len]) << 6; // non-canonical encoding
1683     e |= ((*out_char >> 11) == 0x1b) << 7;  // surrogate half?
1684     e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8;  // out of range?
1685     e |= (s[1] & 0xc0) >> 2;
1686     e |= (s[2] & 0xc0) >> 4;
1687     e |= (s[3]       ) >> 6;
1688     e ^= 0x2a; // top two bits of each tail byte correct?
1689     e >>= shifte[len];
1690 
1691     if (e)
1692     {
1693         // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
1694         // One byte is consumed in case of invalid first byte of in_text.
1695         // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
1696         // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
1697         wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
1698         *out_char = IM_UNICODE_CODEPOINT_INVALID;
1699     }
1700 
1701     return wanted;
1702 }
1703 
ImTextStrFromUtf8(ImWchar * buf,int buf_size,const char * in_text,const char * in_text_end,const char ** in_text_remaining)1704 int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
1705 {
1706     ImWchar* buf_out = buf;
1707     ImWchar* buf_end = buf + buf_size;
1708     while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
1709     {
1710         unsigned int c;
1711         in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
1712         if (c == 0)
1713             break;
1714         *buf_out++ = (ImWchar)c;
1715     }
1716     *buf_out = 0;
1717     if (in_text_remaining)
1718         *in_text_remaining = in_text;
1719     return (int)(buf_out - buf);
1720 }
1721 
ImTextCountCharsFromUtf8(const char * in_text,const char * in_text_end)1722 int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
1723 {
1724     int char_count = 0;
1725     while ((!in_text_end || in_text < in_text_end) && *in_text)
1726     {
1727         unsigned int c;
1728         in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
1729         if (c == 0)
1730             break;
1731         char_count++;
1732     }
1733     return char_count;
1734 }
1735 
1736 // Based on stb_to_utf8() from github.com/nothings/stb/
ImTextCharToUtf8_inline(char * buf,int buf_size,unsigned int c)1737 static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
1738 {
1739     if (c < 0x80)
1740     {
1741         buf[0] = (char)c;
1742         return 1;
1743     }
1744     if (c < 0x800)
1745     {
1746         if (buf_size < 2) return 0;
1747         buf[0] = (char)(0xc0 + (c >> 6));
1748         buf[1] = (char)(0x80 + (c & 0x3f));
1749         return 2;
1750     }
1751     if (c < 0x10000)
1752     {
1753         if (buf_size < 3) return 0;
1754         buf[0] = (char)(0xe0 + (c >> 12));
1755         buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
1756         buf[2] = (char)(0x80 + ((c ) & 0x3f));
1757         return 3;
1758     }
1759     if (c <= 0x10FFFF)
1760     {
1761         if (buf_size < 4) return 0;
1762         buf[0] = (char)(0xf0 + (c >> 18));
1763         buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
1764         buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
1765         buf[3] = (char)(0x80 + ((c ) & 0x3f));
1766         return 4;
1767     }
1768     // Invalid code point, the max unicode is 0x10FFFF
1769     return 0;
1770 }
1771 
ImTextCharToUtf8(char out_buf[5],unsigned int c)1772 const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
1773 {
1774     int count = ImTextCharToUtf8_inline(out_buf, 5, c);
1775     out_buf[count] = 0;
1776     return out_buf;
1777 }
1778 
1779 // Not optimal but we very rarely use this function.
ImTextCountUtf8BytesFromChar(const char * in_text,const char * in_text_end)1780 int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
1781 {
1782     unsigned int unused = 0;
1783     return ImTextCharFromUtf8(&unused, in_text, in_text_end);
1784 }
1785 
ImTextCountUtf8BytesFromChar(unsigned int c)1786 static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
1787 {
1788     if (c < 0x80) return 1;
1789     if (c < 0x800) return 2;
1790     if (c < 0x10000) return 3;
1791     if (c <= 0x10FFFF) return 4;
1792     return 3;
1793 }
1794 
ImTextStrToUtf8(char * out_buf,int out_buf_size,const ImWchar * in_text,const ImWchar * in_text_end)1795 int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
1796 {
1797     char* buf_p = out_buf;
1798     const char* buf_end = out_buf + out_buf_size;
1799     while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
1800     {
1801         unsigned int c = (unsigned int)(*in_text++);
1802         if (c < 0x80)
1803             *buf_p++ = (char)c;
1804         else
1805             buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);
1806     }
1807     *buf_p = 0;
1808     return (int)(buf_p - out_buf);
1809 }
1810 
ImTextCountUtf8BytesFromStr(const ImWchar * in_text,const ImWchar * in_text_end)1811 int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
1812 {
1813     int bytes_count = 0;
1814     while ((!in_text_end || in_text < in_text_end) && *in_text)
1815     {
1816         unsigned int c = (unsigned int)(*in_text++);
1817         if (c < 0x80)
1818             bytes_count++;
1819         else
1820             bytes_count += ImTextCountUtf8BytesFromChar(c);
1821     }
1822     return bytes_count;
1823 }
1824 
1825 //-----------------------------------------------------------------------------
1826 // [SECTION] MISC HELPERS/UTILITIES (Color functions)
1827 // Note: The Convert functions are early design which are not consistent with other API.
1828 //-----------------------------------------------------------------------------
1829 
ImAlphaBlendColors(ImU32 col_a,ImU32 col_b)1830 IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
1831 {
1832     float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
1833     int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
1834     int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
1835     int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
1836     return IM_COL32(r, g, b, 0xFF);
1837 }
1838 
ColorConvertU32ToFloat4(ImU32 in)1839 ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
1840 {
1841     float s = 1.0f / 255.0f;
1842     return ImVec4(
1843         ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
1844         ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
1845         ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
1846         ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
1847 }
1848 
ColorConvertFloat4ToU32(const ImVec4 & in)1849 ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
1850 {
1851     ImU32 out;
1852     out  = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
1853     out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
1854     out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
1855     out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
1856     return out;
1857 }
1858 
1859 // Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
1860 // Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
ColorConvertRGBtoHSV(float r,float g,float b,float & out_h,float & out_s,float & out_v)1861 void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
1862 {
1863     float K = 0.f;
1864     if (g < b)
1865     {
1866         ImSwap(g, b);
1867         K = -1.f;
1868     }
1869     if (r < g)
1870     {
1871         ImSwap(r, g);
1872         K = -2.f / 6.f - K;
1873     }
1874 
1875     const float chroma = r - (g < b ? g : b);
1876     out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
1877     out_s = chroma / (r + 1e-20f);
1878     out_v = r;
1879 }
1880 
1881 // Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
1882 // also http://en.wikipedia.org/wiki/HSL_and_HSV
ColorConvertHSVtoRGB(float h,float s,float v,float & out_r,float & out_g,float & out_b)1883 void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
1884 {
1885     if (s == 0.0f)
1886     {
1887         // gray
1888         out_r = out_g = out_b = v;
1889         return;
1890     }
1891 
1892     h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
1893     int   i = (int)h;
1894     float f = h - (float)i;
1895     float p = v * (1.0f - s);
1896     float q = v * (1.0f - s * f);
1897     float t = v * (1.0f - s * (1.0f - f));
1898 
1899     switch (i)
1900     {
1901     case 0: out_r = v; out_g = t; out_b = p; break;
1902     case 1: out_r = q; out_g = v; out_b = p; break;
1903     case 2: out_r = p; out_g = v; out_b = t; break;
1904     case 3: out_r = p; out_g = q; out_b = v; break;
1905     case 4: out_r = t; out_g = p; out_b = v; break;
1906     case 5: default: out_r = v; out_g = p; out_b = q; break;
1907     }
1908 }
1909 
1910 //-----------------------------------------------------------------------------
1911 // [SECTION] ImGuiStorage
1912 // Helper: Key->value storage
1913 //-----------------------------------------------------------------------------
1914 
1915 // std::lower_bound but without the bullshit
LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair> & data,ImGuiID key)1916 static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)
1917 {
1918     ImGuiStorage::ImGuiStoragePair* first = data.Data;
1919     ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;
1920     size_t count = (size_t)(last - first);
1921     while (count > 0)
1922     {
1923         size_t count2 = count >> 1;
1924         ImGuiStorage::ImGuiStoragePair* mid = first + count2;
1925         if (mid->key < key)
1926         {
1927             first = ++mid;
1928             count -= count2 + 1;
1929         }
1930         else
1931         {
1932             count = count2;
1933         }
1934     }
1935     return first;
1936 }
1937 
1938 // For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
BuildSortByKey()1939 void ImGuiStorage::BuildSortByKey()
1940 {
1941     struct StaticFunc
1942     {
1943         static int IMGUI_CDECL PairCompareByID(const void* lhs, const void* rhs)
1944         {
1945             // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
1946             if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;
1947             if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;
1948             return 0;
1949         }
1950     };
1951     if (Data.Size > 1)
1952         ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairCompareByID);
1953 }
1954 
GetInt(ImGuiID key,int default_val) const1955 int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
1956 {
1957     ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
1958     if (it == Data.end() || it->key != key)
1959         return default_val;
1960     return it->val_i;
1961 }
1962 
GetBool(ImGuiID key,bool default_val) const1963 bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
1964 {
1965     return GetInt(key, default_val ? 1 : 0) != 0;
1966 }
1967 
GetFloat(ImGuiID key,float default_val) const1968 float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
1969 {
1970     ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
1971     if (it == Data.end() || it->key != key)
1972         return default_val;
1973     return it->val_f;
1974 }
1975 
GetVoidPtr(ImGuiID key) const1976 void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
1977 {
1978     ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
1979     if (it == Data.end() || it->key != key)
1980         return NULL;
1981     return it->val_p;
1982 }
1983 
1984 // 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.
GetIntRef(ImGuiID key,int default_val)1985 int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
1986 {
1987     ImGuiStoragePair* it = LowerBound(Data, key);
1988     if (it == Data.end() || it->key != key)
1989         it = Data.insert(it, ImGuiStoragePair(key, default_val));
1990     return &it->val_i;
1991 }
1992 
GetBoolRef(ImGuiID key,bool default_val)1993 bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
1994 {
1995     return (bool*)GetIntRef(key, default_val ? 1 : 0);
1996 }
1997 
GetFloatRef(ImGuiID key,float default_val)1998 float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
1999 {
2000     ImGuiStoragePair* it = LowerBound(Data, key);
2001     if (it == Data.end() || it->key != key)
2002         it = Data.insert(it, ImGuiStoragePair(key, default_val));
2003     return &it->val_f;
2004 }
2005 
GetVoidPtrRef(ImGuiID key,void * default_val)2006 void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2007 {
2008     ImGuiStoragePair* it = LowerBound(Data, key);
2009     if (it == Data.end() || it->key != key)
2010         it = Data.insert(it, ImGuiStoragePair(key, default_val));
2011     return &it->val_p;
2012 }
2013 
2014 // 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)
SetInt(ImGuiID key,int val)2015 void ImGuiStorage::SetInt(ImGuiID key, int val)
2016 {
2017     ImGuiStoragePair* it = LowerBound(Data, key);
2018     if (it == Data.end() || it->key != key)
2019     {
2020         Data.insert(it, ImGuiStoragePair(key, val));
2021         return;
2022     }
2023     it->val_i = val;
2024 }
2025 
SetBool(ImGuiID key,bool val)2026 void ImGuiStorage::SetBool(ImGuiID key, bool val)
2027 {
2028     SetInt(key, val ? 1 : 0);
2029 }
2030 
SetFloat(ImGuiID key,float val)2031 void ImGuiStorage::SetFloat(ImGuiID key, float val)
2032 {
2033     ImGuiStoragePair* it = LowerBound(Data, key);
2034     if (it == Data.end() || it->key != key)
2035     {
2036         Data.insert(it, ImGuiStoragePair(key, val));
2037         return;
2038     }
2039     it->val_f = val;
2040 }
2041 
SetVoidPtr(ImGuiID key,void * val)2042 void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2043 {
2044     ImGuiStoragePair* it = LowerBound(Data, key);
2045     if (it == Data.end() || it->key != key)
2046     {
2047         Data.insert(it, ImGuiStoragePair(key, val));
2048         return;
2049     }
2050     it->val_p = val;
2051 }
2052 
SetAllInt(int v)2053 void ImGuiStorage::SetAllInt(int v)
2054 {
2055     for (int i = 0; i < Data.Size; i++)
2056         Data[i].val_i = v;
2057 }
2058 
2059 //-----------------------------------------------------------------------------
2060 // [SECTION] ImGuiTextFilter
2061 //-----------------------------------------------------------------------------
2062 
2063 // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
ImGuiTextFilter(const char * default_filter)2064 ImGuiTextFilter::ImGuiTextFilter(const char* default_filter)
2065 {
2066     if (default_filter)
2067     {
2068         ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
2069         Build();
2070     }
2071     else
2072     {
2073         InputBuf[0] = 0;
2074         CountGrep = 0;
2075     }
2076 }
2077 
Draw(const char * label,float width)2078 bool ImGuiTextFilter::Draw(const char* label, float width)
2079 {
2080     if (width != 0.0f)
2081         ImGui::SetNextItemWidth(width);
2082     bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
2083     if (value_changed)
2084         Build();
2085     return value_changed;
2086 }
2087 
split(char separator,ImVector<ImGuiTextRange> * out) const2088 void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
2089 {
2090     out->resize(0);
2091     const char* wb = b;
2092     const char* we = wb;
2093     while (we < e)
2094     {
2095         if (*we == separator)
2096         {
2097             out->push_back(ImGuiTextRange(wb, we));
2098             wb = we + 1;
2099         }
2100         we++;
2101     }
2102     if (wb != we)
2103         out->push_back(ImGuiTextRange(wb, we));
2104 }
2105 
Build()2106 void ImGuiTextFilter::Build()
2107 {
2108     Filters.resize(0);
2109     ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
2110     input_range.split(',', &Filters);
2111 
2112     CountGrep = 0;
2113     for (int i = 0; i != Filters.Size; i++)
2114     {
2115         ImGuiTextRange& f = Filters[i];
2116         while (f.b < f.e && ImCharIsBlankA(f.b[0]))
2117             f.b++;
2118         while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
2119             f.e--;
2120         if (f.empty())
2121             continue;
2122         if (Filters[i].b[0] != '-')
2123             CountGrep += 1;
2124     }
2125 }
2126 
PassFilter(const char * text,const char * text_end) const2127 bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
2128 {
2129     if (Filters.empty())
2130         return true;
2131 
2132     if (text == NULL)
2133         text = "";
2134 
2135     for (int i = 0; i != Filters.Size; i++)
2136     {
2137         const ImGuiTextRange& f = Filters[i];
2138         if (f.empty())
2139             continue;
2140         if (f.b[0] == '-')
2141         {
2142             // Subtract
2143             if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
2144                 return false;
2145         }
2146         else
2147         {
2148             // Grep
2149             if (ImStristr(text, text_end, f.b, f.e) != NULL)
2150                 return true;
2151         }
2152     }
2153 
2154     // Implicit * grep
2155     if (CountGrep == 0)
2156         return true;
2157 
2158     return false;
2159 }
2160 
2161 //-----------------------------------------------------------------------------
2162 // [SECTION] ImGuiTextBuffer
2163 //-----------------------------------------------------------------------------
2164 
2165 // On some platform vsnprintf() takes va_list by reference and modifies it.
2166 // va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
2167 #ifndef va_copy
2168 #if defined(__GNUC__) || defined(__clang__)
2169 #define va_copy(dest, src) __builtin_va_copy(dest, src)
2170 #else
2171 #define va_copy(dest, src) (dest = src)
2172 #endif
2173 #endif
2174 
2175 char ImGuiTextBuffer::EmptyString[1] = { 0 };
2176 
append(const char * str,const char * str_end)2177 void ImGuiTextBuffer::append(const char* str, const char* str_end)
2178 {
2179     int len = str_end ? (int)(str_end - str) : (int)strlen(str);
2180 
2181     // Add zero-terminator the first time
2182     const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2183     const int needed_sz = write_off + len;
2184     if (write_off + len >= Buf.Capacity)
2185     {
2186         int new_capacity = Buf.Capacity * 2;
2187         Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2188     }
2189 
2190     Buf.resize(needed_sz);
2191     memcpy(&Buf[write_off - 1], str, (size_t)len);
2192     Buf[write_off - 1 + len] = 0;
2193 }
2194 
appendf(const char * fmt,...)2195 void ImGuiTextBuffer::appendf(const char* fmt, ...)
2196 {
2197     va_list args;
2198     va_start(args, fmt);
2199     appendfv(fmt, args);
2200     va_end(args);
2201 }
2202 
2203 // Helper: Text buffer for logging/accumulating text
appendfv(const char * fmt,va_list args)2204 void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
2205 {
2206     va_list args_copy;
2207     va_copy(args_copy, args);
2208 
2209     int len = ImFormatStringV(NULL, 0, fmt, args);         // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
2210     if (len <= 0)
2211     {
2212         va_end(args_copy);
2213         return;
2214     }
2215 
2216     // Add zero-terminator the first time
2217     const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2218     const int needed_sz = write_off + len;
2219     if (write_off + len >= Buf.Capacity)
2220     {
2221         int new_capacity = Buf.Capacity * 2;
2222         Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2223     }
2224 
2225     Buf.resize(needed_sz);
2226     ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
2227     va_end(args_copy);
2228 }
2229 
2230 //-----------------------------------------------------------------------------
2231 // [SECTION] ImGuiListClipper
2232 // This is currently not as flexible/powerful as it should be and really confusing/spaghetti, mostly because we changed
2233 // the API mid-way through development and support two ways to using the clipper, needs some rework (see TODO)
2234 //-----------------------------------------------------------------------------
2235 
2236 // FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
2237 // The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
GetSkipItemForListClipping()2238 static bool GetSkipItemForListClipping()
2239 {
2240     ImGuiContext& g = *GImGui;
2241     return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
2242 }
2243 
2244 // Helper to calculate coarse clipping of large list of evenly sized items.
2245 // NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern.
2246 // NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX
CalcListClipping(int items_count,float items_height,int * out_items_display_start,int * out_items_display_end)2247 void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
2248 {
2249     ImGuiContext& g = *GImGui;
2250     ImGuiWindow* window = g.CurrentWindow;
2251     if (g.LogEnabled)
2252     {
2253         // If logging is active, do not perform any clipping
2254         *out_items_display_start = 0;
2255         *out_items_display_end = items_count;
2256         return;
2257     }
2258     if (GetSkipItemForListClipping())
2259     {
2260         *out_items_display_start = *out_items_display_end = 0;
2261         return;
2262     }
2263 
2264     // We create the union of the ClipRect and the scoring rect which at worst should be 1 page away from ClipRect
2265     ImRect unclipped_rect = window->ClipRect;
2266     if (g.NavMoveScoringItems)
2267         unclipped_rect.Add(g.NavScoringRect);
2268     if (g.NavJustMovedToId && window->NavLastIds[0] == g.NavJustMovedToId)
2269         unclipped_rect.Add(ImRect(window->Pos + window->NavRectRel[0].Min, window->Pos + window->NavRectRel[0].Max)); // Could store and use NavJustMovedToRectRel
2270 
2271     const ImVec2 pos = window->DC.CursorPos;
2272     int start = (int)((unclipped_rect.Min.y - pos.y) / items_height);
2273     int end = (int)((unclipped_rect.Max.y - pos.y) / items_height);
2274 
2275     // When performing a navigation request, ensure we have one item extra in the direction we are moving to
2276     if (g.NavMoveScoringItems && g.NavMoveClipDir == ImGuiDir_Up)
2277         start--;
2278     if (g.NavMoveScoringItems && g.NavMoveClipDir == ImGuiDir_Down)
2279         end++;
2280 
2281     start = ImClamp(start, 0, items_count);
2282     end = ImClamp(end + 1, start, items_count);
2283     *out_items_display_start = start;
2284     *out_items_display_end = end;
2285 }
2286 
SetCursorPosYAndSetupForPrevLine(float pos_y,float line_height)2287 static void SetCursorPosYAndSetupForPrevLine(float pos_y, float line_height)
2288 {
2289     // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
2290     // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
2291     // The clipper should probably have a 4th step to display the last item in a regular manner.
2292     ImGuiContext& g = *GImGui;
2293     ImGuiWindow* window = g.CurrentWindow;
2294     float off_y = pos_y - window->DC.CursorPos.y;
2295     window->DC.CursorPos.y = pos_y;
2296     window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y);
2297     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.
2298     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.
2299     if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
2300         columns->LineMinY = window->DC.CursorPos.y;                         // Setting this so that cell Y position are set properly
2301     if (ImGuiTable* table = g.CurrentTable)
2302     {
2303         if (table->IsInsideRow)
2304             ImGui::TableEndRow(table);
2305         table->RowPosY2 = window->DC.CursorPos.y;
2306         const int row_increase = (int)((off_y / line_height) + 0.5f);
2307         //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
2308         table->RowBgColorCounter += row_increase;
2309     }
2310 }
2311 
ImGuiListClipper()2312 ImGuiListClipper::ImGuiListClipper()
2313 {
2314     memset(this, 0, sizeof(*this));
2315     ItemsCount = -1;
2316 }
2317 
~ImGuiListClipper()2318 ImGuiListClipper::~ImGuiListClipper()
2319 {
2320     IM_ASSERT(ItemsCount == -1 && "Forgot to call End(), or to Step() until false?");
2321 }
2322 
2323 // Use case A: Begin() called from constructor with items_height<0, then called again from Step() in StepNo 1
2324 // Use case B: Begin() called from constructor with items_height>0
2325 // FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style.
Begin(int items_count,float items_height)2326 void ImGuiListClipper::Begin(int items_count, float items_height)
2327 {
2328     ImGuiContext& g = *GImGui;
2329     ImGuiWindow* window = g.CurrentWindow;
2330 
2331     if (ImGuiTable* table = g.CurrentTable)
2332         if (table->IsInsideRow)
2333             ImGui::TableEndRow(table);
2334 
2335     StartPosY = window->DC.CursorPos.y;
2336     ItemsHeight = items_height;
2337     ItemsCount = items_count;
2338     ItemsFrozen = 0;
2339     StepNo = 0;
2340     DisplayStart = -1;
2341     DisplayEnd = 0;
2342 }
2343 
End()2344 void ImGuiListClipper::End()
2345 {
2346     if (ItemsCount < 0) // Already ended
2347         return;
2348 
2349     // In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user.
2350     if (ItemsCount < INT_MAX && DisplayStart >= 0)
2351         SetCursorPosYAndSetupForPrevLine(StartPosY + (ItemsCount - ItemsFrozen) * ItemsHeight, ItemsHeight);
2352     ItemsCount = -1;
2353     StepNo = 3;
2354 }
2355 
Step()2356 bool ImGuiListClipper::Step()
2357 {
2358     ImGuiContext& g = *GImGui;
2359     ImGuiWindow* window = g.CurrentWindow;
2360 
2361     ImGuiTable* table = g.CurrentTable;
2362     if (table && table->IsInsideRow)
2363         ImGui::TableEndRow(table);
2364 
2365     // No items
2366     if (ItemsCount == 0 || GetSkipItemForListClipping())
2367     {
2368         End();
2369         return false;
2370     }
2371 
2372     // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
2373     if (StepNo == 0)
2374     {
2375         // While we are in frozen row state, keep displaying items one by one, unclipped
2376         // FIXME: Could be stored as a table-agnostic state.
2377         if (table != NULL && !table->IsUnfrozenRows)
2378         {
2379             DisplayStart = ItemsFrozen;
2380             DisplayEnd = ItemsFrozen + 1;
2381             ItemsFrozen++;
2382             return true;
2383         }
2384 
2385         StartPosY = window->DC.CursorPos.y;
2386         if (ItemsHeight <= 0.0f)
2387         {
2388             // Submit the first item so we can measure its height (generally it is 0..1)
2389             DisplayStart = ItemsFrozen;
2390             DisplayEnd = ItemsFrozen + 1;
2391             StepNo = 1;
2392             return true;
2393         }
2394 
2395         // Already has item height (given by user in Begin): skip to calculating step
2396         DisplayStart = DisplayEnd;
2397         StepNo = 2;
2398     }
2399 
2400     // Step 1: the clipper infer height from first element
2401     if (StepNo == 1)
2402     {
2403         IM_ASSERT(ItemsHeight <= 0.0f);
2404         if (table)
2405         {
2406             const float pos_y1 = table->RowPosY1;   // Using this instead of StartPosY to handle clipper straddling the frozen row
2407             const float pos_y2 = table->RowPosY2;   // Using this instead of CursorPos.y to take account of tallest cell.
2408             ItemsHeight = pos_y2 - pos_y1;
2409             window->DC.CursorPos.y = pos_y2;
2410         }
2411         else
2412         {
2413             ItemsHeight = window->DC.CursorPos.y - StartPosY;
2414         }
2415         IM_ASSERT(ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
2416         StepNo = 2;
2417     }
2418 
2419     // Reached end of list
2420     if (DisplayEnd >= ItemsCount)
2421     {
2422         End();
2423         return false;
2424     }
2425 
2426     // Step 2: calculate the actual range of elements to display, and position the cursor before the first element
2427     if (StepNo == 2)
2428     {
2429         IM_ASSERT(ItemsHeight > 0.0f);
2430 
2431         int already_submitted = DisplayEnd;
2432         ImGui::CalcListClipping(ItemsCount - already_submitted, ItemsHeight, &DisplayStart, &DisplayEnd);
2433         DisplayStart += already_submitted;
2434         DisplayEnd += already_submitted;
2435 
2436         // Seek cursor
2437         if (DisplayStart > already_submitted)
2438             SetCursorPosYAndSetupForPrevLine(StartPosY + (DisplayStart - ItemsFrozen) * ItemsHeight, ItemsHeight);
2439 
2440         StepNo = 3;
2441         return true;
2442     }
2443 
2444     // Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
2445     // Advance the cursor to the end of the list and then returns 'false' to end the loop.
2446     if (StepNo == 3)
2447     {
2448         // Seek cursor
2449         if (ItemsCount < INT_MAX)
2450             SetCursorPosYAndSetupForPrevLine(StartPosY + (ItemsCount - ItemsFrozen) * ItemsHeight, ItemsHeight); // advance cursor
2451         ItemsCount = -1;
2452         return false;
2453     }
2454 
2455     IM_ASSERT(0);
2456     return false;
2457 }
2458 
2459 //-----------------------------------------------------------------------------
2460 // [SECTION] STYLING
2461 //-----------------------------------------------------------------------------
2462 
GetStyle()2463 ImGuiStyle& ImGui::GetStyle()
2464 {
2465     IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
2466     return GImGui->Style;
2467 }
2468 
GetColorU32(ImGuiCol idx,float alpha_mul)2469 ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
2470 {
2471     ImGuiStyle& style = GImGui->Style;
2472     ImVec4 c = style.Colors[idx];
2473     c.w *= style.Alpha * alpha_mul;
2474     return ColorConvertFloat4ToU32(c);
2475 }
2476 
GetColorU32(const ImVec4 & col)2477 ImU32 ImGui::GetColorU32(const ImVec4& col)
2478 {
2479     ImGuiStyle& style = GImGui->Style;
2480     ImVec4 c = col;
2481     c.w *= style.Alpha;
2482     return ColorConvertFloat4ToU32(c);
2483 }
2484 
GetStyleColorVec4(ImGuiCol idx)2485 const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
2486 {
2487     ImGuiStyle& style = GImGui->Style;
2488     return style.Colors[idx];
2489 }
2490 
GetColorU32(ImU32 col)2491 ImU32 ImGui::GetColorU32(ImU32 col)
2492 {
2493     ImGuiStyle& style = GImGui->Style;
2494     if (style.Alpha >= 1.0f)
2495         return col;
2496     ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
2497     a = (ImU32)(a * style.Alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
2498     return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
2499 }
2500 
2501 // 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
PushStyleColor(ImGuiCol idx,ImU32 col)2502 void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
2503 {
2504     ImGuiContext& g = *GImGui;
2505     ImGuiColorMod backup;
2506     backup.Col = idx;
2507     backup.BackupValue = g.Style.Colors[idx];
2508     g.ColorStack.push_back(backup);
2509     g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
2510 }
2511 
PushStyleColor(ImGuiCol idx,const ImVec4 & col)2512 void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
2513 {
2514     ImGuiContext& g = *GImGui;
2515     ImGuiColorMod backup;
2516     backup.Col = idx;
2517     backup.BackupValue = g.Style.Colors[idx];
2518     g.ColorStack.push_back(backup);
2519     g.Style.Colors[idx] = col;
2520 }
2521 
PopStyleColor(int count)2522 void ImGui::PopStyleColor(int count)
2523 {
2524     ImGuiContext& g = *GImGui;
2525     while (count > 0)
2526     {
2527         ImGuiColorMod& backup = g.ColorStack.back();
2528         g.Style.Colors[backup.Col] = backup.BackupValue;
2529         g.ColorStack.pop_back();
2530         count--;
2531     }
2532 }
2533 
2534 struct ImGuiStyleVarInfo
2535 {
2536     ImGuiDataType   Type;
2537     ImU32           Count;
2538     ImU32           Offset;
GetVarPtrImGuiStyleVarInfo2539     void*           GetVarPtr(ImGuiStyle* style) const { return (void*)((unsigned char*)style + Offset); }
2540 };
2541 
2542 static const ImGuiStyleVarInfo GStyleVarInfo[] =
2543 {
2544     { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) },               // ImGuiStyleVar_Alpha
2545     { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, DisabledAlpha) },       // ImGuiStyleVar_DisabledAlpha
2546     { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) },       // ImGuiStyleVar_WindowPadding
2547     { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) },      // ImGuiStyleVar_WindowRounding
2548     { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) },    // ImGuiStyleVar_WindowBorderSize
2549     { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) },       // ImGuiStyleVar_WindowMinSize
2550     { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) },    // ImGuiStyleVar_WindowTitleAlign
2551     { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) },       // ImGuiStyleVar_ChildRounding
2552     { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) },     // ImGuiStyleVar_ChildBorderSize
2553     { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) },       // ImGuiStyleVar_PopupRounding
2554     { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) },     // ImGuiStyleVar_PopupBorderSize
2555     { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) },        // ImGuiStyleVar_FramePadding
2556     { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) },       // ImGuiStyleVar_FrameRounding
2557     { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) },     // ImGuiStyleVar_FrameBorderSize
2558     { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) },         // ImGuiStyleVar_ItemSpacing
2559     { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) },    // ImGuiStyleVar_ItemInnerSpacing
2560     { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) },       // ImGuiStyleVar_IndentSpacing
2561     { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, CellPadding) },         // ImGuiStyleVar_CellPadding
2562     { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) },       // ImGuiStyleVar_ScrollbarSize
2563     { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) },   // ImGuiStyleVar_ScrollbarRounding
2564     { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) },         // ImGuiStyleVar_GrabMinSize
2565     { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) },        // ImGuiStyleVar_GrabRounding
2566     { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) },         // ImGuiStyleVar_TabRounding
2567     { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) },     // ImGuiStyleVar_ButtonTextAlign
2568     { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
2569 };
2570 
GetStyleVarInfo(ImGuiStyleVar idx)2571 static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx)
2572 {
2573     IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
2574     IM_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
2575     return &GStyleVarInfo[idx];
2576 }
2577 
PushStyleVar(ImGuiStyleVar idx,float val)2578 void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
2579 {
2580     const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
2581     if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
2582     {
2583         ImGuiContext& g = *GImGui;
2584         float* pvar = (float*)var_info->GetVarPtr(&g.Style);
2585         g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
2586         *pvar = val;
2587         return;
2588     }
2589     IM_ASSERT(0 && "Called PushStyleVar() float variant but variable is not a float!");
2590 }
2591 
PushStyleVar(ImGuiStyleVar idx,const ImVec2 & val)2592 void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
2593 {
2594     const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
2595     if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
2596     {
2597         ImGuiContext& g = *GImGui;
2598         ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
2599         g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
2600         *pvar = val;
2601         return;
2602     }
2603     IM_ASSERT(0 && "Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!");
2604 }
2605 
PopStyleVar(int count)2606 void ImGui::PopStyleVar(int count)
2607 {
2608     ImGuiContext& g = *GImGui;
2609     while (count > 0)
2610     {
2611         // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
2612         ImGuiStyleMod& backup = g.StyleVarStack.back();
2613         const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx);
2614         void* data = info->GetVarPtr(&g.Style);
2615         if (info->Type == ImGuiDataType_Float && info->Count == 1)      { ((float*)data)[0] = backup.BackupFloat[0]; }
2616         else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
2617         g.StyleVarStack.pop_back();
2618         count--;
2619     }
2620 }
2621 
GetStyleColorName(ImGuiCol idx)2622 const char* ImGui::GetStyleColorName(ImGuiCol idx)
2623 {
2624     // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
2625     switch (idx)
2626     {
2627     case ImGuiCol_Text: return "Text";
2628     case ImGuiCol_TextDisabled: return "TextDisabled";
2629     case ImGuiCol_WindowBg: return "WindowBg";
2630     case ImGuiCol_ChildBg: return "ChildBg";
2631     case ImGuiCol_PopupBg: return "PopupBg";
2632     case ImGuiCol_Border: return "Border";
2633     case ImGuiCol_BorderShadow: return "BorderShadow";
2634     case ImGuiCol_FrameBg: return "FrameBg";
2635     case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
2636     case ImGuiCol_FrameBgActive: return "FrameBgActive";
2637     case ImGuiCol_TitleBg: return "TitleBg";
2638     case ImGuiCol_TitleBgActive: return "TitleBgActive";
2639     case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
2640     case ImGuiCol_MenuBarBg: return "MenuBarBg";
2641     case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
2642     case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
2643     case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
2644     case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
2645     case ImGuiCol_CheckMark: return "CheckMark";
2646     case ImGuiCol_SliderGrab: return "SliderGrab";
2647     case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
2648     case ImGuiCol_Button: return "Button";
2649     case ImGuiCol_ButtonHovered: return "ButtonHovered";
2650     case ImGuiCol_ButtonActive: return "ButtonActive";
2651     case ImGuiCol_Header: return "Header";
2652     case ImGuiCol_HeaderHovered: return "HeaderHovered";
2653     case ImGuiCol_HeaderActive: return "HeaderActive";
2654     case ImGuiCol_Separator: return "Separator";
2655     case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
2656     case ImGuiCol_SeparatorActive: return "SeparatorActive";
2657     case ImGuiCol_ResizeGrip: return "ResizeGrip";
2658     case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
2659     case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
2660     case ImGuiCol_Tab: return "Tab";
2661     case ImGuiCol_TabHovered: return "TabHovered";
2662     case ImGuiCol_TabActive: return "TabActive";
2663     case ImGuiCol_TabUnfocused: return "TabUnfocused";
2664     case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
2665     case ImGuiCol_PlotLines: return "PlotLines";
2666     case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
2667     case ImGuiCol_PlotHistogram: return "PlotHistogram";
2668     case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
2669     case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
2670     case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
2671     case ImGuiCol_TableBorderLight: return "TableBorderLight";
2672     case ImGuiCol_TableRowBg: return "TableRowBg";
2673     case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
2674     case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
2675     case ImGuiCol_DragDropTarget: return "DragDropTarget";
2676     case ImGuiCol_NavHighlight: return "NavHighlight";
2677     case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
2678     case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
2679     case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
2680     }
2681     IM_ASSERT(0);
2682     return "Unknown";
2683 }
2684 
2685 
2686 //-----------------------------------------------------------------------------
2687 // [SECTION] RENDER HELPERS
2688 // Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
2689 // we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
2690 // Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
2691 //-----------------------------------------------------------------------------
2692 
FindRenderedTextEnd(const char * text,const char * text_end)2693 const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
2694 {
2695     const char* text_display_end = text;
2696     if (!text_end)
2697         text_end = (const char*)-1;
2698 
2699     while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
2700         text_display_end++;
2701     return text_display_end;
2702 }
2703 
2704 // Internal ImGui functions to render text
2705 // RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
RenderText(ImVec2 pos,const char * text,const char * text_end,bool hide_text_after_hash)2706 void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
2707 {
2708     ImGuiContext& g = *GImGui;
2709     ImGuiWindow* window = g.CurrentWindow;
2710 
2711     // Hide anything after a '##' string
2712     const char* text_display_end;
2713     if (hide_text_after_hash)
2714     {
2715         text_display_end = FindRenderedTextEnd(text, text_end);
2716     }
2717     else
2718     {
2719         if (!text_end)
2720             text_end = text + strlen(text); // FIXME-OPT
2721         text_display_end = text_end;
2722     }
2723 
2724     if (text != text_display_end)
2725     {
2726         window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
2727         if (g.LogEnabled)
2728             LogRenderedText(&pos, text, text_display_end);
2729     }
2730 }
2731 
RenderTextWrapped(ImVec2 pos,const char * text,const char * text_end,float wrap_width)2732 void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
2733 {
2734     ImGuiContext& g = *GImGui;
2735     ImGuiWindow* window = g.CurrentWindow;
2736 
2737     if (!text_end)
2738         text_end = text + strlen(text); // FIXME-OPT
2739 
2740     if (text != text_end)
2741     {
2742         window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
2743         if (g.LogEnabled)
2744             LogRenderedText(&pos, text, text_end);
2745     }
2746 }
2747 
2748 // Default clip_rect uses (pos_min,pos_max)
2749 // Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
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)2750 void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
2751 {
2752     // Perform CPU side clipping for single clipped element to avoid using scissor state
2753     ImVec2 pos = pos_min;
2754     const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
2755 
2756     const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
2757     const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
2758     bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
2759     if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
2760         need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
2761 
2762     // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
2763     if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
2764     if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
2765 
2766     // Render
2767     if (need_clipping)
2768     {
2769         ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
2770         draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
2771     }
2772     else
2773     {
2774         draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
2775     }
2776 }
2777 
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)2778 void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
2779 {
2780     // Hide anything after a '##' string
2781     const char* text_display_end = FindRenderedTextEnd(text, text_end);
2782     const int text_len = (int)(text_display_end - text);
2783     if (text_len == 0)
2784         return;
2785 
2786     ImGuiContext& g = *GImGui;
2787     ImGuiWindow* window = g.CurrentWindow;
2788     RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
2789     if (g.LogEnabled)
2790         LogRenderedText(&pos_min, text, text_display_end);
2791 }
2792 
2793 
2794 // Another overly complex function until we reorganize everything into a nice all-in-one helper.
2795 // 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.
2796 // 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.
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)2797 void 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)
2798 {
2799     ImGuiContext& g = *GImGui;
2800     if (text_end_full == NULL)
2801         text_end_full = FindRenderedTextEnd(text);
2802     const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
2803 
2804     //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));
2805     //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));
2806     //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
2807     // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
2808     if (text_size.x > pos_max.x - pos_min.x)
2809     {
2810         // Hello wo...
2811         // |       |   |
2812         // min   max   ellipsis_max
2813         //          <-> this is generally some padding value
2814 
2815         const ImFont* font = draw_list->_Data->Font;
2816         const float font_size = draw_list->_Data->FontSize;
2817         const char* text_end_ellipsis = NULL;
2818 
2819         ImWchar ellipsis_char = font->EllipsisChar;
2820         int ellipsis_char_count = 1;
2821         if (ellipsis_char == (ImWchar)-1)
2822         {
2823             ellipsis_char = font->DotChar;
2824             ellipsis_char_count = 3;
2825         }
2826         const ImFontGlyph* glyph = font->FindGlyph(ellipsis_char);
2827 
2828         float ellipsis_glyph_width = glyph->X1;                 // Width of the glyph with no padding on either side
2829         float ellipsis_total_width = ellipsis_glyph_width;      // Full width of entire ellipsis
2830 
2831         if (ellipsis_char_count > 1)
2832         {
2833             // Full ellipsis size without free spacing after it.
2834             const float spacing_between_dots = 1.0f * (draw_list->_Data->FontSize / font->FontSize);
2835             ellipsis_glyph_width = glyph->X1 - glyph->X0 + spacing_between_dots;
2836             ellipsis_total_width = ellipsis_glyph_width * (float)ellipsis_char_count - spacing_between_dots;
2837         }
2838 
2839         // We can now claim the space between pos_max.x and ellipsis_max.x
2840         const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_total_width) - pos_min.x, 1.0f);
2841         float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
2842         if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
2843         {
2844             // Always display at least 1 character if there's no room for character + ellipsis
2845             text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
2846             text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
2847         }
2848         while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
2849         {
2850             // 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)
2851             text_end_ellipsis--;
2852             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
2853         }
2854 
2855         // Render text, render ellipsis
2856         RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
2857         float ellipsis_x = pos_min.x + text_size_clipped_x;
2858         if (ellipsis_x + ellipsis_total_width <= ellipsis_max_x)
2859             for (int i = 0; i < ellipsis_char_count; i++)
2860             {
2861                 font->RenderChar(draw_list, font_size, ImVec2(ellipsis_x, pos_min.y), GetColorU32(ImGuiCol_Text), ellipsis_char);
2862                 ellipsis_x += ellipsis_glyph_width;
2863             }
2864     }
2865     else
2866     {
2867         RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
2868     }
2869 
2870     if (g.LogEnabled)
2871         LogRenderedText(&pos_min, text, text_end_full);
2872 }
2873 
2874 // Render a rectangle shaped with optional rounding and borders
RenderFrame(ImVec2 p_min,ImVec2 p_max,ImU32 fill_col,bool border,float rounding)2875 void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
2876 {
2877     ImGuiContext& g = *GImGui;
2878     ImGuiWindow* window = g.CurrentWindow;
2879     window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
2880     const float border_size = g.Style.FrameBorderSize;
2881     if (border && border_size > 0.0f)
2882     {
2883         window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
2884         window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
2885     }
2886 }
2887 
RenderFrameBorder(ImVec2 p_min,ImVec2 p_max,float rounding)2888 void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
2889 {
2890     ImGuiContext& g = *GImGui;
2891     ImGuiWindow* window = g.CurrentWindow;
2892     const float border_size = g.Style.FrameBorderSize;
2893     if (border_size > 0.0f)
2894     {
2895         window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
2896         window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
2897     }
2898 }
2899 
RenderNavHighlight(const ImRect & bb,ImGuiID id,ImGuiNavHighlightFlags flags)2900 void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
2901 {
2902     ImGuiContext& g = *GImGui;
2903     if (id != g.NavId)
2904         return;
2905     if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
2906         return;
2907     ImGuiWindow* window = g.CurrentWindow;
2908     if (window->DC.NavHideHighlightOneFrame)
2909         return;
2910 
2911     float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
2912     ImRect display_rect = bb;
2913     display_rect.ClipWith(window->ClipRect);
2914     if (flags & ImGuiNavHighlightFlags_TypeDefault)
2915     {
2916         const float THICKNESS = 2.0f;
2917         const float DISTANCE = 3.0f + THICKNESS * 0.5f;
2918         display_rect.Expand(ImVec2(DISTANCE, DISTANCE));
2919         bool fully_visible = window->ClipRect.Contains(display_rect);
2920         if (!fully_visible)
2921             window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
2922         window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), display_rect.Max - ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, 0, THICKNESS);
2923         if (!fully_visible)
2924             window->DrawList->PopClipRect();
2925     }
2926     if (flags & ImGuiNavHighlightFlags_TypeThin)
2927     {
2928         window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, 1.0f);
2929     }
2930 }
2931 
2932 //-----------------------------------------------------------------------------
2933 // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
2934 //-----------------------------------------------------------------------------
2935 
2936 // ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
ImGuiWindow(ImGuiContext * context,const char * name)2937 ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name) : DrawListInst(NULL)
2938 {
2939     memset(this, 0, sizeof(*this));
2940     Name = ImStrdup(name);
2941     NameBufLen = (int)strlen(name) + 1;
2942     ID = ImHashStr(name);
2943     IDStack.push_back(ID);
2944     MoveId = GetID("#MOVE");
2945     ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
2946     ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
2947     AutoFitFramesX = AutoFitFramesY = -1;
2948     AutoPosLastDirection = ImGuiDir_None;
2949     SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
2950     SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
2951     LastFrameActive = -1;
2952     LastTimeActive = -1.0f;
2953     FontWindowScale = 1.0f;
2954     SettingsOffset = -1;
2955     DrawList = &DrawListInst;
2956     DrawList->_Data = &context->DrawListSharedData;
2957     DrawList->_OwnerName = Name;
2958 }
2959 
~ImGuiWindow()2960 ImGuiWindow::~ImGuiWindow()
2961 {
2962     IM_ASSERT(DrawList == &DrawListInst);
2963     IM_DELETE(Name);
2964     ColumnsStorage.clear_destruct();
2965 }
2966 
GetID(const char * str,const char * str_end)2967 ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
2968 {
2969     ImGuiID seed = IDStack.back();
2970     ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
2971     ImGui::KeepAliveID(id);
2972     ImGuiContext& g = *GImGui;
2973     if (g.DebugHookIdInfo == id)
2974         ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
2975     return id;
2976 }
2977 
GetID(const void * ptr)2978 ImGuiID ImGuiWindow::GetID(const void* ptr)
2979 {
2980     ImGuiID seed = IDStack.back();
2981     ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
2982     ImGui::KeepAliveID(id);
2983     ImGuiContext& g = *GImGui;
2984     if (g.DebugHookIdInfo == id)
2985         ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
2986     return id;
2987 }
2988 
GetID(int n)2989 ImGuiID ImGuiWindow::GetID(int n)
2990 {
2991     ImGuiID seed = IDStack.back();
2992     ImGuiID id = ImHashData(&n, sizeof(n), seed);
2993     ImGui::KeepAliveID(id);
2994     ImGuiContext& g = *GImGui;
2995     if (g.DebugHookIdInfo == id)
2996         ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
2997     return id;
2998 }
2999 
GetIDNoKeepAlive(const char * str,const char * str_end)3000 ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end)
3001 {
3002     ImGuiID seed = IDStack.back();
3003     ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
3004     ImGuiContext& g = *GImGui;
3005     if (g.DebugHookIdInfo == id)
3006         ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
3007     return id;
3008 }
3009 
GetIDNoKeepAlive(const void * ptr)3010 ImGuiID ImGuiWindow::GetIDNoKeepAlive(const void* ptr)
3011 {
3012     ImGuiID seed = IDStack.back();
3013     ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
3014     ImGuiContext& g = *GImGui;
3015     if (g.DebugHookIdInfo == id)
3016         ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
3017     return id;
3018 }
3019 
GetIDNoKeepAlive(int n)3020 ImGuiID ImGuiWindow::GetIDNoKeepAlive(int n)
3021 {
3022     ImGuiID seed = IDStack.back();
3023     ImGuiID id = ImHashData(&n, sizeof(n), seed);
3024     ImGuiContext& g = *GImGui;
3025     if (g.DebugHookIdInfo == id)
3026         ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
3027     return id;
3028 }
3029 
3030 // This is only used in rare/specific situations to manufacture an ID out of nowhere.
GetIDFromRectangle(const ImRect & r_abs)3031 ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
3032 {
3033     ImGuiID seed = IDStack.back();
3034     const int r_rel[4] = { (int)(r_abs.Min.x - Pos.x), (int)(r_abs.Min.y - Pos.y), (int)(r_abs.Max.x - Pos.x), (int)(r_abs.Max.y - Pos.y) };
3035     ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
3036     ImGui::KeepAliveID(id);
3037     return id;
3038 }
3039 
SetCurrentWindow(ImGuiWindow * window)3040 static void SetCurrentWindow(ImGuiWindow* window)
3041 {
3042     ImGuiContext& g = *GImGui;
3043     g.CurrentWindow = window;
3044     g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
3045     if (window)
3046         g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
3047 }
3048 
GcCompactTransientMiscBuffers()3049 void ImGui::GcCompactTransientMiscBuffers()
3050 {
3051     ImGuiContext& g = *GImGui;
3052     g.ItemFlagsStack.clear();
3053     g.GroupStack.clear();
3054     TableGcCompactSettings();
3055 }
3056 
3057 // Free up/compact internal window buffers, we can use this when a window becomes unused.
3058 // Not freed:
3059 // - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
3060 // This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
GcCompactTransientWindowBuffers(ImGuiWindow * window)3061 void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
3062 {
3063     window->MemoryCompacted = true;
3064     window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
3065     window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
3066     window->IDStack.clear();
3067     window->DrawList->_ClearFreeMemory();
3068     window->DC.ChildWindows.clear();
3069     window->DC.ItemWidthStack.clear();
3070     window->DC.TextWrapPosStack.clear();
3071 }
3072 
GcAwakeTransientWindowBuffers(ImGuiWindow * window)3073 void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
3074 {
3075     // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
3076     // The other buffers tends to amortize much faster.
3077     window->MemoryCompacted = false;
3078     window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
3079     window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
3080     window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
3081 }
3082 
SetActiveID(ImGuiID id,ImGuiWindow * window)3083 void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
3084 {
3085     ImGuiContext& g = *GImGui;
3086     g.ActiveIdIsJustActivated = (g.ActiveId != id);
3087     if (g.ActiveIdIsJustActivated)
3088     {
3089         g.ActiveIdTimer = 0.0f;
3090         g.ActiveIdHasBeenPressedBefore = false;
3091         g.ActiveIdHasBeenEditedBefore = false;
3092         g.ActiveIdMouseButton = -1;
3093         if (id != 0)
3094         {
3095             g.LastActiveId = id;
3096             g.LastActiveIdTimer = 0.0f;
3097         }
3098     }
3099     g.ActiveId = id;
3100     g.ActiveIdAllowOverlap = false;
3101     g.ActiveIdNoClearOnFocusLoss = false;
3102     g.ActiveIdWindow = window;
3103     g.ActiveIdHasBeenEditedThisFrame = false;
3104     if (id)
3105     {
3106         g.ActiveIdIsAlive = id;
3107         g.ActiveIdSource = (g.NavActivateId == id || g.NavActivateInputId == id || g.NavJustTabbedId == id || g.NavJustMovedToId == id) ? ImGuiInputSource_Nav : ImGuiInputSource_Mouse;
3108     }
3109 
3110     // Clear declaration of inputs claimed by the widget
3111     // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
3112     g.ActiveIdUsingMouseWheel = false;
3113     g.ActiveIdUsingNavDirMask = 0x00;
3114     g.ActiveIdUsingNavInputMask = 0x00;
3115     g.ActiveIdUsingKeyInputMask = 0x00;
3116 }
3117 
ClearActiveID()3118 void ImGui::ClearActiveID()
3119 {
3120     SetActiveID(0, NULL); // g.ActiveId = 0;
3121 }
3122 
SetHoveredID(ImGuiID id)3123 void ImGui::SetHoveredID(ImGuiID id)
3124 {
3125     ImGuiContext& g = *GImGui;
3126     g.HoveredId = id;
3127     g.HoveredIdAllowOverlap = false;
3128     g.HoveredIdUsingMouseWheel = false;
3129     if (id != 0 && g.HoveredIdPreviousFrame != id)
3130         g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
3131 }
3132 
GetHoveredID()3133 ImGuiID ImGui::GetHoveredID()
3134 {
3135     ImGuiContext& g = *GImGui;
3136     return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
3137 }
3138 
KeepAliveID(ImGuiID id)3139 void ImGui::KeepAliveID(ImGuiID id)
3140 {
3141     ImGuiContext& g = *GImGui;
3142     if (g.ActiveId == id)
3143         g.ActiveIdIsAlive = id;
3144     if (g.ActiveIdPreviousFrame == id)
3145         g.ActiveIdPreviousFrameIsAlive = true;
3146 }
3147 
MarkItemEdited(ImGuiID id)3148 void ImGui::MarkItemEdited(ImGuiID id)
3149 {
3150     // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
3151     // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need need to fill the data.
3152     ImGuiContext& g = *GImGui;
3153     IM_ASSERT(g.ActiveId == id || g.ActiveId == 0 || g.DragDropActive);
3154     IM_UNUSED(id); // Avoid unused variable warnings when asserts are compiled out.
3155     //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
3156     g.ActiveIdHasBeenEditedThisFrame = true;
3157     g.ActiveIdHasBeenEditedBefore = true;
3158     g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
3159 }
3160 
IsWindowContentHoverable(ImGuiWindow * window,ImGuiHoveredFlags flags)3161 static inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
3162 {
3163     // An active popup disable hovering on other windows (apart from its own children)
3164     // FIXME-OPT: This could be cached/stored within the window.
3165     ImGuiContext& g = *GImGui;
3166     if (g.NavWindow)
3167         if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindow)
3168             if (focused_root_window->WasActive && focused_root_window != window->RootWindow)
3169             {
3170                 // For the purpose of those flags we differentiate "standard popup" from "modal popup"
3171                 // NB: The order of those two tests is important because Modal windows are also Popups.
3172                 if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
3173                     return false;
3174                 if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
3175                     return false;
3176             }
3177     return true;
3178 }
3179 
3180 // This is roughly matching the behavior of internal-facing ItemHoverable()
3181 // - 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()
3182 // - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
IsItemHovered(ImGuiHoveredFlags flags)3183 bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
3184 {
3185     ImGuiContext& g = *GImGui;
3186     ImGuiWindow* window = g.CurrentWindow;
3187     if (g.NavDisableMouseHover && !g.NavDisableHighlight)
3188     {
3189         if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
3190             return false;
3191         return IsItemFocused();
3192     }
3193 
3194     // Test for bounding box overlap, as updated as ItemAdd()
3195     ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
3196     if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
3197         return false;
3198     IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy)) == 0);   // Flags not supported by this function
3199 
3200     // Test if we are hovering the right window (our window could be behind another window)
3201     // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
3202     // [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
3203     // 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
3204     // the test that has been running for a long while.
3205     if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
3206         if ((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0)
3207             return false;
3208 
3209     // Test if another item is active (e.g. being dragged)
3210     if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
3211         if (g.ActiveId != 0 && g.ActiveId != g.LastItemData.ID && !g.ActiveIdAllowOverlap && g.ActiveId != window->MoveId)
3212             return false;
3213 
3214     // Test if interactions on this window are blocked by an active popup or modal.
3215     // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
3216     if (!IsWindowContentHoverable(window, flags))
3217         return false;
3218 
3219     // Test if the item is disabled
3220     if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
3221         return false;
3222 
3223     // Special handling for calling after Begin() which represent the title bar or tab.
3224     // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
3225     if (g.LastItemData.ID == window->MoveId && window->WriteAccessed)
3226         return false;
3227     return true;
3228 }
3229 
3230 // Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
ItemHoverable(const ImRect & bb,ImGuiID id)3231 bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id)
3232 {
3233     ImGuiContext& g = *GImGui;
3234     if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
3235         return false;
3236 
3237     ImGuiWindow* window = g.CurrentWindow;
3238     if (g.HoveredWindow != window)
3239         return false;
3240     if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
3241         return false;
3242     if (!IsMouseHoveringRect(bb.Min, bb.Max))
3243         return false;
3244     if (g.NavDisableMouseHover)
3245         return false;
3246     if (!IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
3247     {
3248         g.HoveredIdDisabled = true;
3249         return false;
3250     }
3251 
3252     // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
3253     // hover test in widgets code. We could also decide to split this function is two.
3254     if (id != 0)
3255         SetHoveredID(id);
3256 
3257     // When disabled we'll return false but still set HoveredId
3258     ImGuiItemFlags item_flags = (g.LastItemData.ID == id ? g.LastItemData.InFlags : g.CurrentItemFlags);
3259     if (item_flags & ImGuiItemFlags_Disabled)
3260     {
3261         // Release active id if turning disabled
3262         if (g.ActiveId == id)
3263             ClearActiveID();
3264         g.HoveredIdDisabled = true;
3265         return false;
3266     }
3267 
3268     if (id != 0)
3269     {
3270         // [DEBUG] Item Picker tool!
3271         // We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making
3272         // the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered
3273         // items if we perform the test in ItemAdd(), but that would incur a small runtime cost.
3274         // #define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX in imconfig.h if you want this check to also be performed in ItemAdd().
3275         if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
3276             GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
3277         if (g.DebugItemPickerBreakId == id)
3278             IM_DEBUG_BREAK();
3279     }
3280 
3281     return true;
3282 }
3283 
IsClippedEx(const ImRect & bb,ImGuiID id)3284 bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
3285 {
3286     ImGuiContext& g = *GImGui;
3287     ImGuiWindow* window = g.CurrentWindow;
3288     if (!bb.Overlaps(window->ClipRect))
3289         if (id == 0 || (id != g.ActiveId && id != g.NavId))
3290             if (!g.LogEnabled)
3291                 return true;
3292     return false;
3293 }
3294 
3295 // Called by ItemAdd()
3296 // Process TAB/Shift+TAB. Be mindful that this function may _clear_ the ActiveID when tabbing out.
3297 // [WIP] This will eventually be refactored and moved into NavProcessItem()
ItemInputable(ImGuiWindow * window,ImGuiID id)3298 void ImGui::ItemInputable(ImGuiWindow* window, ImGuiID id)
3299 {
3300     ImGuiContext& g = *GImGui;
3301     IM_ASSERT(id != 0 && id == g.LastItemData.ID);
3302 
3303     // Increment counters
3304     // FIXME: ImGuiItemFlags_Disabled should disable more.
3305     const bool is_tab_stop = (g.LastItemData.InFlags & (ImGuiItemFlags_NoTabStop | ImGuiItemFlags_Disabled)) == 0;
3306     if (is_tab_stop)
3307     {
3308         window->DC.FocusCounterTabStop++;
3309         if (g.NavId == id)
3310             g.NavIdTabCounter = window->DC.FocusCounterTabStop;
3311     }
3312 
3313     // Process TAB/Shift-TAB to tab *OUT* of the currently focused item.
3314     // (Note that we can always TAB out of a widget that doesn't allow tabbing in)
3315     if (g.ActiveId == id && g.TabFocusPressed && g.TabFocusRequestNextWindow == NULL)
3316     {
3317         g.TabFocusRequestNextWindow = window;
3318         g.TabFocusRequestNextCounterTabStop = window->DC.FocusCounterTabStop + (g.IO.KeyShift ? (is_tab_stop ? -1 : 0) : +1); // Modulo on index will be applied at the end of frame once we've got the total counter of items.
3319     }
3320 
3321     // Handle focus requests
3322     if (g.TabFocusRequestCurrWindow == window)
3323     {
3324         if (is_tab_stop && window->DC.FocusCounterTabStop == g.TabFocusRequestCurrCounterTabStop)
3325         {
3326             g.NavJustTabbedId = id; // FIXME-NAV: aim to eventually set in NavUpdate() once we finish the refactor
3327             g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_FocusedByTabbing;
3328             return;
3329         }
3330 
3331         // If another item is about to be focused, we clear our own active id
3332         if (g.ActiveId == id)
3333             ClearActiveID();
3334     }
3335 }
3336 
CalcWrapWidthForPos(const ImVec2 & pos,float wrap_pos_x)3337 float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
3338 {
3339     if (wrap_pos_x < 0.0f)
3340         return 0.0f;
3341 
3342     ImGuiContext& g = *GImGui;
3343     ImGuiWindow* window = g.CurrentWindow;
3344     if (wrap_pos_x == 0.0f)
3345     {
3346         // We could decide to setup a default wrapping max point for auto-resizing windows,
3347         // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
3348         //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
3349         //    wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
3350         //else
3351         wrap_pos_x = window->WorkRect.Max.x;
3352     }
3353     else if (wrap_pos_x > 0.0f)
3354     {
3355         wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
3356     }
3357 
3358     return ImMax(wrap_pos_x - pos.x, 1.0f);
3359 }
3360 
3361 // IM_ALLOC() == ImGui::MemAlloc()
MemAlloc(size_t size)3362 void* ImGui::MemAlloc(size_t size)
3363 {
3364     if (ImGuiContext* ctx = GImGui)
3365         ctx->IO.MetricsActiveAllocations++;
3366     return (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
3367 }
3368 
3369 // IM_FREE() == ImGui::MemFree()
MemFree(void * ptr)3370 void ImGui::MemFree(void* ptr)
3371 {
3372     if (ptr)
3373         if (ImGuiContext* ctx = GImGui)
3374             ctx->IO.MetricsActiveAllocations--;
3375     return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
3376 }
3377 
GetClipboardText()3378 const char* ImGui::GetClipboardText()
3379 {
3380     ImGuiContext& g = *GImGui;
3381     return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
3382 }
3383 
SetClipboardText(const char * text)3384 void ImGui::SetClipboardText(const char* text)
3385 {
3386     ImGuiContext& g = *GImGui;
3387     if (g.IO.SetClipboardTextFn)
3388         g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
3389 }
3390 
GetVersion()3391 const char* ImGui::GetVersion()
3392 {
3393     return IMGUI_VERSION;
3394 }
3395 
3396 // Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
3397 // 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
GetCurrentContext()3398 ImGuiContext* ImGui::GetCurrentContext()
3399 {
3400     return GImGui;
3401 }
3402 
SetCurrentContext(ImGuiContext * ctx)3403 void ImGui::SetCurrentContext(ImGuiContext* ctx)
3404 {
3405 #ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
3406     IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
3407 #else
3408     GImGui = ctx;
3409 #endif
3410 }
3411 
SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func,ImGuiMemFreeFunc free_func,void * user_data)3412 void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
3413 {
3414     GImAllocatorAllocFunc = alloc_func;
3415     GImAllocatorFreeFunc = free_func;
3416     GImAllocatorUserData = user_data;
3417 }
3418 
3419 // This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
GetAllocatorFunctions(ImGuiMemAllocFunc * p_alloc_func,ImGuiMemFreeFunc * p_free_func,void ** p_user_data)3420 void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
3421 {
3422     *p_alloc_func = GImAllocatorAllocFunc;
3423     *p_free_func = GImAllocatorFreeFunc;
3424     *p_user_data = GImAllocatorUserData;
3425 }
3426 
CreateContext(ImFontAtlas * shared_font_atlas)3427 ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
3428 {
3429     ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
3430     if (GImGui == NULL)
3431         SetCurrentContext(ctx);
3432     Initialize(ctx);
3433     return ctx;
3434 }
3435 
DestroyContext(ImGuiContext * ctx)3436 void ImGui::DestroyContext(ImGuiContext* ctx)
3437 {
3438     if (ctx == NULL)
3439         ctx = GImGui;
3440     Shutdown(ctx);
3441     if (GImGui == ctx)
3442         SetCurrentContext(NULL);
3443     IM_DELETE(ctx);
3444 }
3445 
3446 // No specific ordering/dependency support, will see as needed
AddContextHook(ImGuiContext * ctx,const ImGuiContextHook * hook)3447 ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
3448 {
3449     ImGuiContext& g = *ctx;
3450     IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
3451     g.Hooks.push_back(*hook);
3452     g.Hooks.back().HookId = ++g.HookIdNext;
3453     return g.HookIdNext;
3454 }
3455 
3456 // Deferred removal, avoiding issue with changing vector while iterating it
RemoveContextHook(ImGuiContext * ctx,ImGuiID hook_id)3457 void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
3458 {
3459     ImGuiContext& g = *ctx;
3460     IM_ASSERT(hook_id != 0);
3461     for (int n = 0; n < g.Hooks.Size; n++)
3462         if (g.Hooks[n].HookId == hook_id)
3463             g.Hooks[n].Type = ImGuiContextHookType_PendingRemoval_;
3464 }
3465 
3466 // Call context hooks (used by e.g. test engine)
3467 // We assume a small number of hooks so all stored in same array
CallContextHooks(ImGuiContext * ctx,ImGuiContextHookType hook_type)3468 void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
3469 {
3470     ImGuiContext& g = *ctx;
3471     for (int n = 0; n < g.Hooks.Size; n++)
3472         if (g.Hooks[n].Type == hook_type)
3473             g.Hooks[n].Callback(&g, &g.Hooks[n]);
3474 }
3475 
GetIO()3476 ImGuiIO& ImGui::GetIO()
3477 {
3478     IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
3479     return GImGui->IO;
3480 }
3481 
3482 // Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
GetDrawData()3483 ImDrawData* ImGui::GetDrawData()
3484 {
3485     ImGuiContext& g = *GImGui;
3486     ImGuiViewportP* viewport = g.Viewports[0];
3487     return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
3488 }
3489 
GetTime()3490 double ImGui::GetTime()
3491 {
3492     return GImGui->Time;
3493 }
3494 
GetFrameCount()3495 int ImGui::GetFrameCount()
3496 {
3497     return GImGui->FrameCount;
3498 }
3499 
GetViewportDrawList(ImGuiViewportP * viewport,size_t drawlist_no,const char * drawlist_name)3500 static ImDrawList* GetViewportDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
3501 {
3502     // Create the draw list on demand, because they are not frequently used for all viewports
3503     ImGuiContext& g = *GImGui;
3504     IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->DrawLists));
3505     ImDrawList* draw_list = viewport->DrawLists[drawlist_no];
3506     if (draw_list == NULL)
3507     {
3508         draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
3509         draw_list->_OwnerName = drawlist_name;
3510         viewport->DrawLists[drawlist_no] = draw_list;
3511     }
3512 
3513     // Our ImDrawList system requires that there is always a command
3514     if (viewport->DrawListsLastFrame[drawlist_no] != g.FrameCount)
3515     {
3516         draw_list->_ResetForNewFrame();
3517         draw_list->PushTextureID(g.IO.Fonts->TexID);
3518         draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
3519         viewport->DrawListsLastFrame[drawlist_no] = g.FrameCount;
3520     }
3521     return draw_list;
3522 }
3523 
GetBackgroundDrawList(ImGuiViewport * viewport)3524 ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
3525 {
3526     return GetViewportDrawList((ImGuiViewportP*)viewport, 0, "##Background");
3527 }
3528 
GetBackgroundDrawList()3529 ImDrawList* ImGui::GetBackgroundDrawList()
3530 {
3531     ImGuiContext& g = *GImGui;
3532     return GetBackgroundDrawList(g.Viewports[0]);
3533 }
3534 
GetForegroundDrawList(ImGuiViewport * viewport)3535 ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
3536 {
3537     return GetViewportDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
3538 }
3539 
GetForegroundDrawList()3540 ImDrawList* ImGui::GetForegroundDrawList()
3541 {
3542     ImGuiContext& g = *GImGui;
3543     return GetForegroundDrawList(g.Viewports[0]);
3544 }
3545 
GetDrawListSharedData()3546 ImDrawListSharedData* ImGui::GetDrawListSharedData()
3547 {
3548     return &GImGui->DrawListSharedData;
3549 }
3550 
StartMouseMovingWindow(ImGuiWindow * window)3551 void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
3552 {
3553     // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
3554     // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
3555     // This is because we want ActiveId to be set even when the window is not permitted to move.
3556     ImGuiContext& g = *GImGui;
3557     FocusWindow(window);
3558     SetActiveID(window->MoveId, window);
3559     g.NavDisableHighlight = true;
3560     g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindow->Pos;
3561     g.ActiveIdNoClearOnFocusLoss = true;
3562     SetActiveIdUsingNavAndKeys();
3563 
3564     bool can_move_window = true;
3565     if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindow->Flags & ImGuiWindowFlags_NoMove))
3566         can_move_window = false;
3567     if (can_move_window)
3568         g.MovingWindow = window;
3569 }
3570 
3571 // Handle mouse moving window
3572 // Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
3573 // FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
3574 // This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
3575 // but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
UpdateMouseMovingWindowNewFrame()3576 void ImGui::UpdateMouseMovingWindowNewFrame()
3577 {
3578     ImGuiContext& g = *GImGui;
3579     if (g.MovingWindow != NULL)
3580     {
3581         // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
3582         // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
3583         KeepAliveID(g.ActiveId);
3584         IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindow);
3585         ImGuiWindow* moving_window = g.MovingWindow->RootWindow;
3586         if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos))
3587         {
3588             ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
3589             if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
3590             {
3591                 MarkIniSettingsDirty(moving_window);
3592                 SetWindowPos(moving_window, pos, ImGuiCond_Always);
3593             }
3594             FocusWindow(g.MovingWindow);
3595         }
3596         else
3597         {
3598             g.MovingWindow = NULL;
3599             ClearActiveID();
3600         }
3601     }
3602     else
3603     {
3604         // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
3605         if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
3606         {
3607             KeepAliveID(g.ActiveId);
3608             if (!g.IO.MouseDown[0])
3609                 ClearActiveID();
3610         }
3611     }
3612 }
3613 
3614 // Initiate moving window when clicking on empty space or title bar.
3615 // Handle left-click and right-click focus.
UpdateMouseMovingWindowEndFrame()3616 void ImGui::UpdateMouseMovingWindowEndFrame()
3617 {
3618     ImGuiContext& g = *GImGui;
3619     if (g.ActiveId != 0 || g.HoveredId != 0)
3620         return;
3621 
3622     // Unless we just made a window/popup appear
3623     if (g.NavWindow && g.NavWindow->Appearing)
3624         return;
3625 
3626     // Click on empty space to focus window and start moving
3627     // (after we're done with all our widgets)
3628     if (g.IO.MouseClicked[0])
3629     {
3630         // Handle the edge case of a popup being closed while clicking in its empty space.
3631         // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
3632         ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
3633         const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
3634 
3635         if (root_window != NULL && !is_closed_popup)
3636         {
3637             StartMouseMovingWindow(g.HoveredWindow); //-V595
3638 
3639             // Cancel moving if clicked outside of title bar
3640             if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(root_window->Flags & ImGuiWindowFlags_NoTitleBar))
3641                 if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
3642                     g.MovingWindow = NULL;
3643 
3644             // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
3645             if (g.HoveredIdDisabled)
3646                 g.MovingWindow = NULL;
3647         }
3648         else if (root_window == NULL && g.NavWindow != NULL && GetTopMostPopupModal() == NULL)
3649         {
3650             // Clicking on void disable focus
3651             FocusWindow(NULL);
3652         }
3653     }
3654 
3655     // With right mouse button we close popups without changing focus based on where the mouse is aimed
3656     // Instead, focus will be restored to the window under the bottom-most closed popup.
3657     // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
3658     if (g.IO.MouseClicked[1])
3659     {
3660         // Find the top-most window between HoveredWindow and the top-most Modal Window.
3661         // This is where we can trim the popup stack.
3662         ImGuiWindow* modal = GetTopMostPopupModal();
3663         bool hovered_window_above_modal = g.HoveredWindow && IsWindowAbove(g.HoveredWindow, modal);
3664         ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
3665     }
3666 }
3667 
IsWindowActiveAndVisible(ImGuiWindow * window)3668 static bool IsWindowActiveAndVisible(ImGuiWindow* window)
3669 {
3670     return (window->Active) && (!window->Hidden);
3671 }
3672 
UpdateMouseInputs()3673 static void ImGui::UpdateMouseInputs()
3674 {
3675     ImGuiContext& g = *GImGui;
3676 
3677     // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
3678     if (IsMousePosValid(&g.IO.MousePos))
3679         g.IO.MousePos = g.MouseLastValidPos = ImFloor(g.IO.MousePos);
3680 
3681     // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
3682     if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MousePosPrev))
3683         g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev;
3684     else
3685         g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
3686 
3687     // 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.
3688     if (g.IO.MouseDelta.x != 0.0f || g.IO.MouseDelta.y != 0.0f)
3689         g.NavDisableMouseHover = false;
3690 
3691     g.IO.MousePosPrev = g.IO.MousePos;
3692     for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
3693     {
3694         g.IO.MouseClicked[i] = g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] < 0.0f;
3695         g.IO.MouseReleased[i] = !g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] >= 0.0f;
3696         g.IO.MouseDownDurationPrev[i] = g.IO.MouseDownDuration[i];
3697         g.IO.MouseDownDuration[i] = g.IO.MouseDown[i] ? (g.IO.MouseDownDuration[i] < 0.0f ? 0.0f : g.IO.MouseDownDuration[i] + g.IO.DeltaTime) : -1.0f;
3698         g.IO.MouseDoubleClicked[i] = false;
3699         if (g.IO.MouseClicked[i])
3700         {
3701             if ((float)(g.Time - g.IO.MouseClickedTime[i]) < g.IO.MouseDoubleClickTime)
3702             {
3703                 ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
3704                 if (ImLengthSqr(delta_from_click_pos) < g.IO.MouseDoubleClickMaxDist * g.IO.MouseDoubleClickMaxDist)
3705                     g.IO.MouseDoubleClicked[i] = true;
3706                 g.IO.MouseClickedTime[i] = -g.IO.MouseDoubleClickTime * 2.0f; // Mark as "old enough" so the third click isn't turned into a double-click
3707             }
3708             else
3709             {
3710                 g.IO.MouseClickedTime[i] = g.Time;
3711             }
3712             g.IO.MouseClickedPos[i] = g.IO.MousePos;
3713             g.IO.MouseDownWasDoubleClick[i] = g.IO.MouseDoubleClicked[i];
3714             g.IO.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
3715             g.IO.MouseDragMaxDistanceSqr[i] = 0.0f;
3716         }
3717         else if (g.IO.MouseDown[i])
3718         {
3719             // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
3720             ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
3721             g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
3722             g.IO.MouseDragMaxDistanceAbs[i].x = ImMax(g.IO.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
3723             g.IO.MouseDragMaxDistanceAbs[i].y = ImMax(g.IO.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
3724         }
3725         if (!g.IO.MouseDown[i] && !g.IO.MouseReleased[i])
3726             g.IO.MouseDownWasDoubleClick[i] = false;
3727         if (g.IO.MouseClicked[i]) // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
3728             g.NavDisableMouseHover = false;
3729     }
3730 }
3731 
StartLockWheelingWindow(ImGuiWindow * window)3732 static void StartLockWheelingWindow(ImGuiWindow* window)
3733 {
3734     ImGuiContext& g = *GImGui;
3735     if (g.WheelingWindow == window)
3736         return;
3737     g.WheelingWindow = window;
3738     g.WheelingWindowRefMousePos = g.IO.MousePos;
3739     g.WheelingWindowTimer = WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER;
3740 }
3741 
UpdateMouseWheel()3742 void ImGui::UpdateMouseWheel()
3743 {
3744     ImGuiContext& g = *GImGui;
3745 
3746     // Reset the locked window if we move the mouse or after the timer elapses
3747     if (g.WheelingWindow != NULL)
3748     {
3749         g.WheelingWindowTimer -= g.IO.DeltaTime;
3750         if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
3751             g.WheelingWindowTimer = 0.0f;
3752         if (g.WheelingWindowTimer <= 0.0f)
3753         {
3754             g.WheelingWindow = NULL;
3755             g.WheelingWindowTimer = 0.0f;
3756         }
3757     }
3758 
3759     if (g.IO.MouseWheel == 0.0f && g.IO.MouseWheelH == 0.0f)
3760         return;
3761 
3762     if ((g.ActiveId != 0 && g.ActiveIdUsingMouseWheel) || (g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrameUsingMouseWheel))
3763         return;
3764 
3765     ImGuiWindow* window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
3766     if (!window || window->Collapsed)
3767         return;
3768 
3769     // Zoom / Scale window
3770     // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
3771     if (g.IO.MouseWheel != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
3772     {
3773         StartLockWheelingWindow(window);
3774         const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
3775         const float scale = new_font_scale / window->FontWindowScale;
3776         window->FontWindowScale = new_font_scale;
3777         if (window == window->RootWindow)
3778         {
3779             const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
3780             SetWindowPos(window, window->Pos + offset, 0);
3781             window->Size = ImFloor(window->Size * scale);
3782             window->SizeFull = ImFloor(window->SizeFull * scale);
3783         }
3784         return;
3785     }
3786 
3787     // Mouse wheel scrolling
3788     // If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent
3789     if (g.IO.KeyCtrl)
3790         return;
3791 
3792     // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
3793     // (we avoid doing it on OSX as it the OS input layer handles this already)
3794     const bool swap_axis = g.IO.KeyShift && !g.IO.ConfigMacOSXBehaviors;
3795     const float wheel_y = swap_axis ? 0.0f : g.IO.MouseWheel;
3796     const float wheel_x = swap_axis ? g.IO.MouseWheel : g.IO.MouseWheelH;
3797 
3798     // Vertical Mouse Wheel scrolling
3799     if (wheel_y != 0.0f)
3800     {
3801         StartLockWheelingWindow(window);
3802         while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.y == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))))
3803             window = window->ParentWindow;
3804         if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
3805         {
3806             float max_step = window->InnerRect.GetHeight() * 0.67f;
3807             float scroll_step = ImFloor(ImMin(5 * window->CalcFontSize(), max_step));
3808             SetScrollY(window, window->Scroll.y - wheel_y * scroll_step);
3809         }
3810     }
3811 
3812     // Horizontal Mouse Wheel scrolling, or Vertical Mouse Wheel w/ Shift held
3813     if (wheel_x != 0.0f)
3814     {
3815         StartLockWheelingWindow(window);
3816         while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.x == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))))
3817             window = window->ParentWindow;
3818         if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
3819         {
3820             float max_step = window->InnerRect.GetWidth() * 0.67f;
3821             float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step));
3822             SetScrollX(window, window->Scroll.x - wheel_x * scroll_step);
3823         }
3824     }
3825 }
3826 
UpdateTabFocus()3827 void ImGui::UpdateTabFocus()
3828 {
3829     ImGuiContext& g = *GImGui;
3830 
3831     // Pressing TAB activate widget focus
3832     g.TabFocusPressed = false;
3833     if (g.NavWindow && g.NavWindow->Active && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
3834         if (!g.IO.KeyCtrl && !g.IO.KeyAlt && IsKeyPressedMap(ImGuiKey_Tab) && !IsActiveIdUsingKey(ImGuiKey_Tab))
3835             g.TabFocusPressed = true;
3836     if (g.ActiveId == 0 && g.TabFocusPressed)
3837     {
3838         // - This path is only taken when no widget are active/tabbed-into yet.
3839         //   Subsequent tabbing will be processed by FocusableItemRegister()
3840         // - Note that SetKeyboardFocusHere() sets the Next fields mid-frame. To be consistent we also
3841         //   manipulate the Next fields here even though they will be turned into Curr fields below.
3842         g.TabFocusRequestNextWindow = g.NavWindow;
3843         if (g.NavId != 0 && g.NavIdTabCounter != INT_MAX)
3844             g.TabFocusRequestNextCounterTabStop = g.NavIdTabCounter + (g.IO.KeyShift ? -1 : 0);
3845         else
3846             g.TabFocusRequestNextCounterTabStop = g.IO.KeyShift ? -1 : 0;
3847     }
3848 
3849     // Turn queued focus request into current one
3850     g.TabFocusRequestCurrWindow = NULL;
3851     g.TabFocusRequestCurrCounterTabStop = INT_MAX;
3852     if (g.TabFocusRequestNextWindow != NULL)
3853     {
3854         ImGuiWindow* window = g.TabFocusRequestNextWindow;
3855         g.TabFocusRequestCurrWindow = window;
3856         if (g.TabFocusRequestNextCounterTabStop != INT_MAX && window->DC.FocusCounterTabStop != -1)
3857             g.TabFocusRequestCurrCounterTabStop = ImModPositive(g.TabFocusRequestNextCounterTabStop, window->DC.FocusCounterTabStop + 1);
3858         g.TabFocusRequestNextWindow = NULL;
3859         g.TabFocusRequestNextCounterTabStop = INT_MAX;
3860     }
3861 
3862     g.NavIdTabCounter = INT_MAX;
3863 }
3864 
3865 // 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)
UpdateHoveredWindowAndCaptureFlags()3866 void ImGui::UpdateHoveredWindowAndCaptureFlags()
3867 {
3868     ImGuiContext& g = *GImGui;
3869     ImGuiIO& io = g.IO;
3870     g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
3871 
3872     // Find the window hovered by mouse:
3873     // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
3874     // - 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.
3875     // - 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.
3876     bool clear_hovered_windows = false;
3877     FindHoveredWindow();
3878 
3879     // Modal windows prevents mouse from hovering behind them.
3880     ImGuiWindow* modal_window = GetTopMostPopupModal();
3881     if (modal_window && g.HoveredWindow && !IsWindowChildOf(g.HoveredWindow->RootWindow, modal_window, true))
3882         clear_hovered_windows = true;
3883 
3884     // Disabled mouse?
3885     if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
3886         clear_hovered_windows = true;
3887 
3888     // We track click ownership. When clicked outside of a window the click is owned by the application and
3889     // won't report hovering nor request capture even while dragging over our windows afterward.
3890     const bool has_open_popup = (g.OpenPopupStack.Size > 0);
3891     const bool has_open_modal = (modal_window != NULL);
3892     int mouse_earliest_down = -1;
3893     bool mouse_any_down = false;
3894     for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
3895     {
3896         if (io.MouseClicked[i])
3897         {
3898             io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
3899             io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
3900         }
3901         mouse_any_down |= io.MouseDown[i];
3902         if (io.MouseDown[i])
3903             if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
3904                 mouse_earliest_down = i;
3905     }
3906     const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
3907     const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
3908 
3909     // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
3910     // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
3911     const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
3912     if (!mouse_avail && !mouse_dragging_extern_payload)
3913         clear_hovered_windows = true;
3914 
3915     if (clear_hovered_windows)
3916         g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
3917 
3918     // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
3919     // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
3920     if (g.WantCaptureMouseNextFrame != -1)
3921     {
3922         io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
3923     }
3924     else
3925     {
3926         io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
3927         io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
3928     }
3929 
3930     // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
3931     if (g.WantCaptureKeyboardNextFrame != -1)
3932         io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
3933     else
3934         io.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
3935     if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
3936         io.WantCaptureKeyboard = true;
3937 
3938     // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
3939     io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
3940 }
3941 
GetMergedKeyModFlags()3942 ImGuiKeyModFlags ImGui::GetMergedKeyModFlags()
3943 {
3944     ImGuiContext& g = *GImGui;
3945     ImGuiKeyModFlags key_mod_flags = ImGuiKeyModFlags_None;
3946     if (g.IO.KeyCtrl)   { key_mod_flags |= ImGuiKeyModFlags_Ctrl; }
3947     if (g.IO.KeyShift)  { key_mod_flags |= ImGuiKeyModFlags_Shift; }
3948     if (g.IO.KeyAlt)    { key_mod_flags |= ImGuiKeyModFlags_Alt; }
3949     if (g.IO.KeySuper)  { key_mod_flags |= ImGuiKeyModFlags_Super; }
3950     return key_mod_flags;
3951 }
3952 
NewFrame()3953 void ImGui::NewFrame()
3954 {
3955     IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
3956     ImGuiContext& g = *GImGui;
3957 
3958     // Remove pending delete hooks before frame start.
3959     // This deferred removal avoid issues of removal while iterating the hook vector
3960     for (int n = g.Hooks.Size - 1; n >= 0; n--)
3961         if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
3962             g.Hooks.erase(&g.Hooks[n]);
3963 
3964     CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
3965 
3966     // Check and assert for various common IO and Configuration mistakes
3967     ErrorCheckNewFrameSanityChecks();
3968 
3969     // Load settings on first frame, save settings when modified (after a delay)
3970     UpdateSettings();
3971 
3972     g.Time += g.IO.DeltaTime;
3973     g.WithinFrameScope = true;
3974     g.FrameCount += 1;
3975     g.TooltipOverrideCount = 0;
3976     g.WindowsActiveCount = 0;
3977     g.MenusIdSubmittedThisFrame.resize(0);
3978 
3979     // Calculate frame-rate for the user, as a purely luxurious feature
3980     g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
3981     g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
3982     g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
3983     g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
3984     g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
3985 
3986     UpdateViewportsNewFrame();
3987 
3988     // Setup current font and draw list shared data
3989     g.IO.Fonts->Locked = true;
3990     SetCurrentFont(GetDefaultFont());
3991     IM_ASSERT(g.Font->IsLoaded());
3992     ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
3993     for (int n = 0; n < g.Viewports.Size; n++)
3994         virtual_space.Add(g.Viewports[n]->GetMainRect());
3995     g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
3996     g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
3997     g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
3998     g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
3999     if (g.Style.AntiAliasedLines)
4000         g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
4001     if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines))
4002         g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
4003     if (g.Style.AntiAliasedFill)
4004         g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
4005     if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
4006         g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
4007 
4008     // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
4009     for (int n = 0; n < g.Viewports.Size; n++)
4010     {
4011         ImGuiViewportP* viewport = g.Viewports[n];
4012         viewport->DrawDataP.Clear();
4013     }
4014 
4015     // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
4016     if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
4017         KeepAliveID(g.DragDropPayload.SourceId);
4018 
4019     // Update HoveredId data
4020     if (!g.HoveredIdPreviousFrame)
4021         g.HoveredIdTimer = 0.0f;
4022     if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
4023         g.HoveredIdNotActiveTimer = 0.0f;
4024     if (g.HoveredId)
4025         g.HoveredIdTimer += g.IO.DeltaTime;
4026     if (g.HoveredId && g.ActiveId != g.HoveredId)
4027         g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
4028     g.HoveredIdPreviousFrame = g.HoveredId;
4029     g.HoveredIdPreviousFrameUsingMouseWheel = g.HoveredIdUsingMouseWheel;
4030     g.HoveredId = 0;
4031     g.HoveredIdAllowOverlap = false;
4032     g.HoveredIdUsingMouseWheel = false;
4033     g.HoveredIdDisabled = false;
4034 
4035     // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
4036     if (g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0)
4037         ClearActiveID();
4038     if (g.ActiveId)
4039         g.ActiveIdTimer += g.IO.DeltaTime;
4040     g.LastActiveIdTimer += g.IO.DeltaTime;
4041     g.ActiveIdPreviousFrame = g.ActiveId;
4042     g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
4043     g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
4044     g.ActiveIdIsAlive = 0;
4045     g.ActiveIdHasBeenEditedThisFrame = false;
4046     g.ActiveIdPreviousFrameIsAlive = false;
4047     g.ActiveIdIsJustActivated = false;
4048     if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
4049         g.TempInputId = 0;
4050     if (g.ActiveId == 0)
4051     {
4052         g.ActiveIdUsingNavDirMask = 0x00;
4053         g.ActiveIdUsingNavInputMask = 0x00;
4054         g.ActiveIdUsingKeyInputMask = 0x00;
4055     }
4056 
4057     // Drag and drop
4058     g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
4059     g.DragDropAcceptIdCurr = 0;
4060     g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
4061     g.DragDropWithinSource = false;
4062     g.DragDropWithinTarget = false;
4063     g.DragDropHoldJustPressedId = 0;
4064 
4065     // Close popups on focus lost (currently wip/opt-in)
4066     //if (g.IO.AppFocusLost)
4067     //    ClosePopupsExceptModals();
4068 
4069     // Clear buttons state when focus is lost
4070     // (this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle)
4071     if (g.IO.AppFocusLost)
4072     {
4073         g.IO.ClearInputKeys();
4074         g.IO.AppFocusLost = false;
4075     }
4076 
4077     // Update keyboard input state
4078     // Synchronize io.KeyMods with individual modifiers io.KeyXXX bools
4079     g.IO.KeyMods = GetMergedKeyModFlags();
4080     memcpy(g.IO.KeysDownDurationPrev, g.IO.KeysDownDuration, sizeof(g.IO.KeysDownDuration));
4081     for (int i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++)
4082         g.IO.KeysDownDuration[i] = g.IO.KeysDown[i] ? (g.IO.KeysDownDuration[i] < 0.0f ? 0.0f : g.IO.KeysDownDuration[i] + g.IO.DeltaTime) : -1.0f;
4083 
4084     // Update gamepad/keyboard navigation
4085     NavUpdate();
4086 
4087     // Update mouse input state
4088     UpdateMouseInputs();
4089 
4090     // Find hovered window
4091     // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
4092     UpdateHoveredWindowAndCaptureFlags();
4093 
4094     // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
4095     UpdateMouseMovingWindowNewFrame();
4096 
4097     // Background darkening/whitening
4098     if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
4099         g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
4100     else
4101         g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
4102 
4103     g.MouseCursor = ImGuiMouseCursor_Arrow;
4104     g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
4105     g.PlatformImePos = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default
4106 
4107     // Mouse wheel scrolling, scale
4108     UpdateMouseWheel();
4109 
4110     // Update legacy TAB focus
4111     UpdateTabFocus();
4112 
4113     // Mark all windows as not visible and compact unused memory.
4114     IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
4115     const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
4116     for (int i = 0; i != g.Windows.Size; i++)
4117     {
4118         ImGuiWindow* window = g.Windows[i];
4119         window->WasActive = window->Active;
4120         window->BeginCount = 0;
4121         window->Active = false;
4122         window->WriteAccessed = false;
4123 
4124         // Garbage collect transient buffers of recently unused windows
4125         if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
4126             GcCompactTransientWindowBuffers(window);
4127     }
4128 
4129     // Garbage collect transient buffers of recently unused tables
4130     for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
4131         if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
4132             TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
4133     for (int i = 0; i < g.TablesTempDataStack.Size; i++)
4134         if (g.TablesTempDataStack[i].LastTimeActive >= 0.0f && g.TablesTempDataStack[i].LastTimeActive < memory_compact_start_time)
4135             TableGcCompactTransientBuffers(&g.TablesTempDataStack[i]);
4136     if (g.GcCompactAll)
4137         GcCompactTransientMiscBuffers();
4138     g.GcCompactAll = false;
4139 
4140     // Closing the focused window restore focus to the first active root window in descending z-order
4141     if (g.NavWindow && !g.NavWindow->WasActive)
4142         FocusTopMostWindowUnderOne(NULL, NULL);
4143 
4144     // No window should be open at the beginning of the frame.
4145     // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
4146     g.CurrentWindowStack.resize(0);
4147     g.BeginPopupStack.resize(0);
4148     g.ItemFlagsStack.resize(0);
4149     g.ItemFlagsStack.push_back(ImGuiItemFlags_None);
4150     g.GroupStack.resize(0);
4151 
4152     // [DEBUG] Update debug features
4153     UpdateDebugToolItemPicker();
4154     UpdateDebugToolStackQueries();
4155 
4156     // Create implicit/fallback window - which we will only render it if the user has added something to it.
4157     // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
4158     // This fallback is particularly important as it avoid ImGui:: calls from crashing.
4159     g.WithinFrameScopeWithImplicitWindow = true;
4160     SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
4161     Begin("Debug##Default");
4162     IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
4163 
4164     CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
4165 }
4166 
Initialize(ImGuiContext * context)4167 void ImGui::Initialize(ImGuiContext* context)
4168 {
4169     ImGuiContext& g = *context;
4170     IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
4171 
4172     // Add .ini handle for ImGuiWindow type
4173     {
4174         ImGuiSettingsHandler ini_handler;
4175         ini_handler.TypeName = "Window";
4176         ini_handler.TypeHash = ImHashStr("Window");
4177         ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
4178         ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
4179         ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
4180         ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
4181         ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
4182         g.SettingsHandlers.push_back(ini_handler);
4183     }
4184 
4185     // Add .ini handle for ImGuiTable type
4186     TableSettingsInstallHandler(context);
4187 
4188     // Create default viewport
4189     ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
4190     g.Viewports.push_back(viewport);
4191 
4192 #ifdef IMGUI_HAS_DOCK
4193 #endif
4194 
4195     g.Initialized = true;
4196 }
4197 
4198 // This function is merely here to free heap allocations.
Shutdown(ImGuiContext * context)4199 void ImGui::Shutdown(ImGuiContext* context)
4200 {
4201     // 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)
4202     ImGuiContext& g = *context;
4203     if (g.IO.Fonts && g.FontAtlasOwnedByContext)
4204     {
4205         g.IO.Fonts->Locked = false;
4206         IM_DELETE(g.IO.Fonts);
4207     }
4208     g.IO.Fonts = NULL;
4209 
4210     // Cleanup of other data are conditional on actually having initialized Dear ImGui.
4211     if (!g.Initialized)
4212         return;
4213 
4214     // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
4215     if (g.SettingsLoaded && g.IO.IniFilename != NULL)
4216     {
4217         ImGuiContext* backup_context = GImGui;
4218         SetCurrentContext(&g);
4219         SaveIniSettingsToDisk(g.IO.IniFilename);
4220         SetCurrentContext(backup_context);
4221     }
4222 
4223     CallContextHooks(&g, ImGuiContextHookType_Shutdown);
4224 
4225     // Clear everything else
4226     g.Windows.clear_delete();
4227     g.WindowsFocusOrder.clear();
4228     g.WindowsTempSortBuffer.clear();
4229     g.CurrentWindow = NULL;
4230     g.CurrentWindowStack.clear();
4231     g.WindowsById.Clear();
4232     g.NavWindow = NULL;
4233     g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4234     g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
4235     g.MovingWindow = NULL;
4236     g.ColorStack.clear();
4237     g.StyleVarStack.clear();
4238     g.FontStack.clear();
4239     g.OpenPopupStack.clear();
4240     g.BeginPopupStack.clear();
4241 
4242     g.Viewports.clear_delete();
4243 
4244     g.TabBars.Clear();
4245     g.CurrentTabBarStack.clear();
4246     g.ShrinkWidthBuffer.clear();
4247 
4248     g.Tables.Clear();
4249     g.TablesTempDataStack.clear_destruct();
4250     g.DrawChannelsTempMergeBuffer.clear();
4251 
4252     g.ClipboardHandlerData.clear();
4253     g.MenusIdSubmittedThisFrame.clear();
4254     g.InputTextState.ClearFreeMemory();
4255 
4256     g.SettingsWindows.clear();
4257     g.SettingsHandlers.clear();
4258 
4259     if (g.LogFile)
4260     {
4261 #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
4262         if (g.LogFile != stdout)
4263 #endif
4264             ImFileClose(g.LogFile);
4265         g.LogFile = NULL;
4266     }
4267     g.LogBuffer.clear();
4268 
4269     g.Initialized = false;
4270 }
4271 
4272 // FIXME: Add a more explicit sort order in the window structure.
ChildWindowComparer(const void * lhs,const void * rhs)4273 static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
4274 {
4275     const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
4276     const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
4277     if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
4278         return d;
4279     if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
4280         return d;
4281     return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
4282 }
4283 
AddWindowToSortBuffer(ImVector<ImGuiWindow * > * out_sorted_windows,ImGuiWindow * window)4284 static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
4285 {
4286     out_sorted_windows->push_back(window);
4287     if (window->Active)
4288     {
4289         int count = window->DC.ChildWindows.Size;
4290         if (count > 1)
4291             ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
4292         for (int i = 0; i < count; i++)
4293         {
4294             ImGuiWindow* child = window->DC.ChildWindows[i];
4295             if (child->Active)
4296                 AddWindowToSortBuffer(out_sorted_windows, child);
4297         }
4298     }
4299 }
4300 
AddDrawListToDrawData(ImVector<ImDrawList * > * out_list,ImDrawList * draw_list)4301 static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list)
4302 {
4303     // Remove trailing command if unused.
4304     // Technically we could return directly instead of popping, but this make things looks neat in Metrics/Debugger window as well.
4305     draw_list->_PopUnusedDrawCmd();
4306     if (draw_list->CmdBuffer.Size == 0)
4307         return;
4308 
4309     // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc.
4310     // May trigger for you if you are using PrimXXX functions incorrectly.
4311     IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
4312     IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
4313     if (!(draw_list->Flags & ImDrawListFlags_AllowVtxOffset))
4314         IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
4315 
4316     // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window)
4317     // If this assert triggers because you are drawing lots of stuff manually:
4318     // - First, make sure you are coarse clipping yourself and not trying to draw many things outside visible bounds.
4319     //   Be mindful that the ImDrawList API doesn't filter vertices. Use the Metrics/Debugger window to inspect draw list contents.
4320     // - If you want large meshes with more than 64K vertices, you can either:
4321     //   (A) Handle the ImDrawCmd::VtxOffset value in your renderer backend, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'.
4322     //       Most example backends already support this from 1.71. Pre-1.71 backends won't.
4323     //       Some graphics API such as GL ES 1/2 don't have a way to offset the starting vertex so it is not supported for them.
4324     //   (B) Or handle 32-bit indices in your renderer backend, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h.
4325     //       Most example backends already support this. For example, the OpenGL example code detect index size at compile-time:
4326     //         glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
4327     //       Your own engine or render API may use different parameters or function calls to specify index sizes.
4328     //       2 and 4 bytes indices are generally supported by most graphics API.
4329     // - If for some reason neither of those solutions works for you, a workaround is to call BeginChild()/EndChild() before reaching
4330     //   the 64K limit to split your draw commands in multiple draw lists.
4331     if (sizeof(ImDrawIdx) == 2)
4332         IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above");
4333 
4334     out_list->push_back(draw_list);
4335 }
4336 
AddWindowToDrawData(ImGuiWindow * window,int layer)4337 static void AddWindowToDrawData(ImGuiWindow* window, int layer)
4338 {
4339     ImGuiContext& g = *GImGui;
4340     ImGuiViewportP* viewport = g.Viewports[0];
4341     g.IO.MetricsRenderWindows++;
4342     AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[layer], window->DrawList);
4343     for (int i = 0; i < window->DC.ChildWindows.Size; i++)
4344     {
4345         ImGuiWindow* child = window->DC.ChildWindows[i];
4346         if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
4347             AddWindowToDrawData(child, layer);
4348     }
4349 }
4350 
4351 // Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
AddRootWindowToDrawData(ImGuiWindow * window)4352 static void AddRootWindowToDrawData(ImGuiWindow* window)
4353 {
4354     int layer = (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
4355     AddWindowToDrawData(window, layer);
4356 }
4357 
FlattenIntoSingleLayer()4358 void ImDrawDataBuilder::FlattenIntoSingleLayer()
4359 {
4360     int n = Layers[0].Size;
4361     int size = n;
4362     for (int i = 1; i < IM_ARRAYSIZE(Layers); i++)
4363         size += Layers[i].Size;
4364     Layers[0].resize(size);
4365     for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++)
4366     {
4367         ImVector<ImDrawList*>& layer = Layers[layer_n];
4368         if (layer.empty())
4369             continue;
4370         memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
4371         n += layer.Size;
4372         layer.resize(0);
4373     }
4374 }
4375 
SetupViewportDrawData(ImGuiViewportP * viewport,ImVector<ImDrawList * > * draw_lists)4376 static void SetupViewportDrawData(ImGuiViewportP* viewport, ImVector<ImDrawList*>* draw_lists)
4377 {
4378     ImGuiIO& io = ImGui::GetIO();
4379     ImDrawData* draw_data = &viewport->DrawDataP;
4380     draw_data->Valid = true;
4381     draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL;
4382     draw_data->CmdListsCount = draw_lists->Size;
4383     draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
4384     draw_data->DisplayPos = viewport->Pos;
4385     draw_data->DisplaySize = viewport->Size;
4386     draw_data->FramebufferScale = io.DisplayFramebufferScale;
4387     for (int n = 0; n < draw_lists->Size; n++)
4388     {
4389         draw_data->TotalVtxCount += draw_lists->Data[n]->VtxBuffer.Size;
4390         draw_data->TotalIdxCount += draw_lists->Data[n]->IdxBuffer.Size;
4391     }
4392 }
4393 
4394 // Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
4395 // - When using this function it is sane to ensure that float are perfectly rounded to integer values,
4396 //   so that e.g. (int)(max.x-min.x) in user's render produce correct result.
4397 // - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
4398 //   some frequently called functions which to modify both channels and clipping simultaneously tend to use the
4399 //   more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
PushClipRect(const ImVec2 & clip_rect_min,const ImVec2 & clip_rect_max,bool intersect_with_current_clip_rect)4400 void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
4401 {
4402     ImGuiWindow* window = GetCurrentWindow();
4403     window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
4404     window->ClipRect = window->DrawList->_ClipRectStack.back();
4405 }
4406 
PopClipRect()4407 void ImGui::PopClipRect()
4408 {
4409     ImGuiWindow* window = GetCurrentWindow();
4410     window->DrawList->PopClipRect();
4411     window->ClipRect = window->DrawList->_ClipRectStack.back();
4412 }
4413 
4414 // 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.
EndFrame()4415 void ImGui::EndFrame()
4416 {
4417     ImGuiContext& g = *GImGui;
4418     IM_ASSERT(g.Initialized);
4419 
4420     // Don't process EndFrame() multiple times.
4421     if (g.FrameCountEnded == g.FrameCount)
4422         return;
4423     IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
4424 
4425     CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
4426 
4427     ErrorCheckEndFrameSanityChecks();
4428 
4429     // Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
4430     if (g.IO.ImeSetInputScreenPosFn && (g.PlatformImeLastPos.x == FLT_MAX || ImLengthSqr(g.PlatformImeLastPos - g.PlatformImePos) > 0.0001f))
4431     {
4432         g.IO.ImeSetInputScreenPosFn((int)g.PlatformImePos.x, (int)g.PlatformImePos.y);
4433         g.PlatformImeLastPos = g.PlatformImePos;
4434     }
4435 
4436     // Hide implicit/fallback "Debug" window if it hasn't been used
4437     g.WithinFrameScopeWithImplicitWindow = false;
4438     if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
4439         g.CurrentWindow->Active = false;
4440     End();
4441 
4442     // Update navigation: CTRL+Tab, wrap-around requests
4443     NavEndFrame();
4444 
4445     // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
4446     if (g.DragDropActive)
4447     {
4448         bool is_delivered = g.DragDropPayload.Delivery;
4449         bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));
4450         if (is_delivered || is_elapsed)
4451             ClearDragDrop();
4452     }
4453 
4454     // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
4455     if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
4456     {
4457         g.DragDropWithinSource = true;
4458         SetTooltip("...");
4459         g.DragDropWithinSource = false;
4460     }
4461 
4462     // End frame
4463     g.WithinFrameScope = false;
4464     g.FrameCountEnded = g.FrameCount;
4465 
4466     // Initiate moving window + handle left-click and right-click focus
4467     UpdateMouseMovingWindowEndFrame();
4468 
4469     // Sort the window list so that all child windows are after their parent
4470     // We cannot do that on FocusWindow() because children may not exist yet
4471     g.WindowsTempSortBuffer.resize(0);
4472     g.WindowsTempSortBuffer.reserve(g.Windows.Size);
4473     for (int i = 0; i != g.Windows.Size; i++)
4474     {
4475         ImGuiWindow* window = g.Windows[i];
4476         if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow))       // if a child is active its parent will add it
4477             continue;
4478         AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
4479     }
4480 
4481     // 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.
4482     IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
4483     g.Windows.swap(g.WindowsTempSortBuffer);
4484     g.IO.MetricsActiveWindows = g.WindowsActiveCount;
4485 
4486     // Unlock font atlas
4487     g.IO.Fonts->Locked = false;
4488 
4489     // Clear Input data for next frame
4490     g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
4491     g.IO.InputQueueCharacters.resize(0);
4492     g.IO.KeyModsPrev = g.IO.KeyMods; // doing it here is better than in NewFrame() as we'll tolerate backend writing to KeyMods. If we want to firmly disallow it we should detect it.
4493     memset(g.IO.NavInputs, 0, sizeof(g.IO.NavInputs));
4494 
4495     CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
4496 }
4497 
4498 // Prepare the data for rendering so you can call GetDrawData()
4499 // (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all:
4500 // it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
Render()4501 void ImGui::Render()
4502 {
4503     ImGuiContext& g = *GImGui;
4504     IM_ASSERT(g.Initialized);
4505 
4506     if (g.FrameCountEnded != g.FrameCount)
4507         EndFrame();
4508     g.FrameCountRendered = g.FrameCount;
4509     g.IO.MetricsRenderWindows = 0;
4510 
4511     CallContextHooks(&g, ImGuiContextHookType_RenderPre);
4512 
4513     // Add background ImDrawList (for each active viewport)
4514     for (int n = 0; n != g.Viewports.Size; n++)
4515     {
4516         ImGuiViewportP* viewport = g.Viewports[n];
4517         viewport->DrawDataBuilder.Clear();
4518         if (viewport->DrawLists[0] != NULL)
4519             AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
4520     }
4521 
4522     // Add ImDrawList to render
4523     ImGuiWindow* windows_to_render_top_most[2];
4524     windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindow : NULL;
4525     windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
4526     for (int n = 0; n != g.Windows.Size; n++)
4527     {
4528         ImGuiWindow* window = g.Windows[n];
4529         IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
4530         if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
4531             AddRootWindowToDrawData(window);
4532     }
4533     for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
4534         if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
4535             AddRootWindowToDrawData(windows_to_render_top_most[n]);
4536 
4537     // Setup ImDrawData structures for end-user
4538     g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
4539     for (int n = 0; n < g.Viewports.Size; n++)
4540     {
4541         ImGuiViewportP* viewport = g.Viewports[n];
4542         viewport->DrawDataBuilder.FlattenIntoSingleLayer();
4543 
4544         // Draw software mouse cursor if requested by io.MouseDrawCursor flag
4545         if (g.IO.MouseDrawCursor)
4546             RenderMouseCursor(GetForegroundDrawList(viewport), g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
4547 
4548         // Add foreground ImDrawList (for each active viewport)
4549         if (viewport->DrawLists[1] != NULL)
4550             AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
4551 
4552         SetupViewportDrawData(viewport, &viewport->DrawDataBuilder.Layers[0]);
4553         ImDrawData* draw_data = &viewport->DrawDataP;
4554         g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
4555         g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
4556     }
4557 
4558     CallContextHooks(&g, ImGuiContextHookType_RenderPost);
4559 }
4560 
4561 // Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
4562 // CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
CalcTextSize(const char * text,const char * text_end,bool hide_text_after_double_hash,float wrap_width)4563 ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
4564 {
4565     ImGuiContext& g = *GImGui;
4566 
4567     const char* text_display_end;
4568     if (hide_text_after_double_hash)
4569         text_display_end = FindRenderedTextEnd(text, text_end);      // Hide anything after a '##' string
4570     else
4571         text_display_end = text_end;
4572 
4573     ImFont* font = g.Font;
4574     const float font_size = g.FontSize;
4575     if (text == text_display_end)
4576         return ImVec2(0.0f, font_size);
4577     ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
4578 
4579     // Round
4580     // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
4581     // FIXME: Investigate using ceilf or e.g.
4582     // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
4583     // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
4584     text_size.x = IM_FLOOR(text_size.x + 0.99999f);
4585 
4586     return text_size;
4587 }
4588 
4589 // Find window given position, search front-to-back
4590 // FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
4591 // with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
4592 // called, aka before the next Begin(). Moving window isn't affected.
FindHoveredWindow()4593 static void FindHoveredWindow()
4594 {
4595     ImGuiContext& g = *GImGui;
4596 
4597     ImGuiWindow* hovered_window = NULL;
4598     ImGuiWindow* hovered_window_ignoring_moving_window = NULL;
4599     if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
4600         hovered_window = g.MovingWindow;
4601 
4602     ImVec2 padding_regular = g.Style.TouchExtraPadding;
4603     ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;
4604     for (int i = g.Windows.Size - 1; i >= 0; i--)
4605     {
4606         ImGuiWindow* window = g.Windows[i];
4607         IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
4608         if (!window->Active || window->Hidden)
4609             continue;
4610         if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
4611             continue;
4612 
4613         // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
4614         ImRect bb(window->OuterRectClipped);
4615         if (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize))
4616             bb.Expand(padding_regular);
4617         else
4618             bb.Expand(padding_for_resize);
4619         if (!bb.Contains(g.IO.MousePos))
4620             continue;
4621 
4622         // Support for one rectangular hole in any given window
4623         // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
4624         if (window->HitTestHoleSize.x != 0)
4625         {
4626             ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
4627             ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
4628             if (ImRect(hole_pos, hole_pos + hole_size).Contains(g.IO.MousePos))
4629                 continue;
4630         }
4631 
4632         if (hovered_window == NULL)
4633             hovered_window = window;
4634         IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
4635         if (hovered_window_ignoring_moving_window == NULL && (!g.MovingWindow || window->RootWindow != g.MovingWindow->RootWindow))
4636             hovered_window_ignoring_moving_window = window;
4637         if (hovered_window && hovered_window_ignoring_moving_window)
4638             break;
4639     }
4640 
4641     g.HoveredWindow = hovered_window;
4642     g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window;
4643 }
4644 
4645 // Test if mouse cursor is hovering given rectangle
4646 // NB- Rectangle is clipped by our current clip setting
4647 // NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
IsMouseHoveringRect(const ImVec2 & r_min,const ImVec2 & r_max,bool clip)4648 bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
4649 {
4650     ImGuiContext& g = *GImGui;
4651 
4652     // Clip
4653     ImRect rect_clipped(r_min, r_max);
4654     if (clip)
4655         rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
4656 
4657     // Expand for touch input
4658     const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
4659     if (!rect_for_touch.Contains(g.IO.MousePos))
4660         return false;
4661     return true;
4662 }
4663 
GetKeyIndex(ImGuiKey imgui_key)4664 int ImGui::GetKeyIndex(ImGuiKey imgui_key)
4665 {
4666     IM_ASSERT(imgui_key >= 0 && imgui_key < ImGuiKey_COUNT);
4667     ImGuiContext& g = *GImGui;
4668     return g.IO.KeyMap[imgui_key];
4669 }
4670 
4671 // Note that dear imgui doesn't know the semantic of each entry of io.KeysDown[]!
4672 // Use your own indices/enums according to how your backend/engine stored them into io.KeysDown[]!
IsKeyDown(int user_key_index)4673 bool ImGui::IsKeyDown(int user_key_index)
4674 {
4675     if (user_key_index < 0)
4676         return false;
4677     ImGuiContext& g = *GImGui;
4678     IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
4679     return g.IO.KeysDown[user_key_index];
4680 }
4681 
4682 // t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
4683 // t1 = current time (e.g.: g.Time)
4684 // An event is triggered at:
4685 //  t = 0.0f     t = repeat_delay,    t = repeat_delay + repeat_rate*N
CalcTypematicRepeatAmount(float t0,float t1,float repeat_delay,float repeat_rate)4686 int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
4687 {
4688     if (t1 == 0.0f)
4689         return 1;
4690     if (t0 >= t1)
4691         return 0;
4692     if (repeat_rate <= 0.0f)
4693         return (t0 < repeat_delay) && (t1 >= repeat_delay);
4694     const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
4695     const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
4696     const int count = count_t1 - count_t0;
4697     return count;
4698 }
4699 
GetKeyPressedAmount(int key_index,float repeat_delay,float repeat_rate)4700 int ImGui::GetKeyPressedAmount(int key_index, float repeat_delay, float repeat_rate)
4701 {
4702     ImGuiContext& g = *GImGui;
4703     if (key_index < 0)
4704         return 0;
4705     IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown));
4706     const float t = g.IO.KeysDownDuration[key_index];
4707     return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
4708 }
4709 
IsKeyPressed(int user_key_index,bool repeat)4710 bool ImGui::IsKeyPressed(int user_key_index, bool repeat)
4711 {
4712     ImGuiContext& g = *GImGui;
4713     if (user_key_index < 0)
4714         return false;
4715     IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
4716     const float t = g.IO.KeysDownDuration[user_key_index];
4717     if (t == 0.0f)
4718         return true;
4719     if (repeat && t > g.IO.KeyRepeatDelay)
4720         return GetKeyPressedAmount(user_key_index, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0;
4721     return false;
4722 }
4723 
IsKeyReleased(int user_key_index)4724 bool ImGui::IsKeyReleased(int user_key_index)
4725 {
4726     ImGuiContext& g = *GImGui;
4727     if (user_key_index < 0) return false;
4728     IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
4729     return g.IO.KeysDownDurationPrev[user_key_index] >= 0.0f && !g.IO.KeysDown[user_key_index];
4730 }
4731 
IsMouseDown(ImGuiMouseButton button)4732 bool ImGui::IsMouseDown(ImGuiMouseButton button)
4733 {
4734     ImGuiContext& g = *GImGui;
4735     IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
4736     return g.IO.MouseDown[button];
4737 }
4738 
IsMouseClicked(ImGuiMouseButton button,bool repeat)4739 bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
4740 {
4741     ImGuiContext& g = *GImGui;
4742     IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
4743     const float t = g.IO.MouseDownDuration[button];
4744     if (t == 0.0f)
4745         return true;
4746 
4747     if (repeat && t > g.IO.KeyRepeatDelay)
4748     {
4749         // FIXME: 2019/05/03: Our old repeat code was wrong here and led to doubling the repeat rate, which made it an ok rate for repeat on mouse hold.
4750         int amount = CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate * 0.50f);
4751         if (amount > 0)
4752             return true;
4753     }
4754     return false;
4755 }
4756 
IsMouseReleased(ImGuiMouseButton button)4757 bool ImGui::IsMouseReleased(ImGuiMouseButton button)
4758 {
4759     ImGuiContext& g = *GImGui;
4760     IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
4761     return g.IO.MouseReleased[button];
4762 }
4763 
IsMouseDoubleClicked(ImGuiMouseButton button)4764 bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
4765 {
4766     ImGuiContext& g = *GImGui;
4767     IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
4768     return g.IO.MouseDoubleClicked[button];
4769 }
4770 
4771 // Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
4772 // [Internal] This doesn't test if the button is pressed
IsMouseDragPastThreshold(ImGuiMouseButton button,float lock_threshold)4773 bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
4774 {
4775     ImGuiContext& g = *GImGui;
4776     IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
4777     if (lock_threshold < 0.0f)
4778         lock_threshold = g.IO.MouseDragThreshold;
4779     return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
4780 }
4781 
IsMouseDragging(ImGuiMouseButton button,float lock_threshold)4782 bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
4783 {
4784     ImGuiContext& g = *GImGui;
4785     IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
4786     if (!g.IO.MouseDown[button])
4787         return false;
4788     return IsMouseDragPastThreshold(button, lock_threshold);
4789 }
4790 
GetMousePos()4791 ImVec2 ImGui::GetMousePos()
4792 {
4793     ImGuiContext& g = *GImGui;
4794     return g.IO.MousePos;
4795 }
4796 
4797 // NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
GetMousePosOnOpeningCurrentPopup()4798 ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
4799 {
4800     ImGuiContext& g = *GImGui;
4801     if (g.BeginPopupStack.Size > 0)
4802         return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
4803     return g.IO.MousePos;
4804 }
4805 
4806 // We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
IsMousePosValid(const ImVec2 * mouse_pos)4807 bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
4808 {
4809     // The assert is only to silence a false-positive in XCode Static Analysis.
4810     // 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).
4811     IM_ASSERT(GImGui != NULL);
4812     const float MOUSE_INVALID = -256000.0f;
4813     ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
4814     return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
4815 }
4816 
IsAnyMouseDown()4817 bool ImGui::IsAnyMouseDown()
4818 {
4819     ImGuiContext& g = *GImGui;
4820     for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
4821         if (g.IO.MouseDown[n])
4822             return true;
4823     return false;
4824 }
4825 
4826 // Return the delta from the initial clicking position while the mouse button is clicked or was just released.
4827 // This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
4828 // NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
GetMouseDragDelta(ImGuiMouseButton button,float lock_threshold)4829 ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
4830 {
4831     ImGuiContext& g = *GImGui;
4832     IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
4833     if (lock_threshold < 0.0f)
4834         lock_threshold = g.IO.MouseDragThreshold;
4835     if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
4836         if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
4837             if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
4838                 return g.IO.MousePos - g.IO.MouseClickedPos[button];
4839     return ImVec2(0.0f, 0.0f);
4840 }
4841 
ResetMouseDragDelta(ImGuiMouseButton button)4842 void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
4843 {
4844     ImGuiContext& g = *GImGui;
4845     IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
4846     // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
4847     g.IO.MouseClickedPos[button] = g.IO.MousePos;
4848 }
4849 
GetMouseCursor()4850 ImGuiMouseCursor ImGui::GetMouseCursor()
4851 {
4852     return GImGui->MouseCursor;
4853 }
4854 
SetMouseCursor(ImGuiMouseCursor cursor_type)4855 void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
4856 {
4857     GImGui->MouseCursor = cursor_type;
4858 }
4859 
CaptureKeyboardFromApp(bool capture)4860 void ImGui::CaptureKeyboardFromApp(bool capture)
4861 {
4862     GImGui->WantCaptureKeyboardNextFrame = capture ? 1 : 0;
4863 }
4864 
CaptureMouseFromApp(bool capture)4865 void ImGui::CaptureMouseFromApp(bool capture)
4866 {
4867     GImGui->WantCaptureMouseNextFrame = capture ? 1 : 0;
4868 }
4869 
IsItemActive()4870 bool ImGui::IsItemActive()
4871 {
4872     ImGuiContext& g = *GImGui;
4873     if (g.ActiveId)
4874         return g.ActiveId == g.LastItemData.ID;
4875     return false;
4876 }
4877 
IsItemActivated()4878 bool ImGui::IsItemActivated()
4879 {
4880     ImGuiContext& g = *GImGui;
4881     if (g.ActiveId)
4882         if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
4883             return true;
4884     return false;
4885 }
4886 
IsItemDeactivated()4887 bool ImGui::IsItemDeactivated()
4888 {
4889     ImGuiContext& g = *GImGui;
4890     if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
4891         return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
4892     return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID);
4893 }
4894 
IsItemDeactivatedAfterEdit()4895 bool ImGui::IsItemDeactivatedAfterEdit()
4896 {
4897     ImGuiContext& g = *GImGui;
4898     return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
4899 }
4900 
4901 // == GetItemID() == GetFocusID()
IsItemFocused()4902 bool ImGui::IsItemFocused()
4903 {
4904     ImGuiContext& g = *GImGui;
4905     if (g.NavId != g.LastItemData.ID || g.NavId == 0)
4906         return false;
4907     return true;
4908 }
4909 
4910 // Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
4911 // Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
IsItemClicked(ImGuiMouseButton mouse_button)4912 bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
4913 {
4914     return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
4915 }
4916 
IsItemToggledOpen()4917 bool ImGui::IsItemToggledOpen()
4918 {
4919     ImGuiContext& g = *GImGui;
4920     return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
4921 }
4922 
IsItemToggledSelection()4923 bool ImGui::IsItemToggledSelection()
4924 {
4925     ImGuiContext& g = *GImGui;
4926     return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
4927 }
4928 
IsAnyItemHovered()4929 bool ImGui::IsAnyItemHovered()
4930 {
4931     ImGuiContext& g = *GImGui;
4932     return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
4933 }
4934 
IsAnyItemActive()4935 bool ImGui::IsAnyItemActive()
4936 {
4937     ImGuiContext& g = *GImGui;
4938     return g.ActiveId != 0;
4939 }
4940 
IsAnyItemFocused()4941 bool ImGui::IsAnyItemFocused()
4942 {
4943     ImGuiContext& g = *GImGui;
4944     return g.NavId != 0 && !g.NavDisableHighlight;
4945 }
4946 
IsItemVisible()4947 bool ImGui::IsItemVisible()
4948 {
4949     ImGuiContext& g = *GImGui;
4950     return g.CurrentWindow->ClipRect.Overlaps(g.LastItemData.Rect);
4951 }
4952 
IsItemEdited()4953 bool ImGui::IsItemEdited()
4954 {
4955     ImGuiContext& g = *GImGui;
4956     return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
4957 }
4958 
4959 // Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
4960 // FIXME: Although this is exposed, its interaction and ideal idiom with using ImGuiButtonFlags_AllowItemOverlap flag are extremely confusing, need rework.
SetItemAllowOverlap()4961 void ImGui::SetItemAllowOverlap()
4962 {
4963     ImGuiContext& g = *GImGui;
4964     ImGuiID id = g.LastItemData.ID;
4965     if (g.HoveredId == id)
4966         g.HoveredIdAllowOverlap = true;
4967     if (g.ActiveId == id)
4968         g.ActiveIdAllowOverlap = true;
4969 }
4970 
SetItemUsingMouseWheel()4971 void ImGui::SetItemUsingMouseWheel()
4972 {
4973     ImGuiContext& g = *GImGui;
4974     ImGuiID id = g.LastItemData.ID;
4975     if (g.HoveredId == id)
4976         g.HoveredIdUsingMouseWheel = true;
4977     if (g.ActiveId == id)
4978         g.ActiveIdUsingMouseWheel = true;
4979 }
4980 
SetActiveIdUsingNavAndKeys()4981 void ImGui::SetActiveIdUsingNavAndKeys()
4982 {
4983     ImGuiContext& g = *GImGui;
4984     IM_ASSERT(g.ActiveId != 0);
4985     g.ActiveIdUsingNavDirMask = ~(ImU32)0;
4986     g.ActiveIdUsingNavInputMask = ~(ImU32)0;
4987     g.ActiveIdUsingKeyInputMask = ~(ImU64)0;
4988     NavMoveRequestCancel();
4989 }
4990 
GetItemRectMin()4991 ImVec2 ImGui::GetItemRectMin()
4992 {
4993     ImGuiContext& g = *GImGui;
4994     return g.LastItemData.Rect.Min;
4995 }
4996 
GetItemRectMax()4997 ImVec2 ImGui::GetItemRectMax()
4998 {
4999     ImGuiContext& g = *GImGui;
5000     return g.LastItemData.Rect.Max;
5001 }
5002 
GetItemRectSize()5003 ImVec2 ImGui::GetItemRectSize()
5004 {
5005     ImGuiContext& g = *GImGui;
5006     return g.LastItemData.Rect.GetSize();
5007 }
5008 
BeginChildEx(const char * name,ImGuiID id,const ImVec2 & size_arg,bool border,ImGuiWindowFlags flags)5009 bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags)
5010 {
5011     ImGuiContext& g = *GImGui;
5012     ImGuiWindow* parent_window = g.CurrentWindow;
5013 
5014     flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_ChildWindow;
5015     flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove);  // Inherit the NoMove flag
5016 
5017     // Size
5018     const ImVec2 content_avail = GetContentRegionAvail();
5019     ImVec2 size = ImFloor(size_arg);
5020     const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00);
5021     if (size.x <= 0.0f)
5022         size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
5023     if (size.y <= 0.0f)
5024         size.y = ImMax(content_avail.y + size.y, 4.0f);
5025     SetNextWindowSize(size);
5026 
5027     // 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.
5028     if (name)
5029         ImFormatString(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), "%s/%s_%08X", parent_window->Name, name, id);
5030     else
5031         ImFormatString(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), "%s/%08X", parent_window->Name, id);
5032 
5033     const float backup_border_size = g.Style.ChildBorderSize;
5034     if (!border)
5035         g.Style.ChildBorderSize = 0.0f;
5036     bool ret = Begin(g.TempBuffer, NULL, flags);
5037     g.Style.ChildBorderSize = backup_border_size;
5038 
5039     ImGuiWindow* child_window = g.CurrentWindow;
5040     child_window->ChildId = id;
5041     child_window->AutoFitChildAxises = (ImS8)auto_fit_axises;
5042 
5043     // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
5044     // While this is not really documented/defined, it seems that the expected thing to do.
5045     if (child_window->BeginCount == 1)
5046         parent_window->DC.CursorPos = child_window->Pos;
5047 
5048     // Process navigation-in immediately so NavInit can run on first frame
5049     if (g.NavActivateId == id && !(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavHasScroll))
5050     {
5051         FocusWindow(child_window);
5052         NavInitWindow(child_window, false);
5053         SetActiveID(id + 1, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
5054         g.ActiveIdSource = ImGuiInputSource_Nav;
5055     }
5056     return ret;
5057 }
5058 
BeginChild(const char * str_id,const ImVec2 & size_arg,bool border,ImGuiWindowFlags extra_flags)5059 bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
5060 {
5061     ImGuiWindow* window = GetCurrentWindow();
5062     return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags);
5063 }
5064 
BeginChild(ImGuiID id,const ImVec2 & size_arg,bool border,ImGuiWindowFlags extra_flags)5065 bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
5066 {
5067     IM_ASSERT(id != 0);
5068     return BeginChildEx(NULL, id, size_arg, border, extra_flags);
5069 }
5070 
EndChild()5071 void ImGui::EndChild()
5072 {
5073     ImGuiContext& g = *GImGui;
5074     ImGuiWindow* window = g.CurrentWindow;
5075 
5076     IM_ASSERT(g.WithinEndChild == false);
5077     IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow);   // Mismatched BeginChild()/EndChild() calls
5078 
5079     g.WithinEndChild = true;
5080     if (window->BeginCount > 1)
5081     {
5082         End();
5083     }
5084     else
5085     {
5086         ImVec2 sz = window->Size;
5087         if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f
5088             sz.x = ImMax(4.0f, sz.x);
5089         if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y))
5090             sz.y = ImMax(4.0f, sz.y);
5091         End();
5092 
5093         ImGuiWindow* parent_window = g.CurrentWindow;
5094         ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz);
5095         ItemSize(sz);
5096         if ((window->DC.NavLayersActiveMask != 0 || window->DC.NavHasScroll) && !(window->Flags & ImGuiWindowFlags_NavFlattened))
5097         {
5098             ItemAdd(bb, window->ChildId);
5099             RenderNavHighlight(bb, window->ChildId);
5100 
5101             // 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)
5102             if (window->DC.NavLayersActiveMask == 0 && window == g.NavWindow)
5103                 RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_TypeThin);
5104         }
5105         else
5106         {
5107             // Not navigable into
5108             ItemAdd(bb, 0);
5109         }
5110         if (g.HoveredWindow == window)
5111             g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
5112     }
5113     g.WithinEndChild = false;
5114     g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
5115 }
5116 
5117 // Helper to create a child window / scrolling region that looks like a normal widget frame.
BeginChildFrame(ImGuiID id,const ImVec2 & size,ImGuiWindowFlags extra_flags)5118 bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags)
5119 {
5120     ImGuiContext& g = *GImGui;
5121     const ImGuiStyle& style = g.Style;
5122     PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
5123     PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
5124     PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
5125     PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
5126     bool ret = BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
5127     PopStyleVar(3);
5128     PopStyleColor();
5129     return ret;
5130 }
5131 
EndChildFrame()5132 void ImGui::EndChildFrame()
5133 {
5134     EndChild();
5135 }
5136 
SetWindowConditionAllowFlags(ImGuiWindow * window,ImGuiCond flags,bool enabled)5137 static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
5138 {
5139     window->SetWindowPosAllowFlags       = enabled ? (window->SetWindowPosAllowFlags       | flags) : (window->SetWindowPosAllowFlags       & ~flags);
5140     window->SetWindowSizeAllowFlags      = enabled ? (window->SetWindowSizeAllowFlags      | flags) : (window->SetWindowSizeAllowFlags      & ~flags);
5141     window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
5142 }
5143 
FindWindowByID(ImGuiID id)5144 ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
5145 {
5146     ImGuiContext& g = *GImGui;
5147     return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
5148 }
5149 
FindWindowByName(const char * name)5150 ImGuiWindow* ImGui::FindWindowByName(const char* name)
5151 {
5152     ImGuiID id = ImHashStr(name);
5153     return FindWindowByID(id);
5154 }
5155 
ApplyWindowSettings(ImGuiWindow * window,ImGuiWindowSettings * settings)5156 static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5157 {
5158     window->Pos = ImFloor(ImVec2(settings->Pos.x, settings->Pos.y));
5159     if (settings->Size.x > 0 && settings->Size.y > 0)
5160         window->Size = window->SizeFull = ImFloor(ImVec2(settings->Size.x, settings->Size.y));
5161     window->Collapsed = settings->Collapsed;
5162 }
5163 
CreateNewWindow(const char * name,ImGuiWindowFlags flags)5164 static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
5165 {
5166     ImGuiContext& g = *GImGui;
5167     //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
5168 
5169     // Create window the first time
5170     ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
5171     window->Flags = flags;
5172     g.WindowsById.SetVoidPtr(window->ID, window);
5173 
5174     // Default/arbitrary window position. Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
5175     const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5176     window->Pos = main_viewport->Pos + ImVec2(60, 60);
5177 
5178     // User can disable loading and saving of settings. Tooltip and child windows also don't store settings.
5179     if (!(flags & ImGuiWindowFlags_NoSavedSettings))
5180         if (ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID))
5181         {
5182             // Retrieve settings from .ini file
5183             window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
5184             SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
5185             ApplyWindowSettings(window, settings);
5186         }
5187     window->DC.CursorStartPos = window->DC.CursorMaxPos = window->Pos; // So first call to CalcContentSize() doesn't return crazy values
5188 
5189     if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
5190     {
5191         window->AutoFitFramesX = window->AutoFitFramesY = 2;
5192         window->AutoFitOnlyGrows = false;
5193     }
5194     else
5195     {
5196         if (window->Size.x <= 0.0f)
5197             window->AutoFitFramesX = 2;
5198         if (window->Size.y <= 0.0f)
5199             window->AutoFitFramesY = 2;
5200         window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
5201     }
5202 
5203     if (!(flags & ImGuiWindowFlags_ChildWindow))
5204     {
5205         g.WindowsFocusOrder.push_back(window);
5206         window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
5207     }
5208 
5209     if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
5210         g.Windows.push_front(window); // Quite slow but rare and only once
5211     else
5212         g.Windows.push_back(window);
5213     return window;
5214 }
5215 
CalcWindowSizeAfterConstraint(ImGuiWindow * window,const ImVec2 & size_desired)5216 static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
5217 {
5218     ImGuiContext& g = *GImGui;
5219     ImVec2 new_size = size_desired;
5220     if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
5221     {
5222         // Using -1,-1 on either X/Y axis to preserve the current size.
5223         ImRect cr = g.NextWindowData.SizeConstraintRect;
5224         new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
5225         new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
5226         if (g.NextWindowData.SizeCallback)
5227         {
5228             ImGuiSizeCallbackData data;
5229             data.UserData = g.NextWindowData.SizeCallbackUserData;
5230             data.Pos = window->Pos;
5231             data.CurrentSize = window->SizeFull;
5232             data.DesiredSize = new_size;
5233             g.NextWindowData.SizeCallback(&data);
5234             new_size = data.DesiredSize;
5235         }
5236         new_size.x = IM_FLOOR(new_size.x);
5237         new_size.y = IM_FLOOR(new_size.y);
5238     }
5239 
5240     // Minimum size
5241     if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
5242     {
5243         ImGuiWindow* window_for_height = window;
5244         const float decoration_up_height = window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight();
5245         new_size = ImMax(new_size, g.Style.WindowMinSize);
5246         new_size.y = ImMax(new_size.y, decoration_up_height + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows
5247     }
5248     return new_size;
5249 }
5250 
CalcWindowContentSizes(ImGuiWindow * window,ImVec2 * content_size_current,ImVec2 * content_size_ideal)5251 static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
5252 {
5253     bool preserve_old_content_sizes = false;
5254     if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
5255         preserve_old_content_sizes = true;
5256     else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
5257         preserve_old_content_sizes = true;
5258     if (preserve_old_content_sizes)
5259     {
5260         *content_size_current = window->ContentSize;
5261         *content_size_ideal = window->ContentSizeIdeal;
5262         return;
5263     }
5264 
5265     content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
5266     content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
5267     content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
5268     content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
5269 }
5270 
CalcWindowAutoFitSize(ImGuiWindow * window,const ImVec2 & size_contents)5271 static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
5272 {
5273     ImGuiContext& g = *GImGui;
5274     ImGuiStyle& style = g.Style;
5275     const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
5276     ImVec2 size_pad = window->WindowPadding * 2.0f;
5277     ImVec2 size_desired = size_contents + size_pad + ImVec2(0.0f, decoration_up_height);
5278     if (window->Flags & ImGuiWindowFlags_Tooltip)
5279     {
5280         // Tooltip always resize
5281         return size_desired;
5282     }
5283     else
5284     {
5285         // Maximum window size is determined by the viewport size or monitor size
5286         const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0;
5287         const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0;
5288         ImVec2 size_min = style.WindowMinSize;
5289         if (is_popup || is_menu) // Popups and menus bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
5290             size_min = ImMin(size_min, ImVec2(4.0f, 4.0f));
5291 
5292         // FIXME-VIEWPORT-WORKAREA: May want to use GetWorkSize() instead of Size depending on the type of windows?
5293         ImVec2 avail_size = ImGui::GetMainViewport()->Size;
5294         ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, avail_size - style.DisplaySafeAreaPadding * 2.0f));
5295 
5296         // When the window cannot fit all contents (either because of constraints, either because screen is too small),
5297         // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
5298         ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
5299         bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - 0.0f                 < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
5300         bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - decoration_up_height < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
5301         if (will_have_scrollbar_x)
5302             size_auto_fit.y += style.ScrollbarSize;
5303         if (will_have_scrollbar_y)
5304             size_auto_fit.x += style.ScrollbarSize;
5305         return size_auto_fit;
5306     }
5307 }
5308 
CalcWindowNextAutoFitSize(ImGuiWindow * window)5309 ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
5310 {
5311     ImVec2 size_contents_current;
5312     ImVec2 size_contents_ideal;
5313     CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
5314     ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);
5315     ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
5316     return size_final;
5317 }
5318 
GetWindowBgColorIdxFromFlags(ImGuiWindowFlags flags)5319 static ImGuiCol GetWindowBgColorIdxFromFlags(ImGuiWindowFlags flags)
5320 {
5321     if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
5322         return ImGuiCol_PopupBg;
5323     if (flags & ImGuiWindowFlags_ChildWindow)
5324         return ImGuiCol_ChildBg;
5325     return ImGuiCol_WindowBg;
5326 }
5327 
CalcResizePosSizeFromAnyCorner(ImGuiWindow * window,const ImVec2 & corner_target,const ImVec2 & corner_norm,ImVec2 * out_pos,ImVec2 * out_size)5328 static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
5329 {
5330     ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm);                // Expected window upper-left
5331     ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
5332     ImVec2 size_expected = pos_max - pos_min;
5333     ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
5334     *out_pos = pos_min;
5335     if (corner_norm.x == 0.0f)
5336         out_pos->x -= (size_constrained.x - size_expected.x);
5337     if (corner_norm.y == 0.0f)
5338         out_pos->y -= (size_constrained.y - size_expected.y);
5339     *out_size = size_constrained;
5340 }
5341 
5342 // Data for resizing from corner
5343 struct ImGuiResizeGripDef
5344 {
5345     ImVec2  CornerPosN;
5346     ImVec2  InnerDir;
5347     int     AngleMin12, AngleMax12;
5348 };
5349 static const ImGuiResizeGripDef resize_grip_def[4] =
5350 {
5351     { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 },  // Lower-right
5352     { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 },  // Lower-left
5353     { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 },  // Upper-left (Unused)
5354     { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 }  // Upper-right (Unused)
5355 };
5356 
5357 // Data for resizing from borders
5358 struct ImGuiResizeBorderDef
5359 {
5360     ImVec2 InnerDir;
5361     ImVec2 SegmentN1, SegmentN2;
5362     float  OuterAngle;
5363 };
5364 static const ImGuiResizeBorderDef resize_border_def[4] =
5365 {
5366     { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left
5367     { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
5368     { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up
5369     { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f }  // Down
5370 };
5371 
GetResizeBorderRect(ImGuiWindow * window,int border_n,float perp_padding,float thickness)5372 static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
5373 {
5374     ImRect rect = window->Rect();
5375     if (thickness == 0.0f)
5376         rect.Max -= ImVec2(1, 1);
5377     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); }
5378     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); }
5379     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);    }
5380     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);    }
5381     IM_ASSERT(0);
5382     return ImRect();
5383 }
5384 
5385 // 0..3: corners (Lower-right, Lower-left, Unused, Unused)
GetWindowResizeCornerID(ImGuiWindow * window,int n)5386 ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
5387 {
5388     IM_ASSERT(n >= 0 && n < 4);
5389     ImGuiID id = window->ID;
5390     id = ImHashStr("#RESIZE", 0, id);
5391     id = ImHashData(&n, sizeof(int), id);
5392     return id;
5393 }
5394 
5395 // Borders (Left, Right, Up, Down)
GetWindowResizeBorderID(ImGuiWindow * window,ImGuiDir dir)5396 ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
5397 {
5398     IM_ASSERT(dir >= 0 && dir < 4);
5399     int n = (int)dir + 4;
5400     ImGuiID id = window->ID;
5401     id = ImHashStr("#RESIZE", 0, id);
5402     id = ImHashData(&n, sizeof(int), id);
5403     return id;
5404 }
5405 
5406 // Handle resize for: Resize Grips, Borders, Gamepad
5407 // Return true when using auto-fit (double click on resize grip)
UpdateWindowManualResize(ImGuiWindow * window,const ImVec2 & size_auto_fit,int * border_held,int resize_grip_count,ImU32 resize_grip_col[4],const ImRect & visibility_rect)5408 static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
5409 {
5410     ImGuiContext& g = *GImGui;
5411     ImGuiWindowFlags flags = window->Flags;
5412 
5413     if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
5414         return false;
5415     if (window->WasActive == false) // Early out to avoid running this code for e.g. an hidden implicit/fallback Debug window.
5416         return false;
5417 
5418     bool ret_auto_fit = false;
5419     const int resize_border_count = g.IO.ConfigWindowsResizeFromEdges ? 4 : 0;
5420     const float grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
5421     const float grip_hover_inner_size = IM_FLOOR(grip_draw_size * 0.75f);
5422     const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;
5423 
5424     ImVec2 pos_target(FLT_MAX, FLT_MAX);
5425     ImVec2 size_target(FLT_MAX, FLT_MAX);
5426 
5427     // Resize grips and borders are on layer 1
5428     window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
5429 
5430     // Manual resize grips
5431     PushID("#RESIZE");
5432     for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
5433     {
5434         const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
5435         const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);
5436 
5437         // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
5438         bool hovered, held;
5439         ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
5440         if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
5441         if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
5442         ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()
5443         ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
5444         //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
5445         if (hovered || held)
5446             g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
5447 
5448         if (held && g.IO.MouseDoubleClicked[0] && resize_grip_n == 0)
5449         {
5450             // Manual auto-fit when double-clicking
5451             size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
5452             ret_auto_fit = true;
5453             ClearActiveID();
5454         }
5455         else if (held)
5456         {
5457             // Resize from any of the four corners
5458             // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
5459             ImVec2 clamp_min = ImVec2(def.CornerPosN.x == 1.0f ? visibility_rect.Min.x : -FLT_MAX, def.CornerPosN.y == 1.0f ? visibility_rect.Min.y : -FLT_MAX);
5460             ImVec2 clamp_max = ImVec2(def.CornerPosN.x == 0.0f ? visibility_rect.Max.x : +FLT_MAX, def.CornerPosN.y == 0.0f ? visibility_rect.Max.y : +FLT_MAX);
5461             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
5462             corner_target = ImClamp(corner_target, clamp_min, clamp_max);
5463             CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
5464         }
5465 
5466         // Only lower-left grip is visible before hovering/activating
5467         if (resize_grip_n == 0 || held || hovered)
5468             resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
5469     }
5470     for (int border_n = 0; border_n < resize_border_count; border_n++)
5471     {
5472         const ImGuiResizeBorderDef& def = resize_border_def[border_n];
5473         const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
5474 
5475         bool hovered, held;
5476         ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
5477         ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
5478         ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren);
5479         //GetForegroundDrawLists(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
5480         if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held)
5481         {
5482             g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
5483             if (held)
5484                 *border_held = border_n;
5485         }
5486         if (held)
5487         {
5488             ImVec2 clamp_min(border_n == ImGuiDir_Right ? visibility_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down ? visibility_rect.Min.y : -FLT_MAX);
5489             ImVec2 clamp_max(border_n == ImGuiDir_Left  ? visibility_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up   ? visibility_rect.Max.y : +FLT_MAX);
5490             ImVec2 border_target = window->Pos;
5491             border_target[axis] = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING;
5492             border_target = ImClamp(border_target, clamp_min, clamp_max);
5493             CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);
5494         }
5495     }
5496     PopID();
5497 
5498     // Restore nav layer
5499     window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
5500 
5501     // Navigation resize (keyboard/gamepad)
5502     if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindow == window)
5503     {
5504         ImVec2 nav_resize_delta;
5505         if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
5506             nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down);
5507         if (g.NavInputSource == ImGuiInputSource_Gamepad)
5508             nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_Down);
5509         if (nav_resize_delta.x != 0.0f || nav_resize_delta.y != 0.0f)
5510         {
5511             const float NAV_RESIZE_SPEED = 600.0f;
5512             nav_resize_delta *= ImFloor(NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y));
5513             nav_resize_delta = ImMax(nav_resize_delta, visibility_rect.Min - window->Pos - window->Size);
5514             g.NavWindowingToggleLayer = false;
5515             g.NavDisableMouseHover = true;
5516             resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
5517             // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
5518             size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + nav_resize_delta);
5519         }
5520     }
5521 
5522     // Apply back modified position/size to window
5523     if (size_target.x != FLT_MAX)
5524     {
5525         window->SizeFull = size_target;
5526         MarkIniSettingsDirty(window);
5527     }
5528     if (pos_target.x != FLT_MAX)
5529     {
5530         window->Pos = ImFloor(pos_target);
5531         MarkIniSettingsDirty(window);
5532     }
5533 
5534     window->Size = window->SizeFull;
5535     return ret_auto_fit;
5536 }
5537 
ClampWindowRect(ImGuiWindow * window,const ImRect & visibility_rect)5538 static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& visibility_rect)
5539 {
5540     ImGuiContext& g = *GImGui;
5541     ImVec2 size_for_clamping = window->Size;
5542     if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
5543         size_for_clamping.y = window->TitleBarHeight();
5544     window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
5545 }
5546 
RenderWindowOuterBorders(ImGuiWindow * window)5547 static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
5548 {
5549     ImGuiContext& g = *GImGui;
5550     float rounding = window->WindowRounding;
5551     float border_size = window->WindowBorderSize;
5552     if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground))
5553         window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
5554 
5555     int border_held = window->ResizeBorderHeld;
5556     if (border_held != -1)
5557     {
5558         const ImGuiResizeBorderDef& def = resize_border_def[border_held];
5559         ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f);
5560         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);
5561         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);
5562         window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), 0, ImMax(2.0f, border_size)); // Thicker than usual
5563     }
5564     if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
5565     {
5566         float y = window->Pos.y + window->TitleBarHeight() - 1;
5567         window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), GetColorU32(ImGuiCol_Border), g.Style.FrameBorderSize);
5568     }
5569 }
5570 
5571 // Draw background and borders
5572 // Draw and handle scrollbars
RenderWindowDecorations(ImGuiWindow * window,const ImRect & title_bar_rect,bool title_bar_is_highlight,int resize_grip_count,const ImU32 resize_grip_col[4],float resize_grip_draw_size)5573 void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
5574 {
5575     ImGuiContext& g = *GImGui;
5576     ImGuiStyle& style = g.Style;
5577     ImGuiWindowFlags flags = window->Flags;
5578 
5579     // Ensure that ScrollBar doesn't read last frame's SkipItems
5580     IM_ASSERT(window->BeginCount == 0);
5581     window->SkipItems = false;
5582 
5583     // Draw window + handle manual resize
5584     // As we highlight the title bar when want_focus is set, multiple reappearing windows will have have their title bar highlighted on their reappearing frame.
5585     const float window_rounding = window->WindowRounding;
5586     const float window_border_size = window->WindowBorderSize;
5587     if (window->Collapsed)
5588     {
5589         // Title bar only
5590         float backup_border_size = style.FrameBorderSize;
5591         g.Style.FrameBorderSize = window->WindowBorderSize;
5592         ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
5593         RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
5594         g.Style.FrameBorderSize = backup_border_size;
5595     }
5596     else
5597     {
5598         // Window background
5599         if (!(flags & ImGuiWindowFlags_NoBackground))
5600         {
5601             ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags));
5602             bool override_alpha = false;
5603             float alpha = 1.0f;
5604             if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
5605             {
5606                 alpha = g.NextWindowData.BgAlphaVal;
5607                 override_alpha = true;
5608             }
5609             if (override_alpha)
5610                 bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
5611             window->DrawList->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
5612         }
5613 
5614         // Title bar
5615         if (!(flags & ImGuiWindowFlags_NoTitleBar))
5616         {
5617             ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
5618             window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);
5619         }
5620 
5621         // Menu bar
5622         if (flags & ImGuiWindowFlags_MenuBar)
5623         {
5624             ImRect menu_bar_rect = window->MenuBarRect();
5625             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.
5626             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);
5627             if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
5628                 window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
5629         }
5630 
5631         // Scrollbars
5632         if (window->ScrollbarX)
5633             Scrollbar(ImGuiAxis_X);
5634         if (window->ScrollbarY)
5635             Scrollbar(ImGuiAxis_Y);
5636 
5637         // Render resize grips (after their input handling so we don't have a frame of latency)
5638         if (!(flags & ImGuiWindowFlags_NoResize))
5639         {
5640             for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
5641             {
5642                 const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
5643                 const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
5644                 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)));
5645                 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)));
5646                 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);
5647                 window->DrawList->PathFillConvex(resize_grip_col[resize_grip_n]);
5648             }
5649         }
5650 
5651         // Borders
5652         RenderWindowOuterBorders(window);
5653     }
5654 }
5655 
5656 // Render title text, collapse button, close button
RenderWindowTitleBarContents(ImGuiWindow * window,const ImRect & title_bar_rect,const char * name,bool * p_open)5657 void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
5658 {
5659     ImGuiContext& g = *GImGui;
5660     ImGuiStyle& style = g.Style;
5661     ImGuiWindowFlags flags = window->Flags;
5662 
5663     const bool has_close_button = (p_open != NULL);
5664     const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
5665 
5666     // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
5667     const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
5668     g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
5669     window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
5670 
5671     // Layout buttons
5672     // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
5673     float pad_l = style.FramePadding.x;
5674     float pad_r = style.FramePadding.x;
5675     float button_sz = g.FontSize;
5676     ImVec2 close_button_pos;
5677     ImVec2 collapse_button_pos;
5678     if (has_close_button)
5679     {
5680         pad_r += button_sz;
5681         close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
5682     }
5683     if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
5684     {
5685         pad_r += button_sz;
5686         collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
5687     }
5688     if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
5689     {
5690         collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l - style.FramePadding.x, title_bar_rect.Min.y);
5691         pad_l += button_sz;
5692     }
5693 
5694     // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
5695     if (has_collapse_button)
5696         if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos))
5697             window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
5698 
5699     // Close button
5700     if (has_close_button)
5701         if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
5702             *p_open = false;
5703 
5704     window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
5705     g.CurrentItemFlags = item_flags_backup;
5706 
5707     // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
5708     // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
5709     const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
5710     const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
5711 
5712     // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
5713     // while uncentered title text will still reach edges correctly.
5714     if (pad_l > style.FramePadding.x)
5715         pad_l += g.Style.ItemInnerSpacing.x;
5716     if (pad_r > style.FramePadding.x)
5717         pad_r += g.Style.ItemInnerSpacing.x;
5718     if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
5719     {
5720         float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
5721         float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
5722         pad_l = ImMax(pad_l, pad_extend * centerness);
5723         pad_r = ImMax(pad_r, pad_extend * centerness);
5724     }
5725 
5726     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);
5727     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);
5728     if (flags & ImGuiWindowFlags_UnsavedDocument)
5729     {
5730         ImVec2 marker_pos;
5731         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);
5732         marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
5733         if (marker_pos.x > layout_r.Min.x)
5734         {
5735             RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_Text));
5736             clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f));
5737         }
5738     }
5739     //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
5740     //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
5741     RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
5742 }
5743 
UpdateWindowParentAndRootLinks(ImGuiWindow * window,ImGuiWindowFlags flags,ImGuiWindow * parent_window)5744 void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
5745 {
5746     window->ParentWindow = parent_window;
5747     window->RootWindow = window->RootWindowPopupTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
5748     if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
5749         window->RootWindow = parent_window->RootWindow;
5750     if (parent_window && (flags & ImGuiWindowFlags_Popup))
5751         window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
5752     if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)))
5753         window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
5754     while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
5755     {
5756         IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
5757         window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
5758     }
5759 }
5760 
5761 // Push a new Dear ImGui window to add widgets to.
5762 // - 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.
5763 // - Begin/End can be called multiple times during the frame with the same window name to append content.
5764 // - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
5765 //   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.
5766 // - 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.
5767 // - 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.
Begin(const char * name,bool * p_open,ImGuiWindowFlags flags)5768 bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
5769 {
5770     ImGuiContext& g = *GImGui;
5771     const ImGuiStyle& style = g.Style;
5772     IM_ASSERT(name != NULL && name[0] != '\0');     // Window name required
5773     IM_ASSERT(g.WithinFrameScope);                  // Forgot to call ImGui::NewFrame()
5774     IM_ASSERT(g.FrameCountEnded != g.FrameCount);   // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
5775 
5776     // Find or create
5777     ImGuiWindow* window = FindWindowByName(name);
5778     const bool window_just_created = (window == NULL);
5779     if (window_just_created)
5780         window = CreateNewWindow(name, flags);
5781 
5782     // Automatically disable manual moving/resizing when NoInputs is set
5783     if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
5784         flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
5785 
5786     if (flags & ImGuiWindowFlags_NavFlattened)
5787         IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
5788 
5789     const int current_frame = g.FrameCount;
5790     const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
5791     window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
5792 
5793     // Update the Appearing flag
5794     bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1);   // Not using !WasActive because the implicit "Debug" window would always toggle off->on
5795     if (flags & ImGuiWindowFlags_Popup)
5796     {
5797         ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
5798         window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
5799         window_just_activated_by_user |= (window != popup_ref.Window);
5800     }
5801     window->Appearing = window_just_activated_by_user;
5802     if (window->Appearing)
5803         SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
5804 
5805     // Update Flags, LastFrameActive, BeginOrderXXX fields
5806     if (first_begin_of_the_frame)
5807     {
5808         window->Flags = (ImGuiWindowFlags)flags;
5809         window->LastFrameActive = current_frame;
5810         window->LastTimeActive = (float)g.Time;
5811         window->BeginOrderWithinParent = 0;
5812         window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
5813     }
5814     else
5815     {
5816         flags = window->Flags;
5817     }
5818 
5819     // 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
5820     ImGuiWindow* parent_window_in_stack = g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
5821     ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
5822     IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
5823 
5824     // We allow window memory to be compacted so recreate the base stack when needed.
5825     if (window->IDStack.Size == 0)
5826         window->IDStack.push_back(window->ID);
5827 
5828     // Add to stack
5829     // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
5830     g.CurrentWindow = window;
5831     ImGuiWindowStackData window_stack_data;
5832     window_stack_data.Window = window;
5833     window_stack_data.ParentLastItemDataBackup = g.LastItemData;
5834     window_stack_data.StackSizesOnBegin.SetToCurrentState();
5835     g.CurrentWindowStack.push_back(window_stack_data);
5836     g.CurrentWindow = NULL;
5837 
5838     if (flags & ImGuiWindowFlags_Popup)
5839     {
5840         ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
5841         popup_ref.Window = window;
5842         g.BeginPopupStack.push_back(popup_ref);
5843         window->PopupId = popup_ref.PopupId;
5844     }
5845 
5846     // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
5847     if (first_begin_of_the_frame)
5848         UpdateWindowParentAndRootLinks(window, flags, parent_window);
5849 
5850     // Process SetNextWindow***() calls
5851     // (FIXME: Consider splitting the HasXXX flags into X/Y components
5852     bool window_pos_set_by_api = false;
5853     bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
5854     if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
5855     {
5856         window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
5857         if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
5858         {
5859             // May be processed on the next frame if this is our first frame and we are measuring size
5860             // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
5861             window->SetWindowPosVal = g.NextWindowData.PosVal;
5862             window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
5863             window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
5864         }
5865         else
5866         {
5867             SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
5868         }
5869     }
5870     if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
5871     {
5872         window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
5873         window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
5874         SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
5875     }
5876     if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
5877     {
5878         if (g.NextWindowData.ScrollVal.x >= 0.0f)
5879         {
5880             window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
5881             window->ScrollTargetCenterRatio.x = 0.0f;
5882         }
5883         if (g.NextWindowData.ScrollVal.y >= 0.0f)
5884         {
5885             window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
5886             window->ScrollTargetCenterRatio.y = 0.0f;
5887         }
5888     }
5889     if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
5890         window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
5891     else if (first_begin_of_the_frame)
5892         window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
5893     if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
5894         SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
5895     if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
5896         FocusWindow(window);
5897     if (window->Appearing)
5898         SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
5899 
5900     // When reusing window again multiple times a frame, just append content (don't need to setup again)
5901     if (first_begin_of_the_frame)
5902     {
5903         // Initialize
5904         const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
5905         window->Active = true;
5906         window->HasCloseButton = (p_open != NULL);
5907         window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
5908         window->IDStack.resize(1);
5909         window->DrawList->_ResetForNewFrame();
5910         window->DC.CurrentTableIdx = -1;
5911 
5912         // Restore buffer capacity when woken from a compacted state, to avoid
5913         if (window->MemoryCompacted)
5914             GcAwakeTransientWindowBuffers(window);
5915 
5916         // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
5917         // 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.
5918         bool window_title_visible_elsewhere = false;
5919         if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0)   // Window titles visible when using CTRL+TAB
5920             window_title_visible_elsewhere = true;
5921         if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
5922         {
5923             size_t buf_len = (size_t)window->NameBufLen;
5924             window->Name = ImStrdupcpy(window->Name, &buf_len, name);
5925             window->NameBufLen = (int)buf_len;
5926         }
5927 
5928         // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
5929 
5930         // Update contents size from last frame for auto-fitting (or use explicit size)
5931         const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
5932         CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
5933         if (window->HiddenFramesCanSkipItems > 0)
5934             window->HiddenFramesCanSkipItems--;
5935         if (window->HiddenFramesCannotSkipItems > 0)
5936             window->HiddenFramesCannotSkipItems--;
5937         if (window->HiddenFramesForRenderOnly > 0)
5938             window->HiddenFramesForRenderOnly--;
5939 
5940         // Hide new windows for one frame until they calculate their size
5941         if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
5942             window->HiddenFramesCannotSkipItems = 1;
5943 
5944         // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
5945         // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
5946         if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
5947         {
5948             window->HiddenFramesCannotSkipItems = 1;
5949             if (flags & ImGuiWindowFlags_AlwaysAutoResize)
5950             {
5951                 if (!window_size_x_set_by_api)
5952                     window->Size.x = window->SizeFull.x = 0.f;
5953                 if (!window_size_y_set_by_api)
5954                     window->Size.y = window->SizeFull.y = 0.f;
5955                 window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
5956             }
5957         }
5958 
5959         // SELECT VIEWPORT
5960         // FIXME-VIEWPORT: In the docking/viewport branch, this is the point where we select the current viewport (which may affect the style)
5961         SetCurrentWindow(window);
5962 
5963         // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
5964 
5965         if (flags & ImGuiWindowFlags_ChildWindow)
5966             window->WindowBorderSize = style.ChildBorderSize;
5967         else
5968             window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
5969         window->WindowPadding = style.WindowPadding;
5970         if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)
5971             window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
5972 
5973         // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
5974         window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
5975         window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
5976 
5977         // Collapse window by double-clicking on title bar
5978         // 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
5979         if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse))
5980         {
5981             // 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.
5982             ImRect title_bar_rect = window->TitleBarRect();
5983             if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0])
5984                 window->WantCollapseToggle = true;
5985             if (window->WantCollapseToggle)
5986             {
5987                 window->Collapsed = !window->Collapsed;
5988                 MarkIniSettingsDirty(window);
5989             }
5990         }
5991         else
5992         {
5993             window->Collapsed = false;
5994         }
5995         window->WantCollapseToggle = false;
5996 
5997         // SIZE
5998 
5999         // Calculate auto-fit size, handle automatic resize
6000         const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);
6001         bool use_current_size_for_scrollbar_x = window_just_created;
6002         bool use_current_size_for_scrollbar_y = window_just_created;
6003         if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
6004         {
6005             // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
6006             if (!window_size_x_set_by_api)
6007             {
6008                 window->SizeFull.x = size_auto_fit.x;
6009                 use_current_size_for_scrollbar_x = true;
6010             }
6011             if (!window_size_y_set_by_api)
6012             {
6013                 window->SizeFull.y = size_auto_fit.y;
6014                 use_current_size_for_scrollbar_y = true;
6015             }
6016         }
6017         else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6018         {
6019             // Auto-fit may only grow window during the first few frames
6020             // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
6021             if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
6022             {
6023                 window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
6024                 use_current_size_for_scrollbar_x = true;
6025             }
6026             if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
6027             {
6028                 window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
6029                 use_current_size_for_scrollbar_y = true;
6030             }
6031             if (!window->Collapsed)
6032                 MarkIniSettingsDirty(window);
6033         }
6034 
6035         // Apply minimum/maximum window size constraints and final size
6036         window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
6037         window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
6038 
6039         // Decoration size
6040         const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
6041 
6042         // POSITION
6043 
6044         // Popup latch its initial position, will position itself when it appears next frame
6045         if (window_just_activated_by_user)
6046         {
6047             window->AutoPosLastDirection = ImGuiDir_None;
6048             if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
6049                 window->Pos = g.BeginPopupStack.back().OpenPopupPos;
6050         }
6051 
6052         // Position child window
6053         if (flags & ImGuiWindowFlags_ChildWindow)
6054         {
6055             IM_ASSERT(parent_window && parent_window->Active);
6056             window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
6057             parent_window->DC.ChildWindows.push_back(window);
6058             if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
6059                 window->Pos = parent_window->DC.CursorPos;
6060         }
6061 
6062         const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
6063         if (window_pos_with_pivot)
6064             SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
6065         else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
6066             window->Pos = FindBestWindowPosForPopup(window);
6067         else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
6068             window->Pos = FindBestWindowPosForPopup(window);
6069         else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
6070             window->Pos = FindBestWindowPosForPopup(window);
6071 
6072         // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
6073         // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
6074         ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)GetMainViewport();
6075         ImRect viewport_rect(viewport->GetMainRect());
6076         ImRect viewport_work_rect(viewport->GetWorkRect());
6077         ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
6078         ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
6079 
6080         // Clamp position/size so window stays visible within its viewport or monitor
6081         // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
6082         if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
6083             if (viewport_rect.GetWidth() > 0.0f && viewport_rect.GetHeight() > 0.0f)
6084                 ClampWindowRect(window, visibility_rect);
6085         window->Pos = ImFloor(window->Pos);
6086 
6087         // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
6088         // Large values tend to lead to variety of artifacts and are not recommended.
6089         window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
6090 
6091         // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
6092         //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
6093         //    window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
6094 
6095         // Apply window focus (new and reactivated windows are moved to front)
6096         bool want_focus = false;
6097         if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
6098         {
6099             if (flags & ImGuiWindowFlags_Popup)
6100                 want_focus = true;
6101             else if ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) == 0)
6102                 want_focus = true;
6103         }
6104 
6105         // Handle manual resize: Resize Grips, Borders, Gamepad
6106         int border_held = -1;
6107         ImU32 resize_grip_col[4] = {};
6108         const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
6109         const float resize_grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
6110         if (!window->Collapsed)
6111             if (UpdateWindowManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
6112                 use_current_size_for_scrollbar_x = use_current_size_for_scrollbar_y = true;
6113         window->ResizeBorderHeld = (signed char)border_held;
6114 
6115         // SCROLLBAR VISIBILITY
6116 
6117         // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
6118         if (!window->Collapsed)
6119         {
6120             // When reading the current size we need to read it after size constraints have been applied.
6121             // When we use InnerRect here we are intentionally reading last frame size, same for ScrollbarSizes values before we set them again.
6122             ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - decoration_up_height);
6123             ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + window->ScrollbarSizes;
6124             ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
6125             float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
6126             float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
6127             //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
6128             window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
6129             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));
6130             if (window->ScrollbarX && !window->ScrollbarY)
6131                 window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar);
6132             window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
6133         }
6134 
6135         // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
6136         // Update various regions. Variables they depends on should be set above in this function.
6137         // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
6138 
6139         // Outer rectangle
6140         // Not affected by window border size. Used by:
6141         // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
6142         // - Begin() initial clipping rect for drawing window background and borders.
6143         // - Begin() clipping whole child
6144         const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
6145         const ImRect outer_rect = window->Rect();
6146         const ImRect title_bar_rect = window->TitleBarRect();
6147         window->OuterRectClipped = outer_rect;
6148         window->OuterRectClipped.ClipWith(host_rect);
6149 
6150         // Inner rectangle
6151         // Not affected by window border size. Used by:
6152         // - InnerClipRect
6153         // - ScrollToBringRectIntoView()
6154         // - NavUpdatePageUpPageDown()
6155         // - Scrollbar()
6156         window->InnerRect.Min.x = window->Pos.x;
6157         window->InnerRect.Min.y = window->Pos.y + decoration_up_height;
6158         window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->ScrollbarSizes.x;
6159         window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->ScrollbarSizes.y;
6160 
6161         // Inner clipping rectangle.
6162         // Will extend a little bit outside the normal work region.
6163         // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
6164         // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
6165         // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
6166         // Affected by window/frame border size. Used by:
6167         // - Begin() initial clip rect
6168         float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
6169         window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
6170         window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
6171         window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
6172         window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
6173         window->InnerClipRect.ClipWithFull(host_rect);
6174 
6175         // Default item width. Make it proportional to window size if window manually resizes
6176         if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
6177             window->ItemWidthDefault = ImFloor(window->Size.x * 0.65f);
6178         else
6179             window->ItemWidthDefault = ImFloor(g.FontSize * 16.0f);
6180 
6181         // SCROLLING
6182 
6183         // Lock down maximum scrolling
6184         // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
6185         // for right/bottom aligned items without creating a scrollbar.
6186         window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
6187         window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
6188 
6189         // Apply scrolling
6190         window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
6191         window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
6192 
6193         // DRAWING
6194 
6195         // Setup draw list and outer clipping rectangle
6196         IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
6197         window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
6198         PushClipRect(host_rect.Min, host_rect.Max, false);
6199 
6200         // Draw modal window background (darkens what is behind them, all viewports)
6201         const bool dim_bg_for_modal = (flags & ImGuiWindowFlags_Modal) && window == GetTopMostPopupModal() && window->HiddenFramesCannotSkipItems <= 0;
6202         const bool dim_bg_for_window_list = g.NavWindowingTargetAnim && (window == g.NavWindowingTargetAnim->RootWindow);
6203         if (dim_bg_for_modal || dim_bg_for_window_list)
6204         {
6205             const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
6206             window->DrawList->AddRectFilled(viewport_rect.Min, viewport_rect.Max, dim_bg_col);
6207         }
6208 
6209         // Draw navigation selection/windowing rectangle background
6210         if (dim_bg_for_window_list && window == g.NavWindowingTargetAnim)
6211         {
6212             ImRect bb = window->Rect();
6213             bb.Expand(g.FontSize);
6214             if (!bb.Contains(viewport_rect)) // Avoid drawing if the window covers all the viewport anyway
6215                 window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha * 0.25f), g.Style.WindowRounding);
6216         }
6217 
6218         // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
6219         // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
6220         // 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)
6221         {
6222             bool render_decorations_in_parent = false;
6223             if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
6224             {
6225                 // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
6226                 // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
6227                 ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
6228                 bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false;
6229                 bool parent_is_empty = parent_window->DrawList->VtxBuffer.Size > 0;
6230                 if (window->DrawList->CmdBuffer.back().ElemCount == 0 && parent_is_empty && !previous_child_overlapping)
6231                     render_decorations_in_parent = true;
6232             }
6233             if (render_decorations_in_parent)
6234                 window->DrawList = parent_window->DrawList;
6235 
6236             // Handle title bar, scrollbar, resize grips and resize borders
6237             const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
6238             const bool title_bar_is_highlight = want_focus || (window_to_highlight && window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight);
6239             RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, resize_grip_count, resize_grip_col, resize_grip_draw_size);
6240 
6241             if (render_decorations_in_parent)
6242                 window->DrawList = &window->DrawListInst;
6243         }
6244 
6245         // Draw navigation selection/windowing rectangle border
6246         if (g.NavWindowingTargetAnim == window)
6247         {
6248             float rounding = ImMax(window->WindowRounding, g.Style.WindowRounding);
6249             ImRect bb = window->Rect();
6250             bb.Expand(g.FontSize);
6251             if (bb.Contains(viewport_rect)) // If a window fits the entire viewport, adjust its highlight inward
6252             {
6253                 bb.Expand(-g.FontSize - 1.0f);
6254                 rounding = window->WindowRounding;
6255             }
6256             window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), rounding, 0, 3.0f);
6257         }
6258 
6259         // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
6260 
6261         // Work rectangle.
6262         // Affected by window padding and border size. Used by:
6263         // - Columns() for right-most edge
6264         // - TreeNode(), CollapsingHeader() for right-most edge
6265         // - BeginTabBar() for right-most edge
6266         const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
6267         const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
6268         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->ScrollbarSizes.x));
6269         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 - decoration_up_height - window->ScrollbarSizes.y));
6270         window->WorkRect.Min.x = ImFloor(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
6271         window->WorkRect.Min.y = ImFloor(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
6272         window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
6273         window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
6274         window->ParentWorkRect = window->WorkRect;
6275 
6276         // [LEGACY] Content Region
6277         // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
6278         // Used by:
6279         // - Mouse wheel scrolling + many other things
6280         window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x;
6281         window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + decoration_up_height;
6282         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->ScrollbarSizes.x));
6283         window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - decoration_up_height - window->ScrollbarSizes.y));
6284 
6285         // Setup drawing context
6286         // (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.)
6287         window->DC.Indent.x = 0.0f + window->WindowPadding.x - window->Scroll.x;
6288         window->DC.GroupOffset.x = 0.0f;
6289         window->DC.ColumnsOffset.x = 0.0f;
6290         window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.Indent.x + window->DC.ColumnsOffset.x, decoration_up_height + window->WindowPadding.y - window->Scroll.y);
6291         window->DC.CursorPos = window->DC.CursorStartPos;
6292         window->DC.CursorPosPrevLine = window->DC.CursorPos;
6293         window->DC.CursorMaxPos = window->DC.CursorStartPos;
6294         window->DC.IdealMaxPos = window->DC.CursorStartPos;
6295         window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
6296         window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
6297 
6298         window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6299         window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
6300         window->DC.NavLayersActiveMaskNext = 0x00;
6301         window->DC.NavHideHighlightOneFrame = false;
6302         window->DC.NavHasScroll = (window->ScrollMax.y > 0.0f);
6303 
6304         window->DC.MenuBarAppending = false;
6305         window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user);
6306         window->DC.TreeDepth = 0;
6307         window->DC.TreeJumpToParentOnPopMask = 0x00;
6308         window->DC.ChildWindows.resize(0);
6309         window->DC.StateStorage = &window->StateStorage;
6310         window->DC.CurrentColumns = NULL;
6311         window->DC.LayoutType = ImGuiLayoutType_Vertical;
6312         window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
6313         window->DC.FocusCounterTabStop = -1;
6314 
6315         window->DC.ItemWidth = window->ItemWidthDefault;
6316         window->DC.TextWrapPos = -1.0f; // disabled
6317         window->DC.ItemWidthStack.resize(0);
6318         window->DC.TextWrapPosStack.resize(0);
6319 
6320         if (window->AutoFitFramesX > 0)
6321             window->AutoFitFramesX--;
6322         if (window->AutoFitFramesY > 0)
6323             window->AutoFitFramesY--;
6324 
6325         // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
6326         if (want_focus)
6327         {
6328             FocusWindow(window);
6329             NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
6330         }
6331 
6332         // Title bar
6333         if (!(flags & ImGuiWindowFlags_NoTitleBar))
6334             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);
6335 
6336         // Clear hit test shape every frame
6337         window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
6338 
6339         // Pressing CTRL+C while holding on a window copy its content to the clipboard
6340         // 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.
6341         // Maybe we can support CTRL+C on every element?
6342         /*
6343         //if (g.NavWindow == window && g.ActiveId == 0)
6344         if (g.ActiveId == window->MoveId)
6345             if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C))
6346                 LogToClipboard();
6347         */
6348 
6349         // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
6350         // This is useful to allow creating context menus on title bar only, etc.
6351         g.LastItemData.ID = window->MoveId;
6352         g.LastItemData.InFlags = g.CurrentItemFlags;
6353         g.LastItemData.StatusFlags = IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0;
6354         g.LastItemData.Rect = title_bar_rect;
6355 
6356 #ifdef IMGUI_ENABLE_TEST_ENGINE
6357         if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
6358             IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.Rect, g.LastItemData.ID);
6359 #endif
6360     }
6361     else
6362     {
6363         // Append
6364         SetCurrentWindow(window);
6365     }
6366 
6367     // Pull/inherit current state
6368     window->DC.NavFocusScopeIdCurrent = (flags & ImGuiWindowFlags_ChildWindow) ? parent_window->DC.NavFocusScopeIdCurrent : window->GetID("#FOCUSSCOPE"); // Inherit from parent only // -V595
6369 
6370     PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
6371 
6372     // 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)
6373     window->WriteAccessed = false;
6374     window->BeginCount++;
6375     g.NextWindowData.ClearFlags();
6376 
6377     // Update visibility
6378     if (first_begin_of_the_frame)
6379     {
6380         if (flags & ImGuiWindowFlags_ChildWindow)
6381         {
6382             // Child window can be out of sight and have "negative" clip windows.
6383             // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
6384             IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0);
6385             if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) // FIXME: Doesn't make sense for ChildWindow??
6386                 if (!g.LogEnabled)
6387                     if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
6388                         window->HiddenFramesCanSkipItems = 1;
6389 
6390             // Hide along with parent or if parent is collapsed
6391             if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
6392                 window->HiddenFramesCanSkipItems = 1;
6393             if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
6394                 window->HiddenFramesCannotSkipItems = 1;
6395         }
6396 
6397         // 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)
6398         if (style.Alpha <= 0.0f)
6399             window->HiddenFramesCanSkipItems = 1;
6400 
6401         // Update the Hidden flag
6402         window->Hidden = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0) || (window->HiddenFramesForRenderOnly > 0);
6403 
6404         // Disable inputs for requested number of frames
6405         if (window->DisableInputsFrames > 0)
6406         {
6407             window->DisableInputsFrames--;
6408             window->Flags |= ImGuiWindowFlags_NoInputs;
6409         }
6410 
6411         // Update the SkipItems flag, used to early out of all items functions (no layout required)
6412         bool skip_items = false;
6413         if (window->Collapsed || !window->Active || window->Hidden)
6414             if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
6415                 skip_items = true;
6416         window->SkipItems = skip_items;
6417     }
6418 
6419     return !window->SkipItems;
6420 }
6421 
End()6422 void ImGui::End()
6423 {
6424     ImGuiContext& g = *GImGui;
6425     ImGuiWindow* window = g.CurrentWindow;
6426 
6427     // Error checking: verify that user hasn't called End() too many times!
6428     if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
6429     {
6430         IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
6431         return;
6432     }
6433     IM_ASSERT(g.CurrentWindowStack.Size > 0);
6434 
6435     // Error checking: verify that user doesn't directly call End() on a child window.
6436     if (window->Flags & ImGuiWindowFlags_ChildWindow)
6437         IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
6438 
6439     // Close anything that is open
6440     if (window->DC.CurrentColumns)
6441         EndColumns();
6442     PopClipRect();   // Inner window clip rectangle
6443 
6444     // Stop logging
6445     if (!(window->Flags & ImGuiWindowFlags_ChildWindow))    // FIXME: add more options for scope of logging
6446         LogFinish();
6447 
6448     // Pop from window stack
6449     g.LastItemData = g.CurrentWindowStack.back().ParentLastItemDataBackup;
6450     if (window->Flags & ImGuiWindowFlags_Popup)
6451         g.BeginPopupStack.pop_back();
6452     g.CurrentWindowStack.back().StackSizesOnBegin.CompareWithCurrentState();
6453     g.CurrentWindowStack.pop_back();
6454     SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
6455 }
6456 
BringWindowToFocusFront(ImGuiWindow * window)6457 void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
6458 {
6459     ImGuiContext& g = *GImGui;
6460     IM_ASSERT(window == window->RootWindow);
6461 
6462     const int cur_order = window->FocusOrder;
6463     IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
6464     if (g.WindowsFocusOrder.back() == window)
6465         return;
6466 
6467     const int new_order = g.WindowsFocusOrder.Size - 1;
6468     for (int n = cur_order; n < new_order; n++)
6469     {
6470         g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
6471         g.WindowsFocusOrder[n]->FocusOrder--;
6472         IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
6473     }
6474     g.WindowsFocusOrder[new_order] = window;
6475     window->FocusOrder = (short)new_order;
6476 }
6477 
BringWindowToDisplayFront(ImGuiWindow * window)6478 void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
6479 {
6480     ImGuiContext& g = *GImGui;
6481     ImGuiWindow* current_front_window = g.Windows.back();
6482     if (current_front_window == window || current_front_window->RootWindow == window) // Cheap early out (could be better)
6483         return;
6484     for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
6485         if (g.Windows[i] == window)
6486         {
6487             memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
6488             g.Windows[g.Windows.Size - 1] = window;
6489             break;
6490         }
6491 }
6492 
BringWindowToDisplayBack(ImGuiWindow * window)6493 void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
6494 {
6495     ImGuiContext& g = *GImGui;
6496     if (g.Windows[0] == window)
6497         return;
6498     for (int i = 0; i < g.Windows.Size; i++)
6499         if (g.Windows[i] == window)
6500         {
6501             memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
6502             g.Windows[0] = window;
6503             break;
6504         }
6505 }
6506 
6507 // Moving window to front of display and set focus (which happens to be back of our sorted list)
FocusWindow(ImGuiWindow * window)6508 void ImGui::FocusWindow(ImGuiWindow* window)
6509 {
6510     ImGuiContext& g = *GImGui;
6511 
6512     if (g.NavWindow != window)
6513     {
6514         g.NavWindow = window;
6515         if (window && g.NavDisableMouseHover)
6516             g.NavMousePosDirty = true;
6517         g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
6518         g.NavFocusScopeId = 0;
6519         g.NavIdIsAlive = false;
6520         g.NavLayer = ImGuiNavLayer_Main;
6521         g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
6522         NavUpdateAnyRequestFlag();
6523         //IMGUI_DEBUG_LOG("FocusWindow(\"%s\")\n", window ? window->Name : NULL);
6524     }
6525 
6526     // Close popups if any
6527     ClosePopupsOverWindow(window, false);
6528 
6529     // Move the root window to the top of the pile
6530     IM_ASSERT(window == NULL || window->RootWindow != NULL);
6531     ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL; // NB: In docking branch this is window->RootWindowDockStop
6532     ImGuiWindow* display_front_window = window ? window->RootWindow : NULL;
6533 
6534     // Steal active widgets. Some of the cases it triggers includes:
6535     // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
6536     // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
6537     if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
6538         if (!g.ActiveIdNoClearOnFocusLoss)
6539             ClearActiveID();
6540 
6541     // Passing NULL allow to disable keyboard focus
6542     if (!window)
6543         return;
6544 
6545     // Bring to front
6546     BringWindowToFocusFront(focus_front_window);
6547     if (((window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
6548         BringWindowToDisplayFront(display_front_window);
6549 }
6550 
FocusTopMostWindowUnderOne(ImGuiWindow * under_this_window,ImGuiWindow * ignore_window)6551 void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window)
6552 {
6553     ImGuiContext& g = *GImGui;
6554     int start_idx = g.WindowsFocusOrder.Size - 1;
6555     if (under_this_window != NULL)
6556     {
6557         // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
6558         int offset = -1;
6559         while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
6560         {
6561             under_this_window = under_this_window->ParentWindow;
6562             offset = 0;
6563         }
6564         start_idx = FindWindowFocusIndex(under_this_window) + offset;
6565     }
6566     for (int i = start_idx; i >= 0; i--)
6567     {
6568         // 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.
6569         ImGuiWindow* window = g.WindowsFocusOrder[i];
6570         IM_ASSERT(window == window->RootWindow);
6571         if (window != ignore_window && window->WasActive)
6572             if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
6573             {
6574                 ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(window);
6575                 FocusWindow(focus_window);
6576                 return;
6577             }
6578     }
6579     FocusWindow(NULL);
6580 }
6581 
6582 // Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.
SetCurrentFont(ImFont * font)6583 void ImGui::SetCurrentFont(ImFont* font)
6584 {
6585     ImGuiContext& g = *GImGui;
6586     IM_ASSERT(font && font->IsLoaded());    // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
6587     IM_ASSERT(font->Scale > 0.0f);
6588     g.Font = font;
6589     g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
6590     g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
6591 
6592     ImFontAtlas* atlas = g.Font->ContainerAtlas;
6593     g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
6594     g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
6595     g.DrawListSharedData.Font = g.Font;
6596     g.DrawListSharedData.FontSize = g.FontSize;
6597 }
6598 
PushFont(ImFont * font)6599 void ImGui::PushFont(ImFont* font)
6600 {
6601     ImGuiContext& g = *GImGui;
6602     if (!font)
6603         font = GetDefaultFont();
6604     SetCurrentFont(font);
6605     g.FontStack.push_back(font);
6606     g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
6607 }
6608 
PopFont()6609 void  ImGui::PopFont()
6610 {
6611     ImGuiContext& g = *GImGui;
6612     g.CurrentWindow->DrawList->PopTextureID();
6613     g.FontStack.pop_back();
6614     SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
6615 }
6616 
PushItemFlag(ImGuiItemFlags option,bool enabled)6617 void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
6618 {
6619     ImGuiContext& g = *GImGui;
6620     ImGuiItemFlags item_flags = g.CurrentItemFlags;
6621     IM_ASSERT(item_flags == g.ItemFlagsStack.back());
6622     if (enabled)
6623         item_flags |= option;
6624     else
6625         item_flags &= ~option;
6626     g.CurrentItemFlags = item_flags;
6627     g.ItemFlagsStack.push_back(item_flags);
6628 }
6629 
PopItemFlag()6630 void ImGui::PopItemFlag()
6631 {
6632     ImGuiContext& g = *GImGui;
6633     IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.
6634     g.ItemFlagsStack.pop_back();
6635     g.CurrentItemFlags = g.ItemFlagsStack.back();
6636 }
6637 
6638 // BeginDisabled()/EndDisabled()
6639 // - 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)
6640 // - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
6641 // - Feedback welcome at https://github.com/ocornut/imgui/issues/211
6642 // - 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.
6643 // - Optimized shortcuts instead of PushStyleVar() + PushItemFlag()
BeginDisabled(bool disabled)6644 void ImGui::BeginDisabled(bool disabled)
6645 {
6646     ImGuiContext& g = *GImGui;
6647     bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
6648     if (!was_disabled && disabled)
6649     {
6650         g.DisabledAlphaBackup = g.Style.Alpha;
6651         g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
6652     }
6653     if (was_disabled || disabled)
6654         g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
6655     g.ItemFlagsStack.push_back(g.CurrentItemFlags);
6656     g.DisabledStackSize++;
6657 }
6658 
EndDisabled()6659 void ImGui::EndDisabled()
6660 {
6661     ImGuiContext& g = *GImGui;
6662     IM_ASSERT(g.DisabledStackSize > 0);
6663     g.DisabledStackSize--;
6664     bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
6665     //PopItemFlag();
6666     g.ItemFlagsStack.pop_back();
6667     g.CurrentItemFlags = g.ItemFlagsStack.back();
6668     if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
6669         g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
6670 }
6671 
6672 // FIXME: Look into renaming this once we have settled the new Focus/Activation/TabStop system.
PushAllowKeyboardFocus(bool allow_keyboard_focus)6673 void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus)
6674 {
6675     PushItemFlag(ImGuiItemFlags_NoTabStop, !allow_keyboard_focus);
6676 }
6677 
PopAllowKeyboardFocus()6678 void ImGui::PopAllowKeyboardFocus()
6679 {
6680     PopItemFlag();
6681 }
6682 
PushButtonRepeat(bool repeat)6683 void ImGui::PushButtonRepeat(bool repeat)
6684 {
6685     PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
6686 }
6687 
PopButtonRepeat()6688 void ImGui::PopButtonRepeat()
6689 {
6690     PopItemFlag();
6691 }
6692 
PushTextWrapPos(float wrap_pos_x)6693 void ImGui::PushTextWrapPos(float wrap_pos_x)
6694 {
6695     ImGuiWindow* window = GetCurrentWindow();
6696     window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
6697     window->DC.TextWrapPos = wrap_pos_x;
6698 }
6699 
PopTextWrapPos()6700 void ImGui::PopTextWrapPos()
6701 {
6702     ImGuiWindow* window = GetCurrentWindow();
6703     window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
6704     window->DC.TextWrapPosStack.pop_back();
6705 }
6706 
GetCombinedRootWindow(ImGuiWindow * window,bool popup_hierarchy)6707 static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy)
6708 {
6709     window = window->RootWindow;
6710     if (popup_hierarchy)
6711         window = window->RootWindowPopupTree;
6712     return window;
6713 }
6714 
IsWindowChildOf(ImGuiWindow * window,ImGuiWindow * potential_parent,bool popup_hierarchy)6715 bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy)
6716 {
6717     ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy);
6718     if (window_root == potential_parent)
6719         return true;
6720     while (window != NULL)
6721     {
6722         if (window == potential_parent)
6723             return true;
6724         if (window == window_root) // end of chain
6725             return false;
6726         window = window->ParentWindow;
6727     }
6728     return false;
6729 }
6730 
IsWindowAbove(ImGuiWindow * potential_above,ImGuiWindow * potential_below)6731 bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
6732 {
6733     ImGuiContext& g = *GImGui;
6734     for (int i = g.Windows.Size - 1; i >= 0; i--)
6735     {
6736         ImGuiWindow* candidate_window = g.Windows[i];
6737         if (candidate_window == potential_above)
6738             return true;
6739         if (candidate_window == potential_below)
6740             return false;
6741     }
6742     return false;
6743 }
6744 
IsWindowHovered(ImGuiHoveredFlags flags)6745 bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
6746 {
6747     IM_ASSERT((flags & (ImGuiHoveredFlags_AllowWhenOverlapped | ImGuiHoveredFlags_AllowWhenDisabled)) == 0);   // Flags not supported by this function
6748     ImGuiContext& g = *GImGui;
6749     ImGuiWindow* ref_window = g.HoveredWindow;
6750     ImGuiWindow* cur_window = g.CurrentWindow;
6751     if (ref_window == NULL)
6752         return false;
6753 
6754     if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
6755     {
6756         IM_ASSERT(cur_window); // Not inside a Begin()/End()
6757         const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
6758         if (flags & ImGuiHoveredFlags_RootWindow)
6759             cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy);
6760 
6761         bool result;
6762         if (flags & ImGuiHoveredFlags_ChildWindows)
6763             result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy);
6764         else
6765             result = (ref_window == cur_window);
6766         if (!result)
6767             return false;
6768     }
6769 
6770     if (!IsWindowContentHoverable(ref_window, flags))
6771         return false;
6772     if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
6773         if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
6774             return false;
6775     return true;
6776 }
6777 
IsWindowFocused(ImGuiFocusedFlags flags)6778 bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
6779 {
6780     ImGuiContext& g = *GImGui;
6781     ImGuiWindow* ref_window = g.NavWindow;
6782     ImGuiWindow* cur_window = g.CurrentWindow;
6783 
6784     if (ref_window == NULL)
6785         return false;
6786     if (flags & ImGuiFocusedFlags_AnyWindow)
6787         return true;
6788     IM_ASSERT(cur_window); // Not inside a Begin()/End()
6789 
6790     const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
6791     if (flags & ImGuiHoveredFlags_RootWindow)
6792         cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy);
6793 
6794     if (flags & ImGuiHoveredFlags_ChildWindows)
6795         return IsWindowChildOf(ref_window, cur_window, popup_hierarchy);
6796     else
6797         return (ref_window == cur_window);
6798 }
6799 
6800 // Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
6801 // Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
6802 // If you want a window to never be focused, you may use the e.g. NoInputs flag.
IsWindowNavFocusable(ImGuiWindow * window)6803 bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
6804 {
6805     return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
6806 }
6807 
GetWindowWidth()6808 float ImGui::GetWindowWidth()
6809 {
6810     ImGuiWindow* window = GImGui->CurrentWindow;
6811     return window->Size.x;
6812 }
6813 
GetWindowHeight()6814 float ImGui::GetWindowHeight()
6815 {
6816     ImGuiWindow* window = GImGui->CurrentWindow;
6817     return window->Size.y;
6818 }
6819 
GetWindowPos()6820 ImVec2 ImGui::GetWindowPos()
6821 {
6822     ImGuiContext& g = *GImGui;
6823     ImGuiWindow* window = g.CurrentWindow;
6824     return window->Pos;
6825 }
6826 
SetWindowPos(ImGuiWindow * window,const ImVec2 & pos,ImGuiCond cond)6827 void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
6828 {
6829     // Test condition (NB: bit 0 is always true) and clear flags for next time
6830     if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
6831         return;
6832 
6833     IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
6834     window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
6835     window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
6836 
6837     // Set
6838     const ImVec2 old_pos = window->Pos;
6839     window->Pos = ImFloor(pos);
6840     ImVec2 offset = window->Pos - old_pos;
6841     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
6842     window->DC.CursorMaxPos += offset;      // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
6843     window->DC.IdealMaxPos += offset;
6844     window->DC.CursorStartPos += offset;
6845 }
6846 
SetWindowPos(const ImVec2 & pos,ImGuiCond cond)6847 void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
6848 {
6849     ImGuiWindow* window = GetCurrentWindowRead();
6850     SetWindowPos(window, pos, cond);
6851 }
6852 
SetWindowPos(const char * name,const ImVec2 & pos,ImGuiCond cond)6853 void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
6854 {
6855     if (ImGuiWindow* window = FindWindowByName(name))
6856         SetWindowPos(window, pos, cond);
6857 }
6858 
GetWindowSize()6859 ImVec2 ImGui::GetWindowSize()
6860 {
6861     ImGuiWindow* window = GetCurrentWindowRead();
6862     return window->Size;
6863 }
6864 
SetWindowSize(ImGuiWindow * window,const ImVec2 & size,ImGuiCond cond)6865 void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
6866 {
6867     // Test condition (NB: bit 0 is always true) and clear flags for next time
6868     if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
6869         return;
6870 
6871     IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
6872     window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
6873 
6874     // Set
6875     if (size.x > 0.0f)
6876     {
6877         window->AutoFitFramesX = 0;
6878         window->SizeFull.x = IM_FLOOR(size.x);
6879     }
6880     else
6881     {
6882         window->AutoFitFramesX = 2;
6883         window->AutoFitOnlyGrows = false;
6884     }
6885     if (size.y > 0.0f)
6886     {
6887         window->AutoFitFramesY = 0;
6888         window->SizeFull.y = IM_FLOOR(size.y);
6889     }
6890     else
6891     {
6892         window->AutoFitFramesY = 2;
6893         window->AutoFitOnlyGrows = false;
6894     }
6895 }
6896 
SetWindowSize(const ImVec2 & size,ImGuiCond cond)6897 void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
6898 {
6899     SetWindowSize(GImGui->CurrentWindow, size, cond);
6900 }
6901 
SetWindowSize(const char * name,const ImVec2 & size,ImGuiCond cond)6902 void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
6903 {
6904     if (ImGuiWindow* window = FindWindowByName(name))
6905         SetWindowSize(window, size, cond);
6906 }
6907 
SetWindowCollapsed(ImGuiWindow * window,bool collapsed,ImGuiCond cond)6908 void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
6909 {
6910     // Test condition (NB: bit 0 is always true) and clear flags for next time
6911     if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
6912         return;
6913     window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
6914 
6915     // Set
6916     window->Collapsed = collapsed;
6917 }
6918 
SetWindowHitTestHole(ImGuiWindow * window,const ImVec2 & pos,const ImVec2 & size)6919 void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
6920 {
6921     IM_ASSERT(window->HitTestHoleSize.x == 0);     // We don't support multiple holes/hit test filters
6922     window->HitTestHoleSize = ImVec2ih(size);
6923     window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
6924 }
6925 
SetWindowCollapsed(bool collapsed,ImGuiCond cond)6926 void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
6927 {
6928     SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
6929 }
6930 
IsWindowCollapsed()6931 bool ImGui::IsWindowCollapsed()
6932 {
6933     ImGuiWindow* window = GetCurrentWindowRead();
6934     return window->Collapsed;
6935 }
6936 
IsWindowAppearing()6937 bool ImGui::IsWindowAppearing()
6938 {
6939     ImGuiWindow* window = GetCurrentWindowRead();
6940     return window->Appearing;
6941 }
6942 
SetWindowCollapsed(const char * name,bool collapsed,ImGuiCond cond)6943 void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
6944 {
6945     if (ImGuiWindow* window = FindWindowByName(name))
6946         SetWindowCollapsed(window, collapsed, cond);
6947 }
6948 
SetWindowFocus()6949 void ImGui::SetWindowFocus()
6950 {
6951     FocusWindow(GImGui->CurrentWindow);
6952 }
6953 
SetWindowFocus(const char * name)6954 void ImGui::SetWindowFocus(const char* name)
6955 {
6956     if (name)
6957     {
6958         if (ImGuiWindow* window = FindWindowByName(name))
6959             FocusWindow(window);
6960     }
6961     else
6962     {
6963         FocusWindow(NULL);
6964     }
6965 }
6966 
SetNextWindowPos(const ImVec2 & pos,ImGuiCond cond,const ImVec2 & pivot)6967 void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
6968 {
6969     ImGuiContext& g = *GImGui;
6970     IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
6971     g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
6972     g.NextWindowData.PosVal = pos;
6973     g.NextWindowData.PosPivotVal = pivot;
6974     g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
6975 }
6976 
SetNextWindowSize(const ImVec2 & size,ImGuiCond cond)6977 void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
6978 {
6979     ImGuiContext& g = *GImGui;
6980     IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
6981     g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
6982     g.NextWindowData.SizeVal = size;
6983     g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
6984 }
6985 
SetNextWindowSizeConstraints(const ImVec2 & size_min,const ImVec2 & size_max,ImGuiSizeCallback custom_callback,void * custom_callback_user_data)6986 void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
6987 {
6988     ImGuiContext& g = *GImGui;
6989     g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
6990     g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
6991     g.NextWindowData.SizeCallback = custom_callback;
6992     g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
6993 }
6994 
6995 // Content size = inner scrollable rectangle, padded with WindowPadding.
6996 // SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
SetNextWindowContentSize(const ImVec2 & size)6997 void ImGui::SetNextWindowContentSize(const ImVec2& size)
6998 {
6999     ImGuiContext& g = *GImGui;
7000     g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
7001     g.NextWindowData.ContentSizeVal = ImFloor(size);
7002 }
7003 
SetNextWindowScroll(const ImVec2 & scroll)7004 void ImGui::SetNextWindowScroll(const ImVec2& scroll)
7005 {
7006     ImGuiContext& g = *GImGui;
7007     g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
7008     g.NextWindowData.ScrollVal = scroll;
7009 }
7010 
SetNextWindowCollapsed(bool collapsed,ImGuiCond cond)7011 void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
7012 {
7013     ImGuiContext& g = *GImGui;
7014     IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7015     g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
7016     g.NextWindowData.CollapsedVal = collapsed;
7017     g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
7018 }
7019 
SetNextWindowFocus()7020 void ImGui::SetNextWindowFocus()
7021 {
7022     ImGuiContext& g = *GImGui;
7023     g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
7024 }
7025 
SetNextWindowBgAlpha(float alpha)7026 void ImGui::SetNextWindowBgAlpha(float alpha)
7027 {
7028     ImGuiContext& g = *GImGui;
7029     g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
7030     g.NextWindowData.BgAlphaVal = alpha;
7031 }
7032 
GetWindowDrawList()7033 ImDrawList* ImGui::GetWindowDrawList()
7034 {
7035     ImGuiWindow* window = GetCurrentWindow();
7036     return window->DrawList;
7037 }
7038 
GetFont()7039 ImFont* ImGui::GetFont()
7040 {
7041     return GImGui->Font;
7042 }
7043 
GetFontSize()7044 float ImGui::GetFontSize()
7045 {
7046     return GImGui->FontSize;
7047 }
7048 
GetFontTexUvWhitePixel()7049 ImVec2 ImGui::GetFontTexUvWhitePixel()
7050 {
7051     return GImGui->DrawListSharedData.TexUvWhitePixel;
7052 }
7053 
SetWindowFontScale(float scale)7054 void ImGui::SetWindowFontScale(float scale)
7055 {
7056     IM_ASSERT(scale > 0.0f);
7057     ImGuiContext& g = *GImGui;
7058     ImGuiWindow* window = GetCurrentWindow();
7059     window->FontWindowScale = scale;
7060     g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
7061 }
7062 
ActivateItem(ImGuiID id)7063 void ImGui::ActivateItem(ImGuiID id)
7064 {
7065     ImGuiContext& g = *GImGui;
7066     g.NavNextActivateId = id;
7067     g.NavNextActivateFlags = ImGuiActivateFlags_None;
7068 }
7069 
PushFocusScope(ImGuiID id)7070 void ImGui::PushFocusScope(ImGuiID id)
7071 {
7072     ImGuiContext& g = *GImGui;
7073     ImGuiWindow* window = g.CurrentWindow;
7074     g.FocusScopeStack.push_back(window->DC.NavFocusScopeIdCurrent);
7075     window->DC.NavFocusScopeIdCurrent = id;
7076 }
7077 
PopFocusScope()7078 void ImGui::PopFocusScope()
7079 {
7080     ImGuiContext& g = *GImGui;
7081     ImGuiWindow* window = g.CurrentWindow;
7082     IM_ASSERT(g.FocusScopeStack.Size > 0); // Too many PopFocusScope() ?
7083     window->DC.NavFocusScopeIdCurrent = g.FocusScopeStack.back();
7084     g.FocusScopeStack.pop_back();
7085 }
7086 
SetKeyboardFocusHere(int offset)7087 void ImGui::SetKeyboardFocusHere(int offset)
7088 {
7089     ImGuiContext& g = *GImGui;
7090     ImGuiWindow* window = g.CurrentWindow;
7091     IM_ASSERT(offset >= -1);    // -1 is allowed but not below
7092     g.NavWindow = window;
7093     ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
7094     NavMoveRequestSubmit(ImGuiDir_None, ImGuiDir_None, ImGuiNavMoveFlags_Tabbing, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
7095     if (offset == -1)
7096         NavMoveRequestResolveWithLastItem();
7097     else
7098         g.NavTabbingInputableRemaining = offset + 1;
7099 }
7100 
SetItemDefaultFocus()7101 void ImGui::SetItemDefaultFocus()
7102 {
7103     ImGuiContext& g = *GImGui;
7104     ImGuiWindow* window = g.CurrentWindow;
7105     if (!window->Appearing)
7106         return;
7107     if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResultId == 0) || g.NavLayer != window->DC.NavLayerCurrent)
7108         return;
7109 
7110     g.NavInitRequest = false;
7111     g.NavInitResultId = g.LastItemData.ID;
7112     g.NavInitResultRectRel = ImRect(g.LastItemData.Rect.Min - window->Pos, g.LastItemData.Rect.Max - window->Pos);
7113     NavUpdateAnyRequestFlag();
7114 
7115     // Scroll could be done in NavInitRequestApplyResult() via a opt-in flag (we however don't want regular init requests to scroll)
7116     if (!IsItemVisible())
7117         ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None);
7118 }
7119 
SetStateStorage(ImGuiStorage * tree)7120 void ImGui::SetStateStorage(ImGuiStorage* tree)
7121 {
7122     ImGuiWindow* window = GImGui->CurrentWindow;
7123     window->DC.StateStorage = tree ? tree : &window->StateStorage;
7124 }
7125 
GetStateStorage()7126 ImGuiStorage* ImGui::GetStateStorage()
7127 {
7128     ImGuiWindow* window = GImGui->CurrentWindow;
7129     return window->DC.StateStorage;
7130 }
7131 
PushID(const char * str_id)7132 void ImGui::PushID(const char* str_id)
7133 {
7134     ImGuiContext& g = *GImGui;
7135     ImGuiWindow* window = g.CurrentWindow;
7136     ImGuiID id = window->GetIDNoKeepAlive(str_id);
7137     window->IDStack.push_back(id);
7138 }
7139 
PushID(const char * str_id_begin,const char * str_id_end)7140 void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
7141 {
7142     ImGuiContext& g = *GImGui;
7143     ImGuiWindow* window = g.CurrentWindow;
7144     ImGuiID id = window->GetIDNoKeepAlive(str_id_begin, str_id_end);
7145     window->IDStack.push_back(id);
7146 }
7147 
PushID(const void * ptr_id)7148 void ImGui::PushID(const void* ptr_id)
7149 {
7150     ImGuiContext& g = *GImGui;
7151     ImGuiWindow* window = g.CurrentWindow;
7152     ImGuiID id = window->GetIDNoKeepAlive(ptr_id);
7153     window->IDStack.push_back(id);
7154 }
7155 
PushID(int int_id)7156 void ImGui::PushID(int int_id)
7157 {
7158     ImGuiContext& g = *GImGui;
7159     ImGuiWindow* window = g.CurrentWindow;
7160     ImGuiID id = window->GetIDNoKeepAlive(int_id);
7161     window->IDStack.push_back(id);
7162 }
7163 
7164 // Push a given id value ignoring the ID stack as a seed.
PushOverrideID(ImGuiID id)7165 void ImGui::PushOverrideID(ImGuiID id)
7166 {
7167     ImGuiContext& g = *GImGui;
7168     ImGuiWindow* window = g.CurrentWindow;
7169     if (g.DebugHookIdInfo == id)
7170         DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL);
7171     window->IDStack.push_back(id);
7172 }
7173 
7174 // Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
7175 // (note that when using this pattern, TestEngine's "Stack Tool" will tend to not display the intermediate stack level.
7176 //  for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
GetIDWithSeed(const char * str,const char * str_end,ImGuiID seed)7177 ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
7178 {
7179     ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
7180     KeepAliveID(id);
7181     ImGuiContext& g = *GImGui;
7182     if (g.DebugHookIdInfo == id)
7183         DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
7184     return id;
7185 }
7186 
PopID()7187 void ImGui::PopID()
7188 {
7189     ImGuiWindow* window = GImGui->CurrentWindow;
7190     IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?
7191     window->IDStack.pop_back();
7192 }
7193 
GetID(const char * str_id)7194 ImGuiID ImGui::GetID(const char* str_id)
7195 {
7196     ImGuiWindow* window = GImGui->CurrentWindow;
7197     return window->GetID(str_id);
7198 }
7199 
GetID(const char * str_id_begin,const char * str_id_end)7200 ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
7201 {
7202     ImGuiWindow* window = GImGui->CurrentWindow;
7203     return window->GetID(str_id_begin, str_id_end);
7204 }
7205 
GetID(const void * ptr_id)7206 ImGuiID ImGui::GetID(const void* ptr_id)
7207 {
7208     ImGuiWindow* window = GImGui->CurrentWindow;
7209     return window->GetID(ptr_id);
7210 }
7211 
IsRectVisible(const ImVec2 & size)7212 bool ImGui::IsRectVisible(const ImVec2& size)
7213 {
7214     ImGuiWindow* window = GImGui->CurrentWindow;
7215     return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
7216 }
7217 
IsRectVisible(const ImVec2 & rect_min,const ImVec2 & rect_max)7218 bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
7219 {
7220     ImGuiWindow* window = GImGui->CurrentWindow;
7221     return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
7222 }
7223 
7224 
7225 //-----------------------------------------------------------------------------
7226 // [SECTION] ERROR CHECKING
7227 //-----------------------------------------------------------------------------
7228 
7229 // Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
7230 // Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
7231 // If the user has inconsistent compilation settings, imgui configuration #define, packing pragma, etc. your user code
7232 // may see different structures than what imgui.cpp sees, which is problematic.
7233 // We usually require settings to be in imconfig.h to make sure that they are accessible to all compilation units involved with Dear 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)7234 bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
7235 {
7236     bool error = false;
7237     if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
7238     if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
7239     if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
7240     if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
7241     if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
7242     if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
7243     if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
7244     return !error;
7245 }
7246 
ErrorCheckNewFrameSanityChecks()7247 static void ImGui::ErrorCheckNewFrameSanityChecks()
7248 {
7249     ImGuiContext& g = *GImGui;
7250 
7251     // Check user IM_ASSERT macro
7252     // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
7253     //  If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
7254     //  This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
7255     // #define IM_ASSERT(EXPR)   if (SomeCode(EXPR)) SomeMoreCode();                    // Wrong!
7256     // #define IM_ASSERT(EXPR)   do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0)   // Correct!
7257     if (true) IM_ASSERT(1); else IM_ASSERT(0);
7258 
7259     // Check user data
7260     // (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)
7261     IM_ASSERT(g.Initialized);
7262     IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0)              && "Need a positive DeltaTime!");
7263     IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount)  && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
7264     IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f  && "Invalid DisplaySize value!");
7265     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()");
7266     IM_ASSERT(g.Style.CurveTessellationTol > 0.0f                       && "Invalid style setting!");
7267     IM_ASSERT(g.Style.CircleTessellationMaxError  > 0.0f                && "Invalid style setting!");
7268     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
7269     IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
7270     IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
7271     for (int n = 0; n < ImGuiKey_COUNT; n++)
7272         IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < IM_ARRAYSIZE(g.IO.KeysDown) && "io.KeyMap[] contains an out of bound value (need to be 0..512, or -1 for unmapped key)");
7273 
7274     // 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)
7275     if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard)
7276         IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
7277 
7278     // Check: the io.ConfigWindowsResizeFromEdges option requires backend to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
7279     if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
7280         g.IO.ConfigWindowsResizeFromEdges = false;
7281 }
7282 
ErrorCheckEndFrameSanityChecks()7283 static void ImGui::ErrorCheckEndFrameSanityChecks()
7284 {
7285     ImGuiContext& g = *GImGui;
7286 
7287     // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
7288     // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
7289     // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
7290     // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
7291     // We silently accommodate for this case by ignoring/ the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
7292     // while still correctly asserting on mid-frame key press events.
7293     const ImGuiKeyModFlags key_mod_flags = GetMergedKeyModFlags();
7294     IM_ASSERT((key_mod_flags == 0 || g.IO.KeyMods == key_mod_flags) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
7295     IM_UNUSED(key_mod_flags);
7296 
7297     // Recover from errors
7298     //ErrorCheckEndFrameRecover();
7299 
7300     // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
7301     // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
7302     if (g.CurrentWindowStack.Size != 1)
7303     {
7304         if (g.CurrentWindowStack.Size > 1)
7305         {
7306             IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
7307             while (g.CurrentWindowStack.Size > 1)
7308                 End();
7309         }
7310         else
7311         {
7312             IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
7313         }
7314     }
7315 
7316     IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
7317 }
7318 
7319 // Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
7320 // Must be called during or before EndFrame().
7321 // This is generally flawed as we are not necessarily End/Popping things in the right order.
7322 // FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
7323 // FIXME: Can't recover from interleaved BeginTabBar/Begin
ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback,void * user_data)7324 void    ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
7325 {
7326     // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
7327     ImGuiContext& g = *GImGui;
7328     while (g.CurrentWindowStack.Size > 0) //-V1044
7329     {
7330         ErrorCheckEndWindowRecover(log_callback, user_data);
7331         ImGuiWindow* window = g.CurrentWindow;
7332         if (g.CurrentWindowStack.Size == 1)
7333         {
7334             IM_ASSERT(window->IsFallbackWindow);
7335             break;
7336         }
7337         IM_ASSERT(window == g.CurrentWindow);
7338         if (window->Flags & ImGuiWindowFlags_ChildWindow)
7339         {
7340             if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name);
7341             EndChild();
7342         }
7343         else
7344         {
7345             if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name);
7346             End();
7347         }
7348     }
7349 }
7350 
7351 // Must be called before End()/EndChild()
ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback,void * user_data)7352 void    ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data)
7353 {
7354     ImGuiContext& g = *GImGui;
7355     while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
7356     {
7357         if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name);
7358         EndTable();
7359     }
7360 
7361     ImGuiWindow* window = g.CurrentWindow;
7362     ImGuiStackSizes* stack_sizes = &g.CurrentWindowStack.back().StackSizesOnBegin;
7363     IM_ASSERT(window != NULL);
7364     while (g.CurrentTabBar != NULL) //-V1044
7365     {
7366         if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name);
7367         EndTabBar();
7368     }
7369     while (window->DC.TreeDepth > 0)
7370     {
7371         if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name);
7372         TreePop();
7373     }
7374     while (g.GroupStack.Size > stack_sizes->SizeOfGroupStack) //-V1044
7375     {
7376         if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name);
7377         EndGroup();
7378     }
7379     while (window->IDStack.Size > 1)
7380     {
7381         if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name);
7382         PopID();
7383     }
7384     while (g.DisabledStackSize > stack_sizes->SizeOfDisabledStack) //-V1044
7385     {
7386         if (log_callback) log_callback(user_data, "Recovered from missing EndDisabled() in '%s'", window->Name);
7387         EndDisabled();
7388     }
7389     while (g.ColorStack.Size > stack_sizes->SizeOfColorStack)
7390     {
7391         if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col));
7392         PopStyleColor();
7393     }
7394     while (g.ItemFlagsStack.Size > stack_sizes->SizeOfItemFlagsStack) //-V1044
7395     {
7396         if (log_callback) log_callback(user_data, "Recovered from missing PopItemFlag() in '%s'", window->Name);
7397         PopItemFlag();
7398     }
7399     while (g.StyleVarStack.Size > stack_sizes->SizeOfStyleVarStack) //-V1044
7400     {
7401         if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name);
7402         PopStyleVar();
7403     }
7404     while (g.FocusScopeStack.Size > stack_sizes->SizeOfFocusScopeStack) //-V1044
7405     {
7406         if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name);
7407         PopFocusScope();
7408     }
7409 }
7410 
7411 // Save current stack sizes for later compare
SetToCurrentState()7412 void ImGuiStackSizes::SetToCurrentState()
7413 {
7414     ImGuiContext& g = *GImGui;
7415     ImGuiWindow* window = g.CurrentWindow;
7416     SizeOfIDStack = (short)window->IDStack.Size;
7417     SizeOfColorStack = (short)g.ColorStack.Size;
7418     SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
7419     SizeOfFontStack = (short)g.FontStack.Size;
7420     SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
7421     SizeOfGroupStack = (short)g.GroupStack.Size;
7422     SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
7423     SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
7424     SizeOfDisabledStack = (short)g.DisabledStackSize;
7425 }
7426 
7427 // Compare to detect usage errors
CompareWithCurrentState()7428 void ImGuiStackSizes::CompareWithCurrentState()
7429 {
7430     ImGuiContext& g = *GImGui;
7431     ImGuiWindow* window = g.CurrentWindow;
7432     IM_UNUSED(window);
7433 
7434     // Window stacks
7435     // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
7436     IM_ASSERT(SizeOfIDStack         == window->IDStack.Size     && "PushID/PopID or TreeNode/TreePop Mismatch!");
7437 
7438     // Global stacks
7439     // 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.
7440     IM_ASSERT(SizeOfGroupStack      == g.GroupStack.Size        && "BeginGroup/EndGroup Mismatch!");
7441     IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size   && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!");
7442     IM_ASSERT(SizeOfDisabledStack   == g.DisabledStackSize      && "BeginDisabled/EndDisabled Mismatch!");
7443     IM_ASSERT(SizeOfItemFlagsStack  >= g.ItemFlagsStack.Size    && "PushItemFlag/PopItemFlag Mismatch!");
7444     IM_ASSERT(SizeOfColorStack      >= g.ColorStack.Size        && "PushStyleColor/PopStyleColor Mismatch!");
7445     IM_ASSERT(SizeOfStyleVarStack   >= g.StyleVarStack.Size     && "PushStyleVar/PopStyleVar Mismatch!");
7446     IM_ASSERT(SizeOfFontStack       >= g.FontStack.Size         && "PushFont/PopFont Mismatch!");
7447     IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size   && "PushFocusScope/PopFocusScope Mismatch!");
7448 }
7449 
7450 
7451 //-----------------------------------------------------------------------------
7452 // [SECTION] LAYOUT
7453 //-----------------------------------------------------------------------------
7454 // - ItemSize()
7455 // - ItemAdd()
7456 // - SameLine()
7457 // - GetCursorScreenPos()
7458 // - SetCursorScreenPos()
7459 // - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
7460 // - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
7461 // - GetCursorStartPos()
7462 // - Indent()
7463 // - Unindent()
7464 // - SetNextItemWidth()
7465 // - PushItemWidth()
7466 // - PushMultiItemsWidths()
7467 // - PopItemWidth()
7468 // - CalcItemWidth()
7469 // - CalcItemSize()
7470 // - GetTextLineHeight()
7471 // - GetTextLineHeightWithSpacing()
7472 // - GetFrameHeight()
7473 // - GetFrameHeightWithSpacing()
7474 // - GetContentRegionMax()
7475 // - GetContentRegionMaxAbs() [Internal]
7476 // - GetContentRegionAvail(),
7477 // - GetWindowContentRegionMin(), GetWindowContentRegionMax()
7478 // - BeginGroup()
7479 // - EndGroup()
7480 // Also see in imgui_widgets: tab bars, columns.
7481 //-----------------------------------------------------------------------------
7482 
7483 // Advance cursor given item size for layout.
7484 // Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
7485 // See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
ItemSize(const ImVec2 & size,float text_baseline_y)7486 void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
7487 {
7488     ImGuiContext& g = *GImGui;
7489     ImGuiWindow* window = g.CurrentWindow;
7490     if (window->SkipItems)
7491         return;
7492 
7493     // We increase the height in this function to accommodate for baseline offset.
7494     // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
7495     // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
7496     const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
7497     const float line_height = ImMax(window->DC.CurrLineSize.y, size.y + offset_to_match_baseline_y);
7498 
7499     // Always align ourselves on pixel boundaries
7500     //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]
7501     window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
7502     window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y;
7503     window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);    // Next line
7504     window->DC.CursorPos.y = IM_FLOOR(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y);        // Next line
7505     window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
7506     window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
7507     //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
7508 
7509     window->DC.PrevLineSize.y = line_height;
7510     window->DC.CurrLineSize.y = 0.0f;
7511     window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
7512     window->DC.CurrLineTextBaseOffset = 0.0f;
7513 
7514     // Horizontal layout mode
7515     if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
7516         SameLine();
7517 }
7518 
ItemSize(const ImRect & bb,float text_baseline_y)7519 void ImGui::ItemSize(const ImRect& bb, float text_baseline_y)
7520 {
7521     ItemSize(bb.GetSize(), text_baseline_y);
7522 }
7523 
7524 // Declare item bounding box for clipping and interaction.
7525 // Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
7526 // declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
ItemAdd(const ImRect & bb,ImGuiID id,const ImRect * nav_bb_arg,ImGuiItemFlags extra_flags)7527 bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
7528 {
7529     ImGuiContext& g = *GImGui;
7530     ImGuiWindow* window = g.CurrentWindow;
7531 
7532     // Set item data
7533     // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
7534     g.LastItemData.ID = id;
7535     g.LastItemData.Rect = bb;
7536     g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
7537     g.LastItemData.InFlags = g.CurrentItemFlags | extra_flags;
7538     g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
7539 
7540     // Directional navigation processing
7541     if (id != 0)
7542     {
7543         // Runs prior to clipping early-out
7544         //  (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
7545         //  (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
7546         //      unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
7547         //      thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
7548         //      We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
7549         //      to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
7550         // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
7551         // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
7552         window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
7553         if (g.NavId == id || g.NavAnyRequest)
7554             if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
7555                 if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
7556                     NavProcessItem();
7557 
7558         // [DEBUG] Item Picker tool, when enabling the "extended" version we perform the check in ItemAdd()
7559 #ifdef IMGUI_DEBUG_TOOL_ITEM_PICKER_EX
7560         if (id == g.DebugItemPickerBreakId)
7561         {
7562             IM_DEBUG_BREAK();
7563             g.DebugItemPickerBreakId = 0;
7564         }
7565 #endif
7566     }
7567     g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
7568 
7569 #ifdef IMGUI_ENABLE_TEST_ENGINE
7570     if (id != 0)
7571         IMGUI_TEST_ENGINE_ITEM_ADD(nav_bb_arg ? *nav_bb_arg : bb, id);
7572 #endif
7573 
7574     // Clipping test
7575     const bool is_clipped = IsClippedEx(bb, id);
7576     if (is_clipped)
7577         return false;
7578     //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
7579 
7580     // [WIP] Tab stop handling (previously was using internal FocusableItemRegister() api)
7581     // FIXME-NAV: We would now want to move this before the clipping test, but this would require being able to scroll and currently this would mean an extra frame. (#4079, #343)
7582     if (extra_flags & ImGuiItemFlags_Inputable)
7583         ItemInputable(window, id);
7584 
7585     // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
7586     if (IsMouseHoveringRect(bb.Min, bb.Max))
7587         g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
7588     return true;
7589 }
7590 
7591 // Gets back to previous line and continue with horizontal layout
7592 //      offset_from_start_x == 0 : follow right after previous item
7593 //      offset_from_start_x != 0 : align to specified x position (relative to window/group left)
7594 //      spacing_w < 0            : use default spacing if pos_x == 0, no spacing if pos_x != 0
7595 //      spacing_w >= 0           : enforce spacing amount
SameLine(float offset_from_start_x,float spacing_w)7596 void ImGui::SameLine(float offset_from_start_x, float spacing_w)
7597 {
7598     ImGuiWindow* window = GetCurrentWindow();
7599     if (window->SkipItems)
7600         return;
7601 
7602     ImGuiContext& g = *GImGui;
7603     if (offset_from_start_x != 0.0f)
7604     {
7605         if (spacing_w < 0.0f) spacing_w = 0.0f;
7606         window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
7607         window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
7608     }
7609     else
7610     {
7611         if (spacing_w < 0.0f) spacing_w = g.Style.ItemSpacing.x;
7612         window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
7613         window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
7614     }
7615     window->DC.CurrLineSize = window->DC.PrevLineSize;
7616     window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
7617 }
7618 
GetCursorScreenPos()7619 ImVec2 ImGui::GetCursorScreenPos()
7620 {
7621     ImGuiWindow* window = GetCurrentWindowRead();
7622     return window->DC.CursorPos;
7623 }
7624 
SetCursorScreenPos(const ImVec2 & pos)7625 void ImGui::SetCursorScreenPos(const ImVec2& pos)
7626 {
7627     ImGuiWindow* window = GetCurrentWindow();
7628     window->DC.CursorPos = pos;
7629     window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
7630 }
7631 
7632 // User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
7633 // 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'.
GetCursorPos()7634 ImVec2 ImGui::GetCursorPos()
7635 {
7636     ImGuiWindow* window = GetCurrentWindowRead();
7637     return window->DC.CursorPos - window->Pos + window->Scroll;
7638 }
7639 
GetCursorPosX()7640 float ImGui::GetCursorPosX()
7641 {
7642     ImGuiWindow* window = GetCurrentWindowRead();
7643     return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
7644 }
7645 
GetCursorPosY()7646 float ImGui::GetCursorPosY()
7647 {
7648     ImGuiWindow* window = GetCurrentWindowRead();
7649     return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
7650 }
7651 
SetCursorPos(const ImVec2 & local_pos)7652 void ImGui::SetCursorPos(const ImVec2& local_pos)
7653 {
7654     ImGuiWindow* window = GetCurrentWindow();
7655     window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
7656     window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
7657 }
7658 
SetCursorPosX(float x)7659 void ImGui::SetCursorPosX(float x)
7660 {
7661     ImGuiWindow* window = GetCurrentWindow();
7662     window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
7663     window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
7664 }
7665 
SetCursorPosY(float y)7666 void ImGui::SetCursorPosY(float y)
7667 {
7668     ImGuiWindow* window = GetCurrentWindow();
7669     window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
7670     window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
7671 }
7672 
GetCursorStartPos()7673 ImVec2 ImGui::GetCursorStartPos()
7674 {
7675     ImGuiWindow* window = GetCurrentWindowRead();
7676     return window->DC.CursorStartPos - window->Pos;
7677 }
7678 
Indent(float indent_w)7679 void ImGui::Indent(float indent_w)
7680 {
7681     ImGuiContext& g = *GImGui;
7682     ImGuiWindow* window = GetCurrentWindow();
7683     window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
7684     window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
7685 }
7686 
Unindent(float indent_w)7687 void ImGui::Unindent(float indent_w)
7688 {
7689     ImGuiContext& g = *GImGui;
7690     ImGuiWindow* window = GetCurrentWindow();
7691     window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
7692     window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
7693 }
7694 
7695 // Affect large frame+labels widgets only.
SetNextItemWidth(float item_width)7696 void ImGui::SetNextItemWidth(float item_width)
7697 {
7698     ImGuiContext& g = *GImGui;
7699     g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
7700     g.NextItemData.Width = item_width;
7701 }
7702 
7703 // FIXME: Remove the == 0.0f behavior?
PushItemWidth(float item_width)7704 void ImGui::PushItemWidth(float item_width)
7705 {
7706     ImGuiContext& g = *GImGui;
7707     ImGuiWindow* window = g.CurrentWindow;
7708     window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
7709     window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
7710     g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
7711 }
7712 
PushMultiItemsWidths(int components,float w_full)7713 void ImGui::PushMultiItemsWidths(int components, float w_full)
7714 {
7715     ImGuiContext& g = *GImGui;
7716     ImGuiWindow* window = g.CurrentWindow;
7717     const ImGuiStyle& style = g.Style;
7718     const float w_item_one  = ImMax(1.0f, IM_FLOOR((w_full - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components));
7719     const float w_item_last = ImMax(1.0f, IM_FLOOR(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components - 1)));
7720     window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
7721     window->DC.ItemWidthStack.push_back(w_item_last);
7722     for (int i = 0; i < components - 2; i++)
7723         window->DC.ItemWidthStack.push_back(w_item_one);
7724     window->DC.ItemWidth = (components == 1) ? w_item_last : w_item_one;
7725     g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
7726 }
7727 
PopItemWidth()7728 void ImGui::PopItemWidth()
7729 {
7730     ImGuiWindow* window = GetCurrentWindow();
7731     window->DC.ItemWidth = window->DC.ItemWidthStack.back();
7732     window->DC.ItemWidthStack.pop_back();
7733 }
7734 
7735 // Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
7736 // The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
CalcItemWidth()7737 float ImGui::CalcItemWidth()
7738 {
7739     ImGuiContext& g = *GImGui;
7740     ImGuiWindow* window = g.CurrentWindow;
7741     float w;
7742     if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
7743         w = g.NextItemData.Width;
7744     else
7745         w = window->DC.ItemWidth;
7746     if (w < 0.0f)
7747     {
7748         float region_max_x = GetContentRegionMaxAbs().x;
7749         w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
7750     }
7751     w = IM_FLOOR(w);
7752     return w;
7753 }
7754 
7755 // [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
7756 // Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
7757 // Note that only CalcItemWidth() is publicly exposed.
7758 // The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
CalcItemSize(ImVec2 size,float default_w,float default_h)7759 ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
7760 {
7761     ImGuiWindow* window = GImGui->CurrentWindow;
7762 
7763     ImVec2 region_max;
7764     if (size.x < 0.0f || size.y < 0.0f)
7765         region_max = GetContentRegionMaxAbs();
7766 
7767     if (size.x == 0.0f)
7768         size.x = default_w;
7769     else if (size.x < 0.0f)
7770         size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
7771 
7772     if (size.y == 0.0f)
7773         size.y = default_h;
7774     else if (size.y < 0.0f)
7775         size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
7776 
7777     return size;
7778 }
7779 
GetTextLineHeight()7780 float ImGui::GetTextLineHeight()
7781 {
7782     ImGuiContext& g = *GImGui;
7783     return g.FontSize;
7784 }
7785 
GetTextLineHeightWithSpacing()7786 float ImGui::GetTextLineHeightWithSpacing()
7787 {
7788     ImGuiContext& g = *GImGui;
7789     return g.FontSize + g.Style.ItemSpacing.y;
7790 }
7791 
GetFrameHeight()7792 float ImGui::GetFrameHeight()
7793 {
7794     ImGuiContext& g = *GImGui;
7795     return g.FontSize + g.Style.FramePadding.y * 2.0f;
7796 }
7797 
GetFrameHeightWithSpacing()7798 float ImGui::GetFrameHeightWithSpacing()
7799 {
7800     ImGuiContext& g = *GImGui;
7801     return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
7802 }
7803 
7804 // 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!
7805 
7806 // FIXME: This is in window space (not screen space!).
GetContentRegionMax()7807 ImVec2 ImGui::GetContentRegionMax()
7808 {
7809     ImGuiContext& g = *GImGui;
7810     ImGuiWindow* window = g.CurrentWindow;
7811     ImVec2 mx = window->ContentRegionRect.Max - window->Pos;
7812     if (window->DC.CurrentColumns || g.CurrentTable)
7813         mx.x = window->WorkRect.Max.x - window->Pos.x;
7814     return mx;
7815 }
7816 
7817 // [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
GetContentRegionMaxAbs()7818 ImVec2 ImGui::GetContentRegionMaxAbs()
7819 {
7820     ImGuiContext& g = *GImGui;
7821     ImGuiWindow* window = g.CurrentWindow;
7822     ImVec2 mx = window->ContentRegionRect.Max;
7823     if (window->DC.CurrentColumns || g.CurrentTable)
7824         mx.x = window->WorkRect.Max.x;
7825     return mx;
7826 }
7827 
GetContentRegionAvail()7828 ImVec2 ImGui::GetContentRegionAvail()
7829 {
7830     ImGuiWindow* window = GImGui->CurrentWindow;
7831     return GetContentRegionMaxAbs() - window->DC.CursorPos;
7832 }
7833 
7834 // In window space (not screen space!)
GetWindowContentRegionMin()7835 ImVec2 ImGui::GetWindowContentRegionMin()
7836 {
7837     ImGuiWindow* window = GImGui->CurrentWindow;
7838     return window->ContentRegionRect.Min - window->Pos;
7839 }
7840 
GetWindowContentRegionMax()7841 ImVec2 ImGui::GetWindowContentRegionMax()
7842 {
7843     ImGuiWindow* window = GImGui->CurrentWindow;
7844     return window->ContentRegionRect.Max - window->Pos;
7845 }
7846 
7847 // 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.)
7848 // Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
7849 // FIXME-OPT: Could we safely early out on ->SkipItems?
BeginGroup()7850 void ImGui::BeginGroup()
7851 {
7852     ImGuiContext& g = *GImGui;
7853     ImGuiWindow* window = g.CurrentWindow;
7854 
7855     g.GroupStack.resize(g.GroupStack.Size + 1);
7856     ImGuiGroupData& group_data = g.GroupStack.back();
7857     group_data.WindowID = window->ID;
7858     group_data.BackupCursorPos = window->DC.CursorPos;
7859     group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
7860     group_data.BackupIndent = window->DC.Indent;
7861     group_data.BackupGroupOffset = window->DC.GroupOffset;
7862     group_data.BackupCurrLineSize = window->DC.CurrLineSize;
7863     group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
7864     group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
7865     group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
7866     group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
7867     group_data.EmitItem = true;
7868 
7869     window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
7870     window->DC.Indent = window->DC.GroupOffset;
7871     window->DC.CursorMaxPos = window->DC.CursorPos;
7872     window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
7873     if (g.LogEnabled)
7874         g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
7875 }
7876 
EndGroup()7877 void ImGui::EndGroup()
7878 {
7879     ImGuiContext& g = *GImGui;
7880     ImGuiWindow* window = g.CurrentWindow;
7881     IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
7882 
7883     ImGuiGroupData& group_data = g.GroupStack.back();
7884     IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
7885 
7886     ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
7887 
7888     window->DC.CursorPos = group_data.BackupCursorPos;
7889     window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
7890     window->DC.Indent = group_data.BackupIndent;
7891     window->DC.GroupOffset = group_data.BackupGroupOffset;
7892     window->DC.CurrLineSize = group_data.BackupCurrLineSize;
7893     window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
7894     if (g.LogEnabled)
7895         g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
7896 
7897     if (!group_data.EmitItem)
7898     {
7899         g.GroupStack.pop_back();
7900         return;
7901     }
7902 
7903     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.
7904     ItemSize(group_bb.GetSize());
7905     ItemAdd(group_bb, 0);
7906 
7907     // 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.
7908     // It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
7909     // Also if you grep for LastItemId you'll notice it is only used in that context.
7910     // (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.)
7911     const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
7912     const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
7913     if (group_contains_curr_active_id)
7914         g.LastItemData.ID = g.ActiveId;
7915     else if (group_contains_prev_active_id)
7916         g.LastItemData.ID = g.ActiveIdPreviousFrame;
7917     g.LastItemData.Rect = group_bb;
7918 
7919     // Forward Hovered flag
7920     const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
7921     if (group_contains_curr_hovered_id)
7922         g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
7923 
7924     // Forward Edited flag
7925     if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
7926         g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
7927 
7928     // Forward Deactivated flag
7929     g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
7930     if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
7931         g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
7932 
7933     g.GroupStack.pop_back();
7934     //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255));   // [Debug]
7935 }
7936 
7937 
7938 //-----------------------------------------------------------------------------
7939 // [SECTION] SCROLLING
7940 //-----------------------------------------------------------------------------
7941 
7942 // Helper to snap on edges when aiming at an item very close to the edge,
7943 // So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
7944 // When we refactor the scrolling API this may be configurable with a flag?
7945 // Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
CalcScrollEdgeSnap(float target,float snap_min,float snap_max,float snap_threshold,float center_ratio)7946 static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
7947 {
7948     if (target <= snap_min + snap_threshold)
7949         return ImLerp(snap_min, target, center_ratio);
7950     if (target >= snap_max - snap_threshold)
7951         return ImLerp(target, snap_max, center_ratio);
7952     return target;
7953 }
7954 
CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow * window)7955 static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
7956 {
7957     ImVec2 scroll = window->Scroll;
7958     if (window->ScrollTarget.x < FLT_MAX)
7959     {
7960         float decoration_total_width = window->ScrollbarSizes.x;
7961         float center_x_ratio = window->ScrollTargetCenterRatio.x;
7962         float scroll_target_x = window->ScrollTarget.x;
7963         if (window->ScrollTargetEdgeSnapDist.x > 0.0f)
7964         {
7965             float snap_x_min = 0.0f;
7966             float snap_x_max = window->ScrollMax.x + window->SizeFull.x - decoration_total_width;
7967             scroll_target_x = CalcScrollEdgeSnap(scroll_target_x, snap_x_min, snap_x_max, window->ScrollTargetEdgeSnapDist.x, center_x_ratio);
7968         }
7969         scroll.x = scroll_target_x - center_x_ratio * (window->SizeFull.x - decoration_total_width);
7970     }
7971     if (window->ScrollTarget.y < FLT_MAX)
7972     {
7973         float decoration_total_height = window->TitleBarHeight() + window->MenuBarHeight() + window->ScrollbarSizes.y;
7974         float center_y_ratio = window->ScrollTargetCenterRatio.y;
7975         float scroll_target_y = window->ScrollTarget.y;
7976         if (window->ScrollTargetEdgeSnapDist.y > 0.0f)
7977         {
7978             float snap_y_min = 0.0f;
7979             float snap_y_max = window->ScrollMax.y + window->SizeFull.y - decoration_total_height;
7980             scroll_target_y = CalcScrollEdgeSnap(scroll_target_y, snap_y_min, snap_y_max, window->ScrollTargetEdgeSnapDist.y, center_y_ratio);
7981         }
7982         scroll.y = scroll_target_y - center_y_ratio * (window->SizeFull.y - decoration_total_height);
7983     }
7984     scroll.x = IM_FLOOR(ImMax(scroll.x, 0.0f));
7985     scroll.y = IM_FLOOR(ImMax(scroll.y, 0.0f));
7986     if (!window->Collapsed && !window->SkipItems)
7987     {
7988         scroll.x = ImMin(scroll.x, window->ScrollMax.x);
7989         scroll.y = ImMin(scroll.y, window->ScrollMax.y);
7990     }
7991     return scroll;
7992 }
7993 
ScrollToItem(ImGuiScrollFlags flags)7994 void ImGui::ScrollToItem(ImGuiScrollFlags flags)
7995 {
7996     ImGuiContext& g = *GImGui;
7997     ImGuiWindow* window = g.CurrentWindow;
7998     ScrollToRectEx(window, g.LastItemData.NavRect, flags);
7999 }
8000 
ScrollToRect(ImGuiWindow * window,const ImRect & item_rect,ImGuiScrollFlags flags)8001 void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
8002 {
8003     ScrollToRectEx(window, item_rect, flags);
8004 }
8005 
8006 // Scroll to keep newly navigated item fully into view
ScrollToRectEx(ImGuiWindow * window,const ImRect & item_rect,ImGuiScrollFlags flags)8007 ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
8008 {
8009     ImGuiContext& g = *GImGui;
8010     ImRect window_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
8011     //GetForegroundDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG]
8012 
8013     // Check that only one behavior is selected per axis
8014     IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
8015     IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
8016 
8017     // Defaults
8018     ImGuiScrollFlags in_flags = flags;
8019     if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
8020         flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
8021     if ((flags & ImGuiScrollFlags_MaskY_) == 0)
8022         flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
8023 
8024     const bool fully_visible_x = item_rect.Min.x >= window_rect.Min.x && item_rect.Max.x <= window_rect.Max.x;
8025     const bool fully_visible_y = item_rect.Min.y >= window_rect.Min.y && item_rect.Max.y <= window_rect.Max.y;
8026     const bool can_be_fully_visible_x = item_rect.GetWidth() <= window_rect.GetWidth();
8027     const bool can_be_fully_visible_y = item_rect.GetHeight() <= window_rect.GetHeight();
8028 
8029     if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
8030     {
8031         if (item_rect.Min.x < window_rect.Min.x || !can_be_fully_visible_x)
8032             SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f);
8033         else if (item_rect.Max.x >= window_rect.Max.x)
8034             SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f);
8035     }
8036     else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
8037     {
8038         float target_x = can_be_fully_visible_x ? ImFloor((item_rect.Min.x + item_rect.Max.x - window->InnerRect.GetWidth()) * 0.5f) : item_rect.Min.x;
8039         SetScrollFromPosX(window, target_x - window->Pos.x, 0.0f);
8040     }
8041 
8042     if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
8043     {
8044         if (item_rect.Min.y < window_rect.Min.y || !can_be_fully_visible_y)
8045             SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f);
8046         else if (item_rect.Max.y >= window_rect.Max.y)
8047             SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f);
8048     }
8049     else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
8050     {
8051         float target_y = can_be_fully_visible_y ? ImFloor((item_rect.Min.y + item_rect.Max.y - window->InnerRect.GetHeight()) * 0.5f) : item_rect.Min.y;
8052         SetScrollFromPosY(window, target_y - window->Pos.y, 0.0f);
8053     }
8054 
8055     ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
8056     ImVec2 delta_scroll = next_scroll - window->Scroll;
8057 
8058     // Also scroll parent window to keep us into view if necessary
8059     if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
8060     {
8061         // FIXME-SCROLL: May be an option?
8062         if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
8063             in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
8064         if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
8065             in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
8066         delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags);
8067     }
8068 
8069     return delta_scroll;
8070 }
8071 
GetScrollX()8072 float ImGui::GetScrollX()
8073 {
8074     ImGuiWindow* window = GImGui->CurrentWindow;
8075     return window->Scroll.x;
8076 }
8077 
GetScrollY()8078 float ImGui::GetScrollY()
8079 {
8080     ImGuiWindow* window = GImGui->CurrentWindow;
8081     return window->Scroll.y;
8082 }
8083 
GetScrollMaxX()8084 float ImGui::GetScrollMaxX()
8085 {
8086     ImGuiWindow* window = GImGui->CurrentWindow;
8087     return window->ScrollMax.x;
8088 }
8089 
GetScrollMaxY()8090 float ImGui::GetScrollMaxY()
8091 {
8092     ImGuiWindow* window = GImGui->CurrentWindow;
8093     return window->ScrollMax.y;
8094 }
8095 
SetScrollX(ImGuiWindow * window,float scroll_x)8096 void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
8097 {
8098     window->ScrollTarget.x = scroll_x;
8099     window->ScrollTargetCenterRatio.x = 0.0f;
8100     window->ScrollTargetEdgeSnapDist.x = 0.0f;
8101 }
8102 
SetScrollY(ImGuiWindow * window,float scroll_y)8103 void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
8104 {
8105     window->ScrollTarget.y = scroll_y;
8106     window->ScrollTargetCenterRatio.y = 0.0f;
8107     window->ScrollTargetEdgeSnapDist.y = 0.0f;
8108 }
8109 
SetScrollX(float scroll_x)8110 void ImGui::SetScrollX(float scroll_x)
8111 {
8112     ImGuiContext& g = *GImGui;
8113     SetScrollX(g.CurrentWindow, scroll_x);
8114 }
8115 
SetScrollY(float scroll_y)8116 void ImGui::SetScrollY(float scroll_y)
8117 {
8118     ImGuiContext& g = *GImGui;
8119     SetScrollY(g.CurrentWindow, scroll_y);
8120 }
8121 
8122 // Note that a local position will vary depending on initial scroll value,
8123 // This is a little bit confusing so bear with us:
8124 //  - local_pos = (absolution_pos - window->Pos)
8125 //  - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
8126 //    and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
8127 //  - They mostly exists because of legacy API.
8128 // Following the rules above, when trying to work with scrolling code, consider that:
8129 //  - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
8130 //  - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
8131 // 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
SetScrollFromPosX(ImGuiWindow * window,float local_x,float center_x_ratio)8132 void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
8133 {
8134     IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
8135     window->ScrollTarget.x = IM_FLOOR(local_x + window->Scroll.x); // Convert local position to scroll offset
8136     window->ScrollTargetCenterRatio.x = center_x_ratio;
8137     window->ScrollTargetEdgeSnapDist.x = 0.0f;
8138 }
8139 
SetScrollFromPosY(ImGuiWindow * window,float local_y,float center_y_ratio)8140 void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
8141 {
8142     IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
8143     const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight(); // FIXME: Would be nice to have a more standardized access to our scrollable/client rect;
8144     local_y -= decoration_up_height;
8145     window->ScrollTarget.y = IM_FLOOR(local_y + window->Scroll.y); // Convert local position to scroll offset
8146     window->ScrollTargetCenterRatio.y = center_y_ratio;
8147     window->ScrollTargetEdgeSnapDist.y = 0.0f;
8148 }
8149 
SetScrollFromPosX(float local_x,float center_x_ratio)8150 void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
8151 {
8152     ImGuiContext& g = *GImGui;
8153     SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
8154 }
8155 
SetScrollFromPosY(float local_y,float center_y_ratio)8156 void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
8157 {
8158     ImGuiContext& g = *GImGui;
8159     SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
8160 }
8161 
8162 // center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
SetScrollHereX(float center_x_ratio)8163 void ImGui::SetScrollHereX(float center_x_ratio)
8164 {
8165     ImGuiContext& g = *GImGui;
8166     ImGuiWindow* window = g.CurrentWindow;
8167     float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);
8168     float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio);
8169     SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
8170 
8171     // Tweak: snap on edges when aiming at an item very close to the edge
8172     window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
8173 }
8174 
8175 // center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
SetScrollHereY(float center_y_ratio)8176 void ImGui::SetScrollHereY(float center_y_ratio)
8177 {
8178     ImGuiContext& g = *GImGui;
8179     ImGuiWindow* window = g.CurrentWindow;
8180     float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);
8181     float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
8182     SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
8183 
8184     // Tweak: snap on edges when aiming at an item very close to the edge
8185     window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
8186 }
8187 
8188 //-----------------------------------------------------------------------------
8189 // [SECTION] TOOLTIPS
8190 //-----------------------------------------------------------------------------
8191 
BeginTooltip()8192 void ImGui::BeginTooltip()
8193 {
8194     BeginTooltipEx(ImGuiWindowFlags_None, ImGuiTooltipFlags_None);
8195 }
8196 
BeginTooltipEx(ImGuiWindowFlags extra_flags,ImGuiTooltipFlags tooltip_flags)8197 void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, ImGuiTooltipFlags tooltip_flags)
8198 {
8199     ImGuiContext& g = *GImGui;
8200 
8201     if (g.DragDropWithinSource || g.DragDropWithinTarget)
8202     {
8203         // The default tooltip position is a little offset to give space to see the context menu (it's also clamped within the current viewport/monitor)
8204         // In the context of a dragging tooltip we try to reduce that offset and we enforce following the cursor.
8205         // Whatever we do we want to call SetNextWindowPos() to enforce a tooltip position and disable clipping the tooltip without our display area, like regular tooltip do.
8206         //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
8207         ImVec2 tooltip_pos = g.IO.MousePos + ImVec2(16 * g.Style.MouseCursorScale, 8 * g.Style.MouseCursorScale);
8208         SetNextWindowPos(tooltip_pos);
8209         SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
8210         //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
8211         tooltip_flags |= ImGuiTooltipFlags_OverridePreviousTooltip;
8212     }
8213 
8214     char window_name[16];
8215     ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
8216     if (tooltip_flags & ImGuiTooltipFlags_OverridePreviousTooltip)
8217         if (ImGuiWindow* window = FindWindowByName(window_name))
8218             if (window->Active)
8219             {
8220                 // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
8221                 window->Hidden = true;
8222                 window->HiddenFramesCanSkipItems = 1; // FIXME: This may not be necessary?
8223                 ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
8224             }
8225     ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize;
8226     Begin(window_name, NULL, flags | extra_flags);
8227 }
8228 
EndTooltip()8229 void ImGui::EndTooltip()
8230 {
8231     IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip);   // Mismatched BeginTooltip()/EndTooltip() calls
8232     End();
8233 }
8234 
SetTooltipV(const char * fmt,va_list args)8235 void ImGui::SetTooltipV(const char* fmt, va_list args)
8236 {
8237     BeginTooltipEx(0, ImGuiTooltipFlags_OverridePreviousTooltip);
8238     TextV(fmt, args);
8239     EndTooltip();
8240 }
8241 
SetTooltip(const char * fmt,...)8242 void ImGui::SetTooltip(const char* fmt, ...)
8243 {
8244     va_list args;
8245     va_start(args, fmt);
8246     SetTooltipV(fmt, args);
8247     va_end(args);
8248 }
8249 
8250 //-----------------------------------------------------------------------------
8251 // [SECTION] POPUPS
8252 //-----------------------------------------------------------------------------
8253 
8254 // Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
IsPopupOpen(ImGuiID id,ImGuiPopupFlags popup_flags)8255 bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
8256 {
8257     ImGuiContext& g = *GImGui;
8258     if (popup_flags & ImGuiPopupFlags_AnyPopupId)
8259     {
8260         // Return true if any popup is open at the current BeginPopup() level of the popup stack
8261         // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
8262         IM_ASSERT(id == 0);
8263         if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
8264             return g.OpenPopupStack.Size > 0;
8265         else
8266             return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
8267     }
8268     else
8269     {
8270         if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
8271         {
8272             // Return true if the popup is open anywhere in the popup stack
8273             for (int n = 0; n < g.OpenPopupStack.Size; n++)
8274                 if (g.OpenPopupStack[n].PopupId == id)
8275                     return true;
8276             return false;
8277         }
8278         else
8279         {
8280             // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
8281             return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
8282         }
8283     }
8284 }
8285 
IsPopupOpen(const char * str_id,ImGuiPopupFlags popup_flags)8286 bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
8287 {
8288     ImGuiContext& g = *GImGui;
8289     ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
8290     if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
8291         IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
8292     return IsPopupOpen(id, popup_flags);
8293 }
8294 
GetTopMostPopupModal()8295 ImGuiWindow* ImGui::GetTopMostPopupModal()
8296 {
8297     ImGuiContext& g = *GImGui;
8298     for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
8299         if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
8300             if (popup->Flags & ImGuiWindowFlags_Modal)
8301                 return popup;
8302     return NULL;
8303 }
8304 
OpenPopup(const char * str_id,ImGuiPopupFlags popup_flags)8305 void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
8306 {
8307     ImGuiContext& g = *GImGui;
8308     OpenPopupEx(g.CurrentWindow->GetID(str_id), popup_flags);
8309 }
8310 
OpenPopup(ImGuiID id,ImGuiPopupFlags popup_flags)8311 void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
8312 {
8313     OpenPopupEx(id, popup_flags);
8314 }
8315 
8316 // Mark popup as open (toggle toward open state).
8317 // Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
8318 // Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
8319 // One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
OpenPopupEx(ImGuiID id,ImGuiPopupFlags popup_flags)8320 void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
8321 {
8322     ImGuiContext& g = *GImGui;
8323     ImGuiWindow* parent_window = g.CurrentWindow;
8324     const int current_stack_size = g.BeginPopupStack.Size;
8325 
8326     if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
8327         if (IsPopupOpen(0u, ImGuiPopupFlags_AnyPopupId))
8328             return;
8329 
8330     ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
8331     popup_ref.PopupId = id;
8332     popup_ref.Window = NULL;
8333     popup_ref.SourceWindow = g.NavWindow;
8334     popup_ref.OpenFrameCount = g.FrameCount;
8335     popup_ref.OpenParentId = parent_window->IDStack.back();
8336     popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
8337     popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
8338 
8339     IMGUI_DEBUG_LOG_POPUP("OpenPopupEx(0x%08X)\n", id);
8340     if (g.OpenPopupStack.Size < current_stack_size + 1)
8341     {
8342         g.OpenPopupStack.push_back(popup_ref);
8343     }
8344     else
8345     {
8346         // Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui
8347         // would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing
8348         // situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand.
8349         if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)
8350         {
8351             g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
8352         }
8353         else
8354         {
8355             // Close child popups if any, then flag popup for open/reopen
8356             ClosePopupToLevel(current_stack_size, false);
8357             g.OpenPopupStack.push_back(popup_ref);
8358         }
8359 
8360         // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
8361         // This is equivalent to what ClosePopupToLevel() does.
8362         //if (g.OpenPopupStack[current_stack_size].PopupId == id)
8363         //    FocusWindow(parent_window);
8364     }
8365 }
8366 
8367 // When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
8368 // This function closes any popups that are over 'ref_window'.
ClosePopupsOverWindow(ImGuiWindow * ref_window,bool restore_focus_to_window_under_popup)8369 void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
8370 {
8371     ImGuiContext& g = *GImGui;
8372     if (g.OpenPopupStack.Size == 0)
8373         return;
8374 
8375     // Don't close our own child popup windows.
8376     int popup_count_to_keep = 0;
8377     if (ref_window)
8378     {
8379         // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
8380         for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
8381         {
8382             ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
8383             if (!popup.Window)
8384                 continue;
8385             IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
8386             if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
8387                 continue;
8388 
8389             // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
8390             // - With this stack of window, clicking/focusing Popup1 will close Popup2 and Popup3:
8391             //     Window -> Popup1 -> Popup2 -> Popup3
8392             // - Each popups may contain child windows, which is why we compare ->RootWindow!
8393             //     Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
8394             bool ref_window_is_descendent_of_popup = false;
8395             for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
8396                 if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
8397                     if (popup_window->RootWindow == ref_window->RootWindow)
8398                     {
8399                         ref_window_is_descendent_of_popup = true;
8400                         break;
8401                     }
8402             if (!ref_window_is_descendent_of_popup)
8403                 break;
8404         }
8405     }
8406     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
8407     {
8408         IMGUI_DEBUG_LOG_POPUP("ClosePopupsOverWindow(\"%s\") -> ClosePopupToLevel(%d)\n", ref_window->Name, popup_count_to_keep);
8409         ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
8410     }
8411 }
8412 
ClosePopupsExceptModals()8413 void ImGui::ClosePopupsExceptModals()
8414 {
8415     ImGuiContext& g = *GImGui;
8416 
8417     int popup_count_to_keep;
8418     for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
8419     {
8420         ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
8421         if (!window || window->Flags & ImGuiWindowFlags_Modal)
8422             break;
8423     }
8424     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
8425         ClosePopupToLevel(popup_count_to_keep, true);
8426 }
8427 
ClosePopupToLevel(int remaining,bool restore_focus_to_window_under_popup)8428 void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
8429 {
8430     ImGuiContext& g = *GImGui;
8431     IMGUI_DEBUG_LOG_POPUP("ClosePopupToLevel(%d), restore_focus_to_window_under_popup=%d\n", remaining, restore_focus_to_window_under_popup);
8432     IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
8433 
8434     // Trim open popup stack
8435     ImGuiWindow* focus_window = g.OpenPopupStack[remaining].SourceWindow;
8436     ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window;
8437     g.OpenPopupStack.resize(remaining);
8438 
8439     if (restore_focus_to_window_under_popup)
8440     {
8441         if (focus_window && !focus_window->WasActive && popup_window)
8442         {
8443             // Fallback
8444             FocusTopMostWindowUnderOne(popup_window, NULL);
8445         }
8446         else
8447         {
8448             if (g.NavLayer == ImGuiNavLayer_Main && focus_window)
8449                 focus_window = NavRestoreLastChildNavWindow(focus_window);
8450             FocusWindow(focus_window);
8451         }
8452     }
8453 }
8454 
8455 // Close the popup we have begin-ed into.
CloseCurrentPopup()8456 void ImGui::CloseCurrentPopup()
8457 {
8458     ImGuiContext& g = *GImGui;
8459     int popup_idx = g.BeginPopupStack.Size - 1;
8460     if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
8461         return;
8462 
8463     // Closing a menu closes its top-most parent popup (unless a modal)
8464     while (popup_idx > 0)
8465     {
8466         ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
8467         ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
8468         bool close_parent = false;
8469         if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
8470             if (parent_popup_window == NULL || !(parent_popup_window->Flags & ImGuiWindowFlags_Modal))
8471                 close_parent = true;
8472         if (!close_parent)
8473             break;
8474         popup_idx--;
8475     }
8476     IMGUI_DEBUG_LOG_POPUP("CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
8477     ClosePopupToLevel(popup_idx, true);
8478 
8479     // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
8480     // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
8481     // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
8482     if (ImGuiWindow* window = g.NavWindow)
8483         window->DC.NavHideHighlightOneFrame = true;
8484 }
8485 
8486 // Attention! BeginPopup() adds default flags which BeginPopupEx()!
BeginPopupEx(ImGuiID id,ImGuiWindowFlags flags)8487 bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags)
8488 {
8489     ImGuiContext& g = *GImGui;
8490     if (!IsPopupOpen(id, ImGuiPopupFlags_None))
8491     {
8492         g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
8493         return false;
8494     }
8495 
8496     char name[20];
8497     if (flags & ImGuiWindowFlags_ChildMenu)
8498         ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginPopupStack.Size); // Recycle windows based on depth
8499     else
8500         ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
8501 
8502     flags |= ImGuiWindowFlags_Popup;
8503     bool is_open = Begin(name, NULL, flags);
8504     if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
8505         EndPopup();
8506 
8507     return is_open;
8508 }
8509 
BeginPopup(const char * str_id,ImGuiWindowFlags flags)8510 bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
8511 {
8512     ImGuiContext& g = *GImGui;
8513     if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
8514     {
8515         g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
8516         return false;
8517     }
8518     flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
8519     return BeginPopupEx(g.CurrentWindow->GetID(str_id), flags);
8520 }
8521 
8522 // If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
8523 // Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup) so the actual value of *p_open is meaningless here.
BeginPopupModal(const char * name,bool * p_open,ImGuiWindowFlags flags)8524 bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
8525 {
8526     ImGuiContext& g = *GImGui;
8527     ImGuiWindow* window = g.CurrentWindow;
8528     const ImGuiID id = window->GetID(name);
8529     if (!IsPopupOpen(id, ImGuiPopupFlags_None))
8530     {
8531         g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
8532         return false;
8533     }
8534 
8535     // Center modal windows by default for increased visibility
8536     // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
8537     // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
8538     if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
8539     {
8540         const ImGuiViewport* viewport = GetMainViewport();
8541         SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
8542     }
8543 
8544     flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse;
8545     const bool is_open = Begin(name, p_open, flags);
8546     if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
8547     {
8548         EndPopup();
8549         if (is_open)
8550             ClosePopupToLevel(g.BeginPopupStack.Size, true);
8551         return false;
8552     }
8553     return is_open;
8554 }
8555 
EndPopup()8556 void ImGui::EndPopup()
8557 {
8558     ImGuiContext& g = *GImGui;
8559     ImGuiWindow* window = g.CurrentWindow;
8560     IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup);  // Mismatched BeginPopup()/EndPopup() calls
8561     IM_ASSERT(g.BeginPopupStack.Size > 0);
8562 
8563     // 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)
8564     if (g.NavWindow == window)
8565         NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
8566 
8567     // Child-popups don't need to be laid out
8568     IM_ASSERT(g.WithinEndChild == false);
8569     if (window->Flags & ImGuiWindowFlags_ChildWindow)
8570         g.WithinEndChild = true;
8571     End();
8572     g.WithinEndChild = false;
8573 }
8574 
8575 // Helper to open a popup if mouse button is released over the item
8576 // - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
OpenPopupOnItemClick(const char * str_id,ImGuiPopupFlags popup_flags)8577 void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
8578 {
8579     ImGuiContext& g = *GImGui;
8580     ImGuiWindow* window = g.CurrentWindow;
8581     int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
8582     if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
8583     {
8584         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!
8585         IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
8586         OpenPopupEx(id, popup_flags);
8587     }
8588 }
8589 
8590 // This is a helper to handle the simplest case of associating one named popup to one given widget.
8591 // - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
8592 // - To create a popup with a specific identifier, pass it in str_id.
8593 //    - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
8594 //    - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
8595 // - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
8596 //   This is essentially the same as:
8597 //       id = str_id ? GetID(str_id) : GetItemID();
8598 //       OpenPopupOnItemClick(str_id);
8599 //       return BeginPopup(id);
8600 //   Which is essentially the same as:
8601 //       id = str_id ? GetID(str_id) : GetItemID();
8602 //       if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
8603 //           OpenPopup(id);
8604 //       return BeginPopup(id);
8605 //   The main difference being that this is tweaked to avoid computing the ID twice.
BeginPopupContextItem(const char * str_id,ImGuiPopupFlags popup_flags)8606 bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
8607 {
8608     ImGuiContext& g = *GImGui;
8609     ImGuiWindow* window = g.CurrentWindow;
8610     if (window->SkipItems)
8611         return false;
8612     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!
8613     IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
8614     int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
8615     if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
8616         OpenPopupEx(id, popup_flags);
8617     return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
8618 }
8619 
BeginPopupContextWindow(const char * str_id,ImGuiPopupFlags popup_flags)8620 bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
8621 {
8622     ImGuiContext& g = *GImGui;
8623     ImGuiWindow* window = g.CurrentWindow;
8624     if (!str_id)
8625         str_id = "window_context";
8626     ImGuiID id = window->GetID(str_id);
8627     int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
8628     if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
8629         if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
8630             OpenPopupEx(id, popup_flags);
8631     return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
8632 }
8633 
BeginPopupContextVoid(const char * str_id,ImGuiPopupFlags popup_flags)8634 bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
8635 {
8636     ImGuiContext& g = *GImGui;
8637     ImGuiWindow* window = g.CurrentWindow;
8638     if (!str_id)
8639         str_id = "void_context";
8640     ImGuiID id = window->GetID(str_id);
8641     int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
8642     if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
8643         if (GetTopMostPopupModal() == NULL)
8644             OpenPopupEx(id, popup_flags);
8645     return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
8646 }
8647 
8648 // 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.)
8649 // 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.
8650 // (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
8651 //  information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
8652 //  this allows us to have tooltips/popups displayed out of the parent viewport.)
FindBestWindowPosForPopupEx(const ImVec2 & ref_pos,const ImVec2 & size,ImGuiDir * last_dir,const ImRect & r_outer,const ImRect & r_avoid,ImGuiPopupPositionPolicy policy)8653 ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
8654 {
8655     ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
8656     //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
8657     //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
8658 
8659     // Combo Box policy (we want a connecting edge)
8660     if (policy == ImGuiPopupPositionPolicy_ComboBox)
8661     {
8662         const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
8663         for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
8664         {
8665             const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
8666             if (n != -1 && dir == *last_dir) // Already tried this direction?
8667                 continue;
8668             ImVec2 pos;
8669             if (dir == ImGuiDir_Down)  pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y);          // Below, Toward Right (default)
8670             if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
8671             if (dir == ImGuiDir_Left)  pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
8672             if (dir == ImGuiDir_Up)    pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
8673             if (!r_outer.Contains(ImRect(pos, pos + size)))
8674                 continue;
8675             *last_dir = dir;
8676             return pos;
8677         }
8678     }
8679 
8680     // Tooltip and Default popup policy
8681     // (Always first try the direction we used on the last frame, if any)
8682     if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
8683     {
8684         const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
8685         for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
8686         {
8687             const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
8688             if (n != -1 && dir == *last_dir) // Already tried this direction?
8689                 continue;
8690 
8691             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);
8692             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);
8693 
8694             // If there 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)
8695             if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
8696                 continue;
8697             if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
8698                 continue;
8699 
8700             ImVec2 pos;
8701             pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
8702             pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
8703 
8704             // Clamp top-left corner of popup
8705             pos.x = ImMax(pos.x, r_outer.Min.x);
8706             pos.y = ImMax(pos.y, r_outer.Min.y);
8707 
8708             *last_dir = dir;
8709             return pos;
8710         }
8711     }
8712 
8713     // Fallback when not enough room:
8714     *last_dir = ImGuiDir_None;
8715 
8716     // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
8717     if (policy == ImGuiPopupPositionPolicy_Tooltip)
8718         return ref_pos + ImVec2(2, 2);
8719 
8720     // Otherwise try to keep within display
8721     ImVec2 pos = ref_pos;
8722     pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
8723     pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
8724     return pos;
8725 }
8726 
8727 // Note that this is used for popups, which can overlap the non work-area of individual viewports.
GetPopupAllowedExtentRect(ImGuiWindow * window)8728 ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
8729 {
8730     ImGuiContext& g = *GImGui;
8731     IM_UNUSED(window);
8732     ImRect r_screen = ((ImGuiViewportP*)(void*)GetMainViewport())->GetMainRect();
8733     ImVec2 padding = g.Style.DisplaySafeAreaPadding;
8734     r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
8735     return r_screen;
8736 }
8737 
FindBestWindowPosForPopup(ImGuiWindow * window)8738 ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
8739 {
8740     ImGuiContext& g = *GImGui;
8741 
8742     ImRect r_outer = GetPopupAllowedExtentRect(window);
8743     if (window->Flags & ImGuiWindowFlags_ChildMenu)
8744     {
8745         // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
8746         // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
8747         IM_ASSERT(g.CurrentWindow == window);
8748         ImGuiWindow* parent_window = g.CurrentWindowStack[g.CurrentWindowStack.Size - 2].Window;
8749         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).
8750         ImRect r_avoid;
8751         if (parent_window->DC.MenuBarAppending)
8752             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
8753         else
8754             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);
8755         return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
8756     }
8757     if (window->Flags & ImGuiWindowFlags_Popup)
8758     {
8759         ImRect r_avoid = ImRect(window->Pos.x - 1, window->Pos.y - 1, window->Pos.x + 1, window->Pos.y + 1);
8760         return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
8761     }
8762     if (window->Flags & ImGuiWindowFlags_Tooltip)
8763     {
8764         // Position tooltip (always follows mouse)
8765         float sc = g.Style.MouseCursorScale;
8766         ImVec2 ref_pos = NavCalcPreferredRefPos();
8767         ImRect r_avoid;
8768         if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
8769             r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
8770         else
8771             r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * sc, ref_pos.y + 24 * sc); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
8772         return FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
8773     }
8774     IM_ASSERT(0);
8775     return window->Pos;
8776 }
8777 
8778 //-----------------------------------------------------------------------------
8779 // [SECTION] KEYBOARD/GAMEPAD NAVIGATION
8780 //-----------------------------------------------------------------------------
8781 
8782 // FIXME-NAV: The existence of SetNavID vs SetFocusID properly needs to be clarified/reworked.
8783 // In our terminology those should be interchangeable. Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
SetNavID(ImGuiID id,ImGuiNavLayer nav_layer,ImGuiID focus_scope_id,const ImRect & rect_rel)8784 void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
8785 {
8786     ImGuiContext& g = *GImGui;
8787     IM_ASSERT(g.NavWindow != NULL);
8788     IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
8789     g.NavId = id;
8790     g.NavLayer = nav_layer;
8791     g.NavFocusScopeId = focus_scope_id;
8792     g.NavWindow->NavLastIds[nav_layer] = id;
8793     g.NavWindow->NavRectRel[nav_layer] = rect_rel;
8794     //g.NavDisableHighlight = false;
8795     //g.NavDisableMouseHover = g.NavMousePosDirty = true;
8796 }
8797 
SetFocusID(ImGuiID id,ImGuiWindow * window)8798 void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
8799 {
8800     ImGuiContext& g = *GImGui;
8801     IM_ASSERT(id != 0);
8802 
8803     // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and window->DC.NavFocusScopeIdCurrent are valid.
8804     // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
8805     const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
8806     if (g.NavWindow != window)
8807         g.NavInitRequest = false;
8808     g.NavWindow = window;
8809     g.NavId = id;
8810     g.NavLayer = nav_layer;
8811     g.NavFocusScopeId = window->DC.NavFocusScopeIdCurrent;
8812     window->NavLastIds[nav_layer] = id;
8813     if (g.LastItemData.ID == id)
8814         window->NavRectRel[nav_layer] = ImRect(g.LastItemData.NavRect.Min - window->Pos, g.LastItemData.NavRect.Max - window->Pos);
8815 
8816     if (g.ActiveIdSource == ImGuiInputSource_Nav)
8817         g.NavDisableMouseHover = true;
8818     else
8819         g.NavDisableHighlight = true;
8820 }
8821 
ImGetDirQuadrantFromDelta(float dx,float dy)8822 ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
8823 {
8824     if (ImFabs(dx) > ImFabs(dy))
8825         return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
8826     return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
8827 }
8828 
NavScoreItemDistInterval(float a0,float a1,float b0,float b1)8829 static float inline NavScoreItemDistInterval(float a0, float a1, float b0, float b1)
8830 {
8831     if (a1 < b0)
8832         return a1 - b0;
8833     if (b1 < a0)
8834         return a0 - b1;
8835     return 0.0f;
8836 }
8837 
NavClampRectToVisibleAreaForMoveDir(ImGuiDir move_dir,ImRect & r,const ImRect & clip_rect)8838 static void inline NavClampRectToVisibleAreaForMoveDir(ImGuiDir move_dir, ImRect& r, const ImRect& clip_rect)
8839 {
8840     if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
8841     {
8842         r.Min.y = ImClamp(r.Min.y, clip_rect.Min.y, clip_rect.Max.y);
8843         r.Max.y = ImClamp(r.Max.y, clip_rect.Min.y, clip_rect.Max.y);
8844     }
8845     else // FIXME: PageUp/PageDown are leaving move_dir == None
8846     {
8847         r.Min.x = ImClamp(r.Min.x, clip_rect.Min.x, clip_rect.Max.x);
8848         r.Max.x = ImClamp(r.Max.x, clip_rect.Min.x, clip_rect.Max.x);
8849     }
8850 }
8851 
8852 // Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
NavScoreItem(ImGuiNavItemData * result)8853 static bool ImGui::NavScoreItem(ImGuiNavItemData* result)
8854 {
8855     ImGuiContext& g = *GImGui;
8856     ImGuiWindow* window = g.CurrentWindow;
8857     if (g.NavLayer != window->DC.NavLayerCurrent)
8858         return false;
8859 
8860     // FIXME: Those are not good variables names
8861     ImRect cand = g.LastItemData.NavRect;   // Current item nav rectangle
8862     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)
8863     g.NavScoringDebugCount++;
8864 
8865     // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
8866     if (window->ParentWindow == g.NavWindow)
8867     {
8868         IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
8869         if (!window->ClipRect.Overlaps(cand))
8870             return false;
8871         cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
8872     }
8873 
8874     // We perform scoring on items bounding box clipped by the current clipping rectangle on the other axis (clipping on our movement axis would give us equal scores for all clipped items)
8875     // For example, this ensure that items in one column are not reached when moving vertically from items in another column.
8876     NavClampRectToVisibleAreaForMoveDir(g.NavMoveClipDir, cand, window->ClipRect);
8877 
8878     // Compute distance between boxes
8879     // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
8880     float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
8881     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
8882     if (dby != 0.0f && dbx != 0.0f)
8883         dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
8884     float dist_box = ImFabs(dbx) + ImFabs(dby);
8885 
8886     // 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)
8887     float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
8888     float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
8889     float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
8890 
8891     // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
8892     ImGuiDir quadrant;
8893     float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
8894     if (dbx != 0.0f || dby != 0.0f)
8895     {
8896         // For non-overlapping boxes, use distance between boxes
8897         dax = dbx;
8898         day = dby;
8899         dist_axial = dist_box;
8900         quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
8901     }
8902     else if (dcx != 0.0f || dcy != 0.0f)
8903     {
8904         // For overlapping boxes with different centers, use distance between centers
8905         dax = dcx;
8906         day = dcy;
8907         dist_axial = dist_center;
8908         quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
8909     }
8910     else
8911     {
8912         // 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)
8913         quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
8914     }
8915 
8916 #if IMGUI_DEBUG_NAV_SCORING
8917     char buf[128];
8918     if (IsMouseHoveringRect(cand.Min, cand.Max))
8919     {
8920         ImFormatString(buf, IM_ARRAYSIZE(buf), "dbox (%.2f,%.2f->%.4f)\ndcen (%.2f,%.2f->%.4f)\nd (%.2f,%.2f->%.4f)\nnav %c, quadrant %c", dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "WENS"[g.NavMoveDir], "WENS"[quadrant]);
8921         ImDrawList* draw_list = GetForegroundDrawList(window);
8922         draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255,200,0,100));
8923         draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200));
8924         draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40,0,0,150));
8925         draw_list->AddText(cand.Max, ~0U, buf);
8926     }
8927     else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate.
8928     {
8929         if (quadrant == g.NavMoveDir)
8930         {
8931             ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
8932             ImDrawList* draw_list = GetForegroundDrawList(window);
8933             draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 200));
8934             draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
8935         }
8936     }
8937 #endif
8938 
8939     // Is it in the quadrant we're interesting in moving to?
8940     bool new_best = false;
8941     const ImGuiDir move_dir = g.NavMoveDir;
8942     if (quadrant == move_dir)
8943     {
8944         // Does it beat the current best candidate?
8945         if (dist_box < result->DistBox)
8946         {
8947             result->DistBox = dist_box;
8948             result->DistCenter = dist_center;
8949             return true;
8950         }
8951         if (dist_box == result->DistBox)
8952         {
8953             // Try using distance between center points to break ties
8954             if (dist_center < result->DistCenter)
8955             {
8956                 result->DistCenter = dist_center;
8957                 new_best = true;
8958             }
8959             else if (dist_center == result->DistCenter)
8960             {
8961                 // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
8962                 // (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),
8963                 // 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.
8964                 if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
8965                     new_best = true;
8966             }
8967         }
8968     }
8969 
8970     // 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
8971     // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
8972     // 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.
8973     // 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.
8974     // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
8975     if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial)  // Check axial match
8976         if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
8977             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))
8978             {
8979                 result->DistAxial = dist_axial;
8980                 new_best = true;
8981             }
8982 
8983     return new_best;
8984 }
8985 
NavApplyItemToResult(ImGuiNavItemData * result)8986 static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
8987 {
8988     ImGuiContext& g = *GImGui;
8989     ImGuiWindow* window = g.CurrentWindow;
8990     result->Window = window;
8991     result->ID = g.LastItemData.ID;
8992     result->FocusScopeId = window->DC.NavFocusScopeIdCurrent;
8993     result->InFlags = g.LastItemData.InFlags;
8994     result->RectRel = ImRect(g.LastItemData.NavRect.Min - window->Pos, g.LastItemData.NavRect.Max - window->Pos);
8995 }
8996 
8997 // We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
8998 // This is called after LastItemData is set.
NavProcessItem()8999 static void ImGui::NavProcessItem()
9000 {
9001     ImGuiContext& g = *GImGui;
9002     ImGuiWindow* window = g.CurrentWindow;
9003     const ImGuiID id = g.LastItemData.ID;
9004     const ImRect nav_bb = g.LastItemData.NavRect;
9005     const ImGuiItemFlags item_flags = g.LastItemData.InFlags;
9006 
9007     // Process Init Request
9008     if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent)
9009     {
9010         // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
9011         const bool candidate_for_nav_default_focus = (item_flags & (ImGuiItemFlags_NoNavDefaultFocus | ImGuiItemFlags_Disabled)) == 0;
9012         if (candidate_for_nav_default_focus || g.NavInitResultId == 0)
9013         {
9014             g.NavInitResultId = id;
9015             g.NavInitResultRectRel = ImRect(nav_bb.Min - window->Pos, nav_bb.Max - window->Pos);
9016         }
9017         if (candidate_for_nav_default_focus)
9018         {
9019             g.NavInitRequest = false; // Found a match, clear request
9020             NavUpdateAnyRequestFlag();
9021         }
9022     }
9023 
9024     // Process Move Request (scoring for navigation)
9025     // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
9026     if (g.NavMoveScoringItems)
9027     {
9028         if (item_flags & ImGuiItemFlags_Inputable)
9029             g.NavTabbingInputableRemaining--;
9030 
9031         if ((g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & (ImGuiItemFlags_Disabled | ImGuiItemFlags_NoNav)))
9032         {
9033             ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
9034 
9035             if (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing)
9036             {
9037                 if (g.NavTabbingInputableRemaining == 0)
9038                     NavMoveRequestResolveWithLastItem();
9039             }
9040             else
9041             {
9042                 if (NavScoreItem(result))
9043                     NavApplyItemToResult(result);
9044 
9045                 // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
9046                 const float VISIBLE_RATIO = 0.70f;
9047                 if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
9048                     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)
9049                         if (NavScoreItem(&g.NavMoveResultLocalVisible))
9050                             NavApplyItemToResult(&g.NavMoveResultLocalVisible);
9051             }
9052         }
9053     }
9054 
9055     // Update window-relative bounding box of navigated item
9056     if (g.NavId == id)
9057     {
9058         g.NavWindow = window;                                           // Always refresh g.NavWindow, because some operations such as FocusItem() don't have a window.
9059         g.NavLayer = window->DC.NavLayerCurrent;
9060         g.NavFocusScopeId = window->DC.NavFocusScopeIdCurrent;
9061         g.NavIdIsAlive = true;
9062         window->NavRectRel[window->DC.NavLayerCurrent] = ImRect(nav_bb.Min - window->Pos, nav_bb.Max - window->Pos);    // Store item bounding box (relative to window position)
9063     }
9064 }
9065 
NavMoveRequestButNoResultYet()9066 bool ImGui::NavMoveRequestButNoResultYet()
9067 {
9068     ImGuiContext& g = *GImGui;
9069     return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
9070 }
9071 
9072 // FIXME: ScoringRect is not set
NavMoveRequestSubmit(ImGuiDir move_dir,ImGuiDir clip_dir,ImGuiNavMoveFlags move_flags,ImGuiScrollFlags scroll_flags)9073 void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
9074 {
9075     ImGuiContext& g = *GImGui;
9076     IM_ASSERT(g.NavWindow != NULL);
9077 
9078     if (move_flags & ImGuiNavMoveFlags_Tabbing)
9079         move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
9080 
9081     g.NavMoveSubmitted = g.NavMoveScoringItems = true;
9082     g.NavMoveDir = move_dir;
9083     g.NavMoveDirForDebug = move_dir;
9084     g.NavMoveClipDir = clip_dir;
9085     g.NavMoveFlags = move_flags;
9086     g.NavMoveScrollFlags = scroll_flags;
9087     g.NavMoveForwardToNextFrame = false;
9088     g.NavMoveKeyMods = g.IO.KeyMods;
9089     g.NavTabbingInputableRemaining = 0;
9090     g.NavMoveResultLocal.Clear();
9091     g.NavMoveResultLocalVisible.Clear();
9092     g.NavMoveResultOther.Clear();
9093     NavUpdateAnyRequestFlag();
9094 }
9095 
NavMoveRequestResolveWithLastItem()9096 void ImGui::NavMoveRequestResolveWithLastItem()
9097 {
9098     ImGuiContext& g = *GImGui;
9099     g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
9100     NavApplyItemToResult(&g.NavMoveResultLocal);
9101     NavUpdateAnyRequestFlag();
9102 }
9103 
NavMoveRequestCancel()9104 void ImGui::NavMoveRequestCancel()
9105 {
9106     ImGuiContext& g = *GImGui;
9107     g.NavMoveSubmitted = g.NavMoveScoringItems = false;
9108     NavUpdateAnyRequestFlag();
9109 }
9110 
9111 // Forward will reuse the move request again on the next frame (generally with modifications done to it)
NavMoveRequestForward(ImGuiDir move_dir,ImGuiDir clip_dir,ImGuiNavMoveFlags move_flags,ImGuiScrollFlags scroll_flags)9112 void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
9113 {
9114     ImGuiContext& g = *GImGui;
9115     IM_ASSERT(g.NavMoveForwardToNextFrame == false);
9116     NavMoveRequestCancel();
9117     g.NavMoveForwardToNextFrame = true;
9118     g.NavMoveDir = move_dir;
9119     g.NavMoveClipDir = clip_dir;
9120     g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
9121     g.NavMoveScrollFlags = scroll_flags;
9122 }
9123 
9124 // Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
9125 // popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
NavMoveRequestTryWrapping(ImGuiWindow * window,ImGuiNavMoveFlags wrap_flags)9126 void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
9127 {
9128     ImGuiContext& g = *GImGui;
9129     IM_ASSERT(wrap_flags != 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
9130     // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it, NavEndFrame() will do the same test
9131     if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
9132         g.NavMoveFlags |= wrap_flags;
9133 }
9134 
9135 // FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
9136 // This way we could find the last focused window among our children. It would be much less confusing this way?
NavSaveLastChildNavWindowIntoParent(ImGuiWindow * nav_window)9137 static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
9138 {
9139     ImGuiWindow* parent = nav_window;
9140     while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
9141         parent = parent->ParentWindow;
9142     if (parent && parent != nav_window)
9143         parent->NavLastChildNavWindow = nav_window;
9144 }
9145 
9146 // Restore the last focused child.
9147 // Call when we are expected to land on the Main Layer (0) after FocusWindow()
NavRestoreLastChildNavWindow(ImGuiWindow * window)9148 static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
9149 {
9150     if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
9151         return window->NavLastChildNavWindow;
9152     return window;
9153 }
9154 
NavRestoreLayer(ImGuiNavLayer layer)9155 void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
9156 {
9157     ImGuiContext& g = *GImGui;
9158     if (layer == ImGuiNavLayer_Main)
9159         g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow);
9160     ImGuiWindow* window = g.NavWindow;
9161     if (window->NavLastIds[layer] != 0)
9162     {
9163         SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
9164     }
9165     else
9166     {
9167         g.NavLayer = layer;
9168         NavInitWindow(window, true);
9169     }
9170     g.NavDisableHighlight = false;
9171     g.NavDisableMouseHover = g.NavMousePosDirty = true;
9172 }
9173 
NavUpdateAnyRequestFlag()9174 static inline void ImGui::NavUpdateAnyRequestFlag()
9175 {
9176     ImGuiContext& g = *GImGui;
9177     g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
9178     if (g.NavAnyRequest)
9179         IM_ASSERT(g.NavWindow != NULL);
9180 }
9181 
9182 // This needs to be called before we submit any widget (aka in or before Begin)
NavInitWindow(ImGuiWindow * window,bool force_reinit)9183 void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
9184 {
9185     ImGuiContext& g = *GImGui;
9186     IM_ASSERT(window == g.NavWindow);
9187 
9188     if (window->Flags & ImGuiWindowFlags_NoNavInputs)
9189     {
9190         g.NavId = g.NavFocusScopeId = 0;
9191         return;
9192     }
9193 
9194     bool init_for_nav = false;
9195     if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
9196         init_for_nav = true;
9197     IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
9198     if (init_for_nav)
9199     {
9200         SetNavID(0, g.NavLayer, 0, ImRect());
9201         g.NavInitRequest = true;
9202         g.NavInitRequestFromMove = false;
9203         g.NavInitResultId = 0;
9204         g.NavInitResultRectRel = ImRect();
9205         NavUpdateAnyRequestFlag();
9206     }
9207     else
9208     {
9209         g.NavId = window->NavLastIds[0];
9210         g.NavFocusScopeId = 0;
9211     }
9212 }
9213 
NavCalcPreferredRefPos()9214 static ImVec2 ImGui::NavCalcPreferredRefPos()
9215 {
9216     ImGuiContext& g = *GImGui;
9217     if (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow)
9218     {
9219         // Mouse (we need a fallback in case the mouse becomes invalid after being used)
9220         if (IsMousePosValid(&g.IO.MousePos))
9221             return g.IO.MousePos;
9222         return g.MouseLastValidPos;
9223     }
9224     else
9225     {
9226         // When navigation is active and mouse is disabled, decide on an arbitrary position around the bottom left of the currently navigated item.
9227         const ImRect& rect_rel = g.NavWindow->NavRectRel[g.NavLayer];
9228         ImVec2 pos = g.NavWindow->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()));
9229         ImGuiViewport* viewport = GetMainViewport();
9230         return ImFloor(ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size)); // ImFloor() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
9231     }
9232 }
9233 
GetNavInputAmount(ImGuiNavInput n,ImGuiInputReadMode mode)9234 float ImGui::GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode)
9235 {
9236     ImGuiContext& g = *GImGui;
9237     if (mode == ImGuiInputReadMode_Down)
9238         return g.IO.NavInputs[n];                         // Instant, read analog input (0.0f..1.0f, as provided by user)
9239 
9240     const float t = g.IO.NavInputsDownDuration[n];
9241     if (t < 0.0f && mode == ImGuiInputReadMode_Released)  // Return 1.0f when just released, no repeat, ignore analog input.
9242         return (g.IO.NavInputsDownDurationPrev[n] >= 0.0f ? 1.0f : 0.0f);
9243     if (t < 0.0f)
9244         return 0.0f;
9245     if (mode == ImGuiInputReadMode_Pressed)               // Return 1.0f when just pressed, no repeat, ignore analog input.
9246         return (t == 0.0f) ? 1.0f : 0.0f;
9247     if (mode == ImGuiInputReadMode_Repeat)
9248         return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 0.72f, g.IO.KeyRepeatRate * 0.80f);
9249     if (mode == ImGuiInputReadMode_RepeatSlow)
9250         return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 1.25f, g.IO.KeyRepeatRate * 2.00f);
9251     if (mode == ImGuiInputReadMode_RepeatFast)
9252         return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 0.72f, g.IO.KeyRepeatRate * 0.30f);
9253     return 0.0f;
9254 }
9255 
GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources,ImGuiInputReadMode mode,float slow_factor,float fast_factor)9256 ImVec2 ImGui::GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInputReadMode mode, float slow_factor, float fast_factor)
9257 {
9258     ImVec2 delta(0.0f, 0.0f);
9259     if (dir_sources & ImGuiNavDirSourceFlags_Keyboard)
9260         delta += ImVec2(GetNavInputAmount(ImGuiNavInput_KeyRight_, mode)   - GetNavInputAmount(ImGuiNavInput_KeyLeft_,   mode), GetNavInputAmount(ImGuiNavInput_KeyDown_,   mode) - GetNavInputAmount(ImGuiNavInput_KeyUp_,   mode));
9261     if (dir_sources & ImGuiNavDirSourceFlags_PadDPad)
9262         delta += ImVec2(GetNavInputAmount(ImGuiNavInput_DpadRight, mode)   - GetNavInputAmount(ImGuiNavInput_DpadLeft,   mode), GetNavInputAmount(ImGuiNavInput_DpadDown,   mode) - GetNavInputAmount(ImGuiNavInput_DpadUp,   mode));
9263     if (dir_sources & ImGuiNavDirSourceFlags_PadLStick)
9264         delta += ImVec2(GetNavInputAmount(ImGuiNavInput_LStickRight, mode) - GetNavInputAmount(ImGuiNavInput_LStickLeft, mode), GetNavInputAmount(ImGuiNavInput_LStickDown, mode) - GetNavInputAmount(ImGuiNavInput_LStickUp, mode));
9265     if (slow_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakSlow))
9266         delta *= slow_factor;
9267     if (fast_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakFast))
9268         delta *= fast_factor;
9269     return delta;
9270 }
9271 
NavUpdate()9272 static void ImGui::NavUpdate()
9273 {
9274     ImGuiContext& g = *GImGui;
9275     ImGuiIO& io = g.IO;
9276 
9277     io.WantSetMousePos = false;
9278     //if (g.NavScoringDebugCount > 0) IMGUI_DEBUG_LOG("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);
9279 
9280     // Set input source as Gamepad when buttons are pressed (as some features differs when used with Gamepad vs Keyboard)
9281     // (do it before we map Keyboard input!)
9282     const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
9283     const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
9284     if (nav_gamepad_active && g.NavInputSource != ImGuiInputSource_Gamepad)
9285     {
9286         if (io.NavInputs[ImGuiNavInput_Activate] > 0.0f || io.NavInputs[ImGuiNavInput_Input] > 0.0f || io.NavInputs[ImGuiNavInput_Cancel] > 0.0f || io.NavInputs[ImGuiNavInput_Menu] > 0.0f
9287             || io.NavInputs[ImGuiNavInput_DpadLeft] > 0.0f || io.NavInputs[ImGuiNavInput_DpadRight] > 0.0f || io.NavInputs[ImGuiNavInput_DpadUp] > 0.0f || io.NavInputs[ImGuiNavInput_DpadDown] > 0.0f)
9288             g.NavInputSource = ImGuiInputSource_Gamepad;
9289     }
9290 
9291     // Update Keyboard->Nav inputs mapping
9292     if (nav_keyboard_active)
9293     {
9294         #define NAV_MAP_KEY(_KEY, _NAV_INPUT)  do { if (IsKeyDown(io.KeyMap[_KEY])) { io.NavInputs[_NAV_INPUT] = 1.0f; g.NavInputSource = ImGuiInputSource_Keyboard; } } while (0)
9295         NAV_MAP_KEY(ImGuiKey_Space,     ImGuiNavInput_Activate );
9296         NAV_MAP_KEY(ImGuiKey_Enter,     ImGuiNavInput_Input    );
9297         NAV_MAP_KEY(ImGuiKey_Escape,    ImGuiNavInput_Cancel   );
9298         NAV_MAP_KEY(ImGuiKey_LeftArrow, ImGuiNavInput_KeyLeft_ );
9299         NAV_MAP_KEY(ImGuiKey_RightArrow,ImGuiNavInput_KeyRight_);
9300         NAV_MAP_KEY(ImGuiKey_UpArrow,   ImGuiNavInput_KeyUp_   );
9301         NAV_MAP_KEY(ImGuiKey_DownArrow, ImGuiNavInput_KeyDown_ );
9302         if (io.KeyCtrl)
9303             io.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f;
9304         if (io.KeyShift)
9305             io.NavInputs[ImGuiNavInput_TweakFast] = 1.0f;
9306         #undef NAV_MAP_KEY
9307     }
9308     memcpy(io.NavInputsDownDurationPrev, io.NavInputsDownDuration, sizeof(io.NavInputsDownDuration));
9309     for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++)
9310         io.NavInputsDownDuration[i] = (io.NavInputs[i] > 0.0f) ? (io.NavInputsDownDuration[i] < 0.0f ? 0.0f : io.NavInputsDownDuration[i] + io.DeltaTime) : -1.0f;
9311 
9312     // Process navigation init request (select first/default focus)
9313     if (g.NavInitResultId != 0)
9314         NavInitRequestApplyResult();
9315     g.NavInitRequest = false;
9316     g.NavInitRequestFromMove = false;
9317     g.NavInitResultId = 0;
9318     g.NavJustMovedToId = 0;
9319 
9320     // Process navigation move request
9321     if (g.NavMoveSubmitted)
9322         NavMoveRequestApplyResult();
9323     g.NavTabbingInputableRemaining = 0;
9324     g.NavMoveSubmitted = g.NavMoveScoringItems = false;
9325 
9326     // Apply application mouse position movement, after we had a chance to process move request result.
9327     if (g.NavMousePosDirty && g.NavIdIsAlive)
9328     {
9329         // Set mouse position given our knowledge of the navigated item position from last frame
9330         if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
9331             if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
9332             {
9333                 io.MousePos = io.MousePosPrev = NavCalcPreferredRefPos();
9334                 io.WantSetMousePos = true;
9335                 //IMGUI_DEBUG_LOG("SetMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
9336             }
9337         g.NavMousePosDirty = false;
9338     }
9339     g.NavIdIsAlive = false;
9340     g.NavJustTabbedId = 0;
9341     IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
9342 
9343     // 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
9344     if (g.NavWindow)
9345         NavSaveLastChildNavWindowIntoParent(g.NavWindow);
9346     if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
9347         g.NavWindow->NavLastChildNavWindow = NULL;
9348 
9349     // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
9350     NavUpdateWindowing();
9351 
9352     // Set output flags for user application
9353     io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
9354     io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
9355 
9356     // Process NavCancel input (to close a popup, get back to parent, clear focus)
9357     NavUpdateCancelRequest();
9358 
9359     // Process manual activation request
9360     g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavActivateInputId = 0;
9361     g.NavActivateFlags = ImGuiActivateFlags_None;
9362     if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
9363     {
9364         bool activate_down = IsNavInputDown(ImGuiNavInput_Activate);
9365         bool input_down = IsNavInputDown(ImGuiNavInput_Input);
9366         bool activate_pressed = activate_down && IsNavInputTest(ImGuiNavInput_Activate, ImGuiInputReadMode_Pressed);
9367         bool input_pressed = input_down && IsNavInputTest(ImGuiNavInput_Input, ImGuiInputReadMode_Pressed);
9368         if (g.ActiveId == 0 && activate_pressed)
9369         {
9370             g.NavActivateId = g.NavId;
9371             g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
9372         }
9373         if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
9374         {
9375             g.NavActivateInputId = g.NavId;
9376             g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
9377         }
9378         if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_down)
9379             g.NavActivateDownId = g.NavId;
9380         if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_pressed)
9381             g.NavActivatePressedId = g.NavId;
9382     }
9383     if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
9384         g.NavDisableHighlight = true;
9385     if (g.NavActivateId != 0)
9386         IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
9387 
9388     // Process programmatic activation request
9389     // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
9390     if (g.NavNextActivateId != 0)
9391     {
9392         if (g.NavNextActivateFlags & ImGuiActivateFlags_PreferInput)
9393             g.NavActivateInputId = g.NavNextActivateId;
9394         else
9395             g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
9396         g.NavActivateFlags = g.NavNextActivateFlags;
9397     }
9398     g.NavNextActivateId = 0;
9399 
9400     // Process move requests
9401     NavUpdateCreateMoveRequest();
9402     NavUpdateAnyRequestFlag();
9403 
9404     // Scrolling
9405     if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
9406     {
9407         // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
9408         ImGuiWindow* window = g.NavWindow;
9409         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.
9410         const ImGuiDir move_dir = g.NavMoveDir;
9411         if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavHasScroll && move_dir != ImGuiDir_None)
9412         {
9413             if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
9414                 SetScrollX(window, ImFloor(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
9415             if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
9416                 SetScrollY(window, ImFloor(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
9417         }
9418 
9419         // *Normal* Manual scroll with NavScrollXXX keys
9420         // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
9421         ImVec2 scroll_dir = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down, 1.0f / 10.0f, 10.0f);
9422         if (scroll_dir.x != 0.0f && window->ScrollbarX)
9423             SetScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed));
9424         if (scroll_dir.y != 0.0f)
9425             SetScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed));
9426     }
9427 
9428     // Always prioritize mouse highlight if navigation is disabled
9429     if (!nav_keyboard_active && !nav_gamepad_active)
9430     {
9431         g.NavDisableHighlight = true;
9432         g.NavDisableMouseHover = g.NavMousePosDirty = false;
9433     }
9434 
9435     // [DEBUG]
9436     g.NavScoringDebugCount = 0;
9437 #if IMGUI_DEBUG_NAV_RECTS
9438     if (g.NavWindow)
9439     {
9440         ImDrawList* draw_list = GetForegroundDrawList(g.NavWindow);
9441         if (1) { for (int layer = 0; layer < 2; layer++) draw_list->AddRect(g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Min, g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Max, IM_COL32(255,200,0,255)); } // [DEBUG]
9442         if (1) { ImU32 col = (!g.NavWindow->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); }
9443     }
9444 #endif
9445 }
9446 
NavInitRequestApplyResult()9447 void ImGui::NavInitRequestApplyResult()
9448 {
9449     // 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)
9450     ImGuiContext& g = *GImGui;
9451     if (!g.NavWindow)
9452         return;
9453 
9454     // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
9455     // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
9456     IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", g.NavInitResultId, g.NavLayer, g.NavWindow->Name);
9457     SetNavID(g.NavInitResultId, g.NavLayer, 0, g.NavInitResultRectRel);
9458     g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
9459     if (g.NavInitRequestFromMove)
9460     {
9461         g.NavDisableHighlight = false;
9462         g.NavDisableMouseHover = g.NavMousePosDirty = true;
9463     }
9464 }
9465 
NavUpdateCreateMoveRequest()9466 void ImGui::NavUpdateCreateMoveRequest()
9467 {
9468     ImGuiContext& g = *GImGui;
9469     ImGuiIO& io = g.IO;
9470     ImGuiWindow* window = g.NavWindow;
9471 
9472     if (g.NavMoveForwardToNextFrame && window != NULL)
9473     {
9474         // 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)
9475         // (preserve most state, which were already set by the NavMoveRequestForward() function)
9476         IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
9477         IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
9478         IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
9479     }
9480     else
9481     {
9482         // Initiate directional inputs request
9483         g.NavMoveDir = ImGuiDir_None;
9484         g.NavMoveFlags = ImGuiNavMoveFlags_None;
9485         g.NavMoveScrollFlags = ImGuiScrollFlags_None;
9486         if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
9487         {
9488             const ImGuiInputReadMode read_mode = ImGuiInputReadMode_Repeat;
9489             if (!IsActiveIdUsingNavDir(ImGuiDir_Left)  && (IsNavInputTest(ImGuiNavInput_DpadLeft,  read_mode) || IsNavInputTest(ImGuiNavInput_KeyLeft_,  read_mode))) { g.NavMoveDir = ImGuiDir_Left; }
9490             if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && (IsNavInputTest(ImGuiNavInput_DpadRight, read_mode) || IsNavInputTest(ImGuiNavInput_KeyRight_, read_mode))) { g.NavMoveDir = ImGuiDir_Right; }
9491             if (!IsActiveIdUsingNavDir(ImGuiDir_Up)    && (IsNavInputTest(ImGuiNavInput_DpadUp,    read_mode) || IsNavInputTest(ImGuiNavInput_KeyUp_,    read_mode))) { g.NavMoveDir = ImGuiDir_Up; }
9492             if (!IsActiveIdUsingNavDir(ImGuiDir_Down)  && (IsNavInputTest(ImGuiNavInput_DpadDown,  read_mode) || IsNavInputTest(ImGuiNavInput_KeyDown_,  read_mode))) { g.NavMoveDir = ImGuiDir_Down; }
9493         }
9494         g.NavMoveClipDir = g.NavMoveDir;
9495     }
9496 
9497     // Update PageUp/PageDown/Home/End scroll
9498     // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
9499     const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
9500     float scoring_rect_offset_y = 0.0f;
9501     if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
9502         scoring_rect_offset_y = NavUpdatePageUpPageDown();
9503 
9504     // [DEBUG] Always send a request
9505 #if IMGUI_DEBUG_NAV_SCORING
9506     if (io.KeyCtrl && IsKeyPressedMap(ImGuiKey_C))
9507         g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
9508     if (io.KeyCtrl && g.NavMoveDir == ImGuiDir_None)
9509     {
9510         g.NavMoveDir = g.NavMoveDirForDebug;
9511         g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
9512     }
9513 #endif
9514 
9515     // Submit
9516     g.NavMoveForwardToNextFrame = false;
9517     if (g.NavMoveDir != ImGuiDir_None)
9518         NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags);
9519 
9520     // Moving with no reference triggers a init request (will be used as a fallback if the direction fails to find a match)
9521     if (g.NavMoveSubmitted && g.NavId == 0)
9522     {
9523         IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", g.NavWindow->Name, g.NavLayer);
9524         g.NavInitRequest = g.NavInitRequestFromMove = true;
9525         g.NavInitResultId = 0;
9526         g.NavDisableHighlight = false;
9527     }
9528 
9529     // When using gamepad, we project the reference nav bounding box into window visible area.
9530     // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling, since with gamepad every movements are relative
9531     // (can't focus a visible object like we can with the mouse).
9532     if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)
9533     {
9534         ImRect window_rect_rel(window->InnerRect.Min - window->Pos - ImVec2(1, 1), window->InnerRect.Max - window->Pos + ImVec2(1, 1));
9535         if (!window_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
9536         {
9537             IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel\n");
9538             float pad = window->CalcFontSize() * 0.5f;
9539             window_rect_rel.Expand(ImVec2(-ImMin(window_rect_rel.GetWidth(), pad), -ImMin(window_rect_rel.GetHeight(), pad))); // Terrible approximation for the intent of starting navigation from first fully visible item
9540             window->NavRectRel[g.NavLayer].ClipWithFull(window_rect_rel);
9541             g.NavId = g.NavFocusScopeId = 0;
9542         }
9543     }
9544 
9545     // 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)
9546     ImRect scoring_rect;
9547     if (window != NULL)
9548     {
9549         ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
9550         scoring_rect = ImRect(window->Pos + nav_rect_rel.Min, window->Pos + nav_rect_rel.Max);
9551         scoring_rect.TranslateY(scoring_rect_offset_y);
9552         scoring_rect.Min.x = ImMin(scoring_rect.Min.x + 1.0f, scoring_rect.Max.x);
9553         scoring_rect.Max.x = scoring_rect.Min.x;
9554         IM_ASSERT(!scoring_rect.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allows us to remove extraneous ImFabs() calls in NavScoreItem().
9555         //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
9556     }
9557     g.NavScoringRect = scoring_rect;
9558 }
9559 
9560 // Apply result from previous frame navigation directional move request. Always called from NavUpdate()
NavMoveRequestApplyResult()9561 void ImGui::NavMoveRequestApplyResult()
9562 {
9563     ImGuiContext& g = *GImGui;
9564 #if IMGUI_DEBUG_NAV_SCORING
9565     if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
9566         return;
9567 #endif
9568 
9569     // Select which result to use
9570     ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
9571 
9572     // In a situation when there is no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
9573     if (result == NULL)
9574     {
9575         if (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing)
9576             g.NavMoveFlags |= ImGuiNavMoveFlags_DontSetNavHighlight;
9577         if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_DontSetNavHighlight) == 0)
9578         {
9579             g.NavDisableHighlight = false;
9580             g.NavDisableMouseHover = true;
9581         }
9582         return;
9583     }
9584 
9585     // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
9586     if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
9587         if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
9588             result = &g.NavMoveResultLocalVisible;
9589 
9590     // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
9591     if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
9592         if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
9593             result = &g.NavMoveResultOther;
9594     IM_ASSERT(g.NavWindow && result->Window);
9595 
9596     // Scroll to keep newly navigated item fully into view.
9597     if (g.NavLayer == ImGuiNavLayer_Main)
9598     {
9599         ImVec2 delta_scroll;
9600         if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
9601         {
9602             // FIXME: Should remove this
9603             float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
9604             delta_scroll.y = result->Window->Scroll.y - scroll_target;
9605             SetScrollY(result->Window, scroll_target);
9606         }
9607         else
9608         {
9609             ImRect rect_abs = ImRect(result->RectRel.Min + result->Window->Pos, result->RectRel.Max + result->Window->Pos);
9610             delta_scroll = ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags);
9611         }
9612 
9613         // Offset our result position so mouse position can be applied immediately after in NavUpdate()
9614         result->RectRel.TranslateX(-delta_scroll.x);
9615         result->RectRel.TranslateY(-delta_scroll.y);
9616     }
9617 
9618     ClearActiveID();
9619     g.NavWindow = result->Window;
9620     if (g.NavId != result->ID)
9621     {
9622         // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
9623         g.NavJustMovedToId = result->ID;
9624         g.NavJustMovedToFocusScopeId = result->FocusScopeId;
9625         g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
9626     }
9627 
9628     // Focus
9629     IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
9630     SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
9631 
9632     // Tabbing: Activates Inputable or Focus non-Inputable
9633     if ((g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) && (result->InFlags & ImGuiItemFlags_Inputable))
9634     {
9635         g.NavNextActivateId = result->ID;
9636         g.NavNextActivateFlags = ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState;
9637         g.NavMoveFlags |= ImGuiNavMoveFlags_DontSetNavHighlight;
9638     }
9639 
9640     // Activate
9641     if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
9642     {
9643         g.NavNextActivateId = result->ID;
9644         g.NavNextActivateFlags = ImGuiActivateFlags_None;
9645     }
9646 
9647     // Enable nav highlight
9648     if ((g.NavMoveFlags & ImGuiNavMoveFlags_DontSetNavHighlight) == 0)
9649     {
9650         g.NavDisableHighlight = false;
9651         g.NavDisableMouseHover = g.NavMousePosDirty = true;
9652     }
9653 }
9654 
9655 // Process NavCancel input (to close a popup, get back to parent, clear focus)
9656 // FIXME: In order to support e.g. Escape to clear a selection we'll need:
9657 // - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
9658 // - 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
NavUpdateCancelRequest()9659 static void ImGui::NavUpdateCancelRequest()
9660 {
9661     ImGuiContext& g = *GImGui;
9662     if (!IsNavInputTest(ImGuiNavInput_Cancel, ImGuiInputReadMode_Pressed))
9663         return;
9664 
9665     IMGUI_DEBUG_LOG_NAV("[nav] ImGuiNavInput_Cancel\n");
9666     if (g.ActiveId != 0)
9667     {
9668         if (!IsActiveIdUsingNavInput(ImGuiNavInput_Cancel))
9669             ClearActiveID();
9670     }
9671     else if (g.NavLayer != ImGuiNavLayer_Main)
9672     {
9673         // Leave the "menu" layer
9674         NavRestoreLayer(ImGuiNavLayer_Main);
9675     }
9676     else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow)
9677     {
9678         // Exit child window
9679         ImGuiWindow* child_window = g.NavWindow;
9680         ImGuiWindow* parent_window = g.NavWindow->ParentWindow;
9681         IM_ASSERT(child_window->ChildId != 0);
9682         ImRect child_rect = child_window->Rect();
9683         FocusWindow(parent_window);
9684         SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, ImRect(child_rect.Min - parent_window->Pos, child_rect.Max - parent_window->Pos));
9685     }
9686     else if (g.OpenPopupStack.Size > 0)
9687     {
9688         // Close open popup/menu
9689         if (!(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
9690             ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
9691     }
9692     else
9693     {
9694         // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
9695         if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
9696             g.NavWindow->NavLastIds[0] = 0;
9697         g.NavId = g.NavFocusScopeId = 0;
9698     }
9699 }
9700 
9701 // Handle PageUp/PageDown/Home/End keys
9702 // Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
9703 // FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
9704 // FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
NavUpdatePageUpPageDown()9705 static float ImGui::NavUpdatePageUpPageDown()
9706 {
9707     ImGuiContext& g = *GImGui;
9708     ImGuiIO& io = g.IO;
9709 
9710     ImGuiWindow* window = g.NavWindow;
9711     if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL || g.NavLayer != ImGuiNavLayer_Main)
9712         return 0.0f;
9713 
9714     const bool page_up_held = IsKeyDown(io.KeyMap[ImGuiKey_PageUp]) && !IsActiveIdUsingKey(ImGuiKey_PageUp);
9715     const bool page_down_held = IsKeyDown(io.KeyMap[ImGuiKey_PageDown]) && !IsActiveIdUsingKey(ImGuiKey_PageDown);
9716     const bool home_pressed = IsKeyPressed(io.KeyMap[ImGuiKey_Home]) && !IsActiveIdUsingKey(ImGuiKey_Home);
9717     const bool end_pressed = IsKeyPressed(io.KeyMap[ImGuiKey_End]) && !IsActiveIdUsingKey(ImGuiKey_End);
9718     if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
9719         return 0.0f;
9720 
9721     if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavHasScroll)
9722     {
9723         // Fallback manual-scroll when window has no navigable item
9724         if (IsKeyPressed(io.KeyMap[ImGuiKey_PageUp], true))
9725             SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
9726         else if (IsKeyPressed(io.KeyMap[ImGuiKey_PageDown], true))
9727             SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
9728         else if (home_pressed)
9729             SetScrollY(window, 0.0f);
9730         else if (end_pressed)
9731             SetScrollY(window, window->ScrollMax.y);
9732     }
9733     else
9734     {
9735         ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
9736         const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
9737         float nav_scoring_rect_offset_y = 0.0f;
9738         if (IsKeyPressed(io.KeyMap[ImGuiKey_PageUp], true))
9739         {
9740             nav_scoring_rect_offset_y = -page_offset_y;
9741             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)
9742             g.NavMoveClipDir = ImGuiDir_Up;
9743             g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
9744         }
9745         else if (IsKeyPressed(io.KeyMap[ImGuiKey_PageDown], true))
9746         {
9747             nav_scoring_rect_offset_y = +page_offset_y;
9748             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)
9749             g.NavMoveClipDir = ImGuiDir_Down;
9750             g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
9751         }
9752         else if (home_pressed)
9753         {
9754             // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
9755             // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
9756             // Preserve current horizontal position if we have any.
9757             nav_rect_rel.Min.y = nav_rect_rel.Max.y = -window->Scroll.y;
9758             if (nav_rect_rel.IsInverted())
9759                 nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
9760             g.NavMoveDir = ImGuiDir_Down;
9761             g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
9762             // FIXME-NAV: MoveClipDir left to _None, intentional?
9763         }
9764         else if (end_pressed)
9765         {
9766             nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ScrollMax.y + window->SizeFull.y - window->Scroll.y;
9767             if (nav_rect_rel.IsInverted())
9768                 nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
9769             g.NavMoveDir = ImGuiDir_Up;
9770             g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
9771             // FIXME-NAV: MoveClipDir left to _None, intentional?
9772         }
9773         return nav_scoring_rect_offset_y;
9774     }
9775     return 0.0f;
9776 }
9777 
NavEndFrame()9778 static void ImGui::NavEndFrame()
9779 {
9780     ImGuiContext& g = *GImGui;
9781 
9782     // Show CTRL+TAB list window
9783     if (g.NavWindowingTarget != NULL)
9784         NavUpdateWindowingOverlay();
9785 
9786     // Perform wrap-around in menus
9787     // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
9788     ImGuiWindow* window = g.NavWindow;
9789     const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
9790     const ImGuiNavMoveFlags wanted_flags = ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY;
9791     if (window && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & wanted_flags) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
9792     {
9793         bool do_forward = false;
9794         ImRect bb_rel = window->NavRectRel[g.NavLayer];
9795         ImGuiDir clip_dir = g.NavMoveDir;
9796         if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
9797         {
9798             bb_rel.Min.x = bb_rel.Max.x =
9799                 ImMax(window->SizeFull.x, window->ContentSize.x + window->WindowPadding.x * 2.0f) - window->Scroll.x;
9800             if (move_flags & ImGuiNavMoveFlags_WrapX)
9801             {
9802                 bb_rel.TranslateY(-bb_rel.GetHeight());
9803                 clip_dir = ImGuiDir_Up;
9804             }
9805             do_forward = true;
9806         }
9807         if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
9808         {
9809             bb_rel.Min.x = bb_rel.Max.x = -window->Scroll.x;
9810             if (move_flags & ImGuiNavMoveFlags_WrapX)
9811             {
9812                 bb_rel.TranslateY(+bb_rel.GetHeight());
9813                 clip_dir = ImGuiDir_Down;
9814             }
9815             do_forward = true;
9816         }
9817         const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
9818         if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
9819         {
9820             bb_rel.Min.y = bb_rel.Max.y =
9821                 ImMax(window->SizeFull.y, window->ContentSize.y + window->WindowPadding.y * 2.0f) - window->Scroll.y + decoration_up_height;
9822             if (move_flags & ImGuiNavMoveFlags_WrapY)
9823             {
9824                 bb_rel.TranslateX(-bb_rel.GetWidth());
9825                 clip_dir = ImGuiDir_Left;
9826             }
9827             do_forward = true;
9828         }
9829         if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
9830         {
9831             bb_rel.Min.y = bb_rel.Max.y = -window->Scroll.y + decoration_up_height;
9832             if (move_flags & ImGuiNavMoveFlags_WrapY)
9833             {
9834                 bb_rel.TranslateX(+bb_rel.GetWidth());
9835                 clip_dir = ImGuiDir_Right;
9836             }
9837             do_forward = true;
9838         }
9839         if (do_forward)
9840         {
9841             window->NavRectRel[g.NavLayer] = bb_rel;
9842             NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags);
9843         }
9844     }
9845 }
9846 
FindWindowFocusIndex(ImGuiWindow * window)9847 static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
9848 {
9849     ImGuiContext& g = *GImGui;
9850     IM_UNUSED(g);
9851     int order = window->FocusOrder;
9852     IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
9853     IM_ASSERT(g.WindowsFocusOrder[order] == window);
9854     return order;
9855 }
9856 
FindWindowNavFocusable(int i_start,int i_stop,int dir)9857 static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
9858 {
9859     ImGuiContext& g = *GImGui;
9860     for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
9861         if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
9862             return g.WindowsFocusOrder[i];
9863     return NULL;
9864 }
9865 
NavUpdateWindowingHighlightWindow(int focus_change_dir)9866 static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
9867 {
9868     ImGuiContext& g = *GImGui;
9869     IM_ASSERT(g.NavWindowingTarget);
9870     if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
9871         return;
9872 
9873     const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
9874     ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
9875     if (!window_target)
9876         window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
9877     if (window_target) // Don't reset windowing target if there's a single window in the list
9878         g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
9879     g.NavWindowingToggleLayer = false;
9880 }
9881 
9882 // Windowing management mode
9883 // Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
9884 // Gamepad:  Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
NavUpdateWindowing()9885 static void ImGui::NavUpdateWindowing()
9886 {
9887     ImGuiContext& g = *GImGui;
9888     ImGuiIO& io = g.IO;
9889 
9890     ImGuiWindow* apply_focus_window = NULL;
9891     bool apply_toggle_layer = false;
9892 
9893     ImGuiWindow* modal_window = GetTopMostPopupModal();
9894     bool allow_windowing = (modal_window == NULL);
9895     if (!allow_windowing)
9896         g.NavWindowingTarget = NULL;
9897 
9898     // Fade out
9899     if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
9900     {
9901         g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f);
9902         if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
9903             g.NavWindowingTargetAnim = NULL;
9904     }
9905 
9906     // Start CTRL-TAB or Square+L/R window selection
9907     const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
9908     const bool start_windowing_with_gamepad = allow_windowing && !g.NavWindowingTarget && IsNavInputTest(ImGuiNavInput_Menu, ImGuiInputReadMode_Pressed);
9909     const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && nav_keyboard_active && io.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab);
9910     if (start_windowing_with_gamepad || start_windowing_with_keyboard)
9911         if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
9912         {
9913             g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow;
9914             g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
9915             g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer
9916             g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
9917         }
9918 
9919     // Gamepad update
9920     g.NavWindowingTimer += io.DeltaTime;
9921     if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)
9922     {
9923         // 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
9924         g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
9925 
9926         // Select window to focus
9927         const int focus_change_dir = (int)IsNavInputTest(ImGuiNavInput_FocusPrev, ImGuiInputReadMode_RepeatSlow) - (int)IsNavInputTest(ImGuiNavInput_FocusNext, ImGuiInputReadMode_RepeatSlow);
9928         if (focus_change_dir != 0)
9929         {
9930             NavUpdateWindowingHighlightWindow(focus_change_dir);
9931             g.NavWindowingHighlightAlpha = 1.0f;
9932         }
9933 
9934         // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
9935         if (!IsNavInputDown(ImGuiNavInput_Menu))
9936         {
9937             g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
9938             if (g.NavWindowingToggleLayer && g.NavWindow)
9939                 apply_toggle_layer = true;
9940             else if (!g.NavWindowingToggleLayer)
9941                 apply_focus_window = g.NavWindowingTarget;
9942             g.NavWindowingTarget = NULL;
9943         }
9944     }
9945 
9946     // Keyboard: Focus
9947     if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard)
9948     {
9949         // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
9950         g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
9951         if (IsKeyPressedMap(ImGuiKey_Tab, true))
9952             NavUpdateWindowingHighlightWindow(io.KeyShift ? +1 : -1);
9953         if (!io.KeyCtrl)
9954             apply_focus_window = g.NavWindowingTarget;
9955     }
9956 
9957     // Keyboard: Press and Release ALT to toggle menu layer
9958     // - Testing that only Alt is tested prevents Alt+Shift or AltGR from toggling menu layer.
9959     // - AltGR is normally Alt+Ctrl but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl). But even on keyboards without AltGR we don't want Alt+Ctrl to open menu anyway.
9960     if (nav_keyboard_active && io.KeyMods == ImGuiKeyModFlags_Alt && (io.KeyModsPrev & ImGuiKeyModFlags_Alt) == 0)
9961     {
9962         g.NavWindowingToggleLayer = true;
9963         g.NavInputSource = ImGuiInputSource_Keyboard;
9964     }
9965     if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard)
9966     {
9967         // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
9968         // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
9969         if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper)
9970             g.NavWindowingToggleLayer = false;
9971 
9972         // Apply layer toggle on release
9973         // Important: we don't assume that Alt was previously held in order to handle loss of focus when backend calls io.AddFocusEvent(false)
9974         // 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.
9975         if (!(io.KeyMods & ImGuiKeyModFlags_Alt) && (io.KeyModsPrev & ImGuiKeyModFlags_Alt) && g.NavWindowingToggleLayer)
9976             if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
9977                 if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev))
9978                     apply_toggle_layer = true;
9979         if (!io.KeyAlt)
9980             g.NavWindowingToggleLayer = false;
9981     }
9982 
9983     // Move window
9984     if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
9985     {
9986         ImVec2 move_delta;
9987         if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
9988             move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down);
9989         if (g.NavInputSource == ImGuiInputSource_Gamepad)
9990             move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down);
9991         if (move_delta.x != 0.0f || move_delta.y != 0.0f)
9992         {
9993             const float NAV_MOVE_SPEED = 800.0f;
9994             const float move_speed = ImFloor(NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y)); // FIXME: Doesn't handle variable framerate very well
9995             ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindow;
9996             SetWindowPos(moving_window, moving_window->Pos + move_delta * move_speed, ImGuiCond_Always);
9997             MarkIniSettingsDirty(moving_window);
9998             g.NavDisableMouseHover = true;
9999         }
10000     }
10001 
10002     // Apply final focus
10003     if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
10004     {
10005         ClearActiveID();
10006         g.NavDisableHighlight = false;
10007         g.NavDisableMouseHover = true;
10008         apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window);
10009         ClosePopupsOverWindow(apply_focus_window, false);
10010         FocusWindow(apply_focus_window);
10011         if (apply_focus_window->NavLastIds[0] == 0)
10012             NavInitWindow(apply_focus_window, false);
10013 
10014         // If the window has ONLY a menu layer (no main layer), select it directly
10015         // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
10016         // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
10017         // the target window as already been previewed once.
10018         // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
10019         // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
10020         // won't be valid.
10021         if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
10022             g.NavLayer = ImGuiNavLayer_Menu;
10023     }
10024     if (apply_focus_window)
10025         g.NavWindowingTarget = NULL;
10026 
10027     // Apply menu/layer toggle
10028     if (apply_toggle_layer && g.NavWindow)
10029     {
10030         ClearActiveID();
10031 
10032         // Move to parent menu if necessary
10033         ImGuiWindow* new_nav_window = g.NavWindow;
10034         while (new_nav_window->ParentWindow
10035             && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
10036             && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
10037             && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
10038             new_nav_window = new_nav_window->ParentWindow;
10039         if (new_nav_window != g.NavWindow)
10040         {
10041             ImGuiWindow* old_nav_window = g.NavWindow;
10042             FocusWindow(new_nav_window);
10043             new_nav_window->NavLastChildNavWindow = old_nav_window;
10044         }
10045 
10046         // Toggle layer
10047         const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
10048         if (new_nav_layer != g.NavLayer)
10049         {
10050             // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
10051             if (new_nav_layer == ImGuiNavLayer_Menu)
10052                 g.NavWindow->NavLastIds[new_nav_layer] = 0;
10053             NavRestoreLayer(new_nav_layer);
10054         }
10055     }
10056 }
10057 
10058 // Window has already passed the IsWindowNavFocusable()
GetFallbackWindowNameForWindowingList(ImGuiWindow * window)10059 static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
10060 {
10061     if (window->Flags & ImGuiWindowFlags_Popup)
10062         return "(Popup)";
10063     if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
10064         return "(Main menu bar)";
10065     return "(Untitled)";
10066 }
10067 
10068 // Overlay displayed when using CTRL+TAB. Called by EndFrame().
NavUpdateWindowingOverlay()10069 void ImGui::NavUpdateWindowingOverlay()
10070 {
10071     ImGuiContext& g = *GImGui;
10072     IM_ASSERT(g.NavWindowingTarget != NULL);
10073 
10074     if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
10075         return;
10076 
10077     if (g.NavWindowingListWindow == NULL)
10078         g.NavWindowingListWindow = FindWindowByName("###NavWindowingList");
10079     const ImGuiViewport* viewport = GetMainViewport();
10080     SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
10081     SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
10082     PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
10083     Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
10084     for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
10085     {
10086         ImGuiWindow* window = g.WindowsFocusOrder[n];
10087         IM_ASSERT(window != NULL); // Fix static analyzers
10088         if (!IsWindowNavFocusable(window))
10089             continue;
10090         const char* label = window->Name;
10091         if (label == FindRenderedTextEnd(label))
10092             label = GetFallbackWindowNameForWindowingList(window);
10093         Selectable(label, g.NavWindowingTarget == window);
10094     }
10095     End();
10096     PopStyleVar();
10097 }
10098 
10099 
10100 //-----------------------------------------------------------------------------
10101 // [SECTION] DRAG AND DROP
10102 //-----------------------------------------------------------------------------
10103 
ClearDragDrop()10104 void ImGui::ClearDragDrop()
10105 {
10106     ImGuiContext& g = *GImGui;
10107     g.DragDropActive = false;
10108     g.DragDropPayload.Clear();
10109     g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
10110     g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
10111     g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
10112     g.DragDropAcceptFrameCount = -1;
10113 
10114     g.DragDropPayloadBufHeap.clear();
10115     memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
10116 }
10117 
10118 // When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
10119 // If the item has an identifier:
10120 // - This assume/require the item to be activated (typically via ButtonBehavior).
10121 // - 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.
10122 // - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
10123 // If the item has no identifier:
10124 // - Currently always assume left mouse button.
BeginDragDropSource(ImGuiDragDropFlags flags)10125 bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
10126 {
10127     ImGuiContext& g = *GImGui;
10128     ImGuiWindow* window = g.CurrentWindow;
10129 
10130     // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
10131     // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
10132     ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
10133 
10134     bool source_drag_active = false;
10135     ImGuiID source_id = 0;
10136     ImGuiID source_parent_id = 0;
10137     if (!(flags & ImGuiDragDropFlags_SourceExtern))
10138     {
10139         source_id = g.LastItemData.ID;
10140         if (source_id != 0)
10141         {
10142             // Common path: items with ID
10143             if (g.ActiveId != source_id)
10144                 return false;
10145             if (g.ActiveIdMouseButton != -1)
10146                 mouse_button = g.ActiveIdMouseButton;
10147             if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
10148                 return false;
10149             g.ActiveIdAllowOverlap = false;
10150         }
10151         else
10152         {
10153             // Uncommon path: items without ID
10154             if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
10155                 return false;
10156             if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
10157                 return false;
10158 
10159             // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
10160             // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag, C) Swallow your programmer pride.
10161             if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
10162             {
10163                 IM_ASSERT(0);
10164                 return false;
10165             }
10166 
10167             // Magic fallback (=somehow reprehensible) to handle items with no assigned ID, e.g. Text(), Image()
10168             // We build a throwaway ID based on current ID stack + relative AABB of items in window.
10169             // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
10170             // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
10171             // Rely on keeping other window->LastItemXXX fields intact.
10172             source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect);
10173             bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id);
10174             if (is_hovered && g.IO.MouseClicked[mouse_button])
10175             {
10176                 SetActiveID(source_id, window);
10177                 FocusWindow(window);
10178             }
10179             if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
10180                 g.ActiveIdAllowOverlap = is_hovered;
10181         }
10182         if (g.ActiveId != source_id)
10183             return false;
10184         source_parent_id = window->IDStack.back();
10185         source_drag_active = IsMouseDragging(mouse_button);
10186 
10187         // Disable navigation and key inputs while dragging + cancel existing request if any
10188         SetActiveIdUsingNavAndKeys();
10189     }
10190     else
10191     {
10192         window = NULL;
10193         source_id = ImHashStr("#SourceExtern");
10194         source_drag_active = true;
10195     }
10196 
10197     if (source_drag_active)
10198     {
10199         if (!g.DragDropActive)
10200         {
10201             IM_ASSERT(source_id != 0);
10202             ClearDragDrop();
10203             ImGuiPayload& payload = g.DragDropPayload;
10204             payload.SourceId = source_id;
10205             payload.SourceParentId = source_parent_id;
10206             g.DragDropActive = true;
10207             g.DragDropSourceFlags = flags;
10208             g.DragDropMouseButton = mouse_button;
10209             if (payload.SourceId == g.ActiveId)
10210                 g.ActiveIdNoClearOnFocusLoss = true;
10211         }
10212         g.DragDropSourceFrameCount = g.FrameCount;
10213         g.DragDropWithinSource = true;
10214 
10215         if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
10216         {
10217             // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
10218             // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
10219             BeginTooltip();
10220             if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
10221             {
10222                 ImGuiWindow* tooltip_window = g.CurrentWindow;
10223                 tooltip_window->Hidden = tooltip_window->SkipItems = true;
10224                 tooltip_window->HiddenFramesCanSkipItems = 1;
10225             }
10226         }
10227 
10228         if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
10229             g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
10230 
10231         return true;
10232     }
10233     return false;
10234 }
10235 
EndDragDropSource()10236 void ImGui::EndDragDropSource()
10237 {
10238     ImGuiContext& g = *GImGui;
10239     IM_ASSERT(g.DragDropActive);
10240     IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
10241 
10242     if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
10243         EndTooltip();
10244 
10245     // Discard the drag if have not called SetDragDropPayload()
10246     if (g.DragDropPayload.DataFrameCount == -1)
10247         ClearDragDrop();
10248     g.DragDropWithinSource = false;
10249 }
10250 
10251 // Use 'cond' to choose to submit payload on drag start or every frame
SetDragDropPayload(const char * type,const void * data,size_t data_size,ImGuiCond cond)10252 bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
10253 {
10254     ImGuiContext& g = *GImGui;
10255     ImGuiPayload& payload = g.DragDropPayload;
10256     if (cond == 0)
10257         cond = ImGuiCond_Always;
10258 
10259     IM_ASSERT(type != NULL);
10260     IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
10261     IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
10262     IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
10263     IM_ASSERT(payload.SourceId != 0);                               // Not called between BeginDragDropSource() and EndDragDropSource()
10264 
10265     if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
10266     {
10267         // Copy payload
10268         ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
10269         g.DragDropPayloadBufHeap.resize(0);
10270         if (data_size > sizeof(g.DragDropPayloadBufLocal))
10271         {
10272             // Store in heap
10273             g.DragDropPayloadBufHeap.resize((int)data_size);
10274             payload.Data = g.DragDropPayloadBufHeap.Data;
10275             memcpy(payload.Data, data, data_size);
10276         }
10277         else if (data_size > 0)
10278         {
10279             // Store locally
10280             memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
10281             payload.Data = g.DragDropPayloadBufLocal;
10282             memcpy(payload.Data, data, data_size);
10283         }
10284         else
10285         {
10286             payload.Data = NULL;
10287         }
10288         payload.DataSize = (int)data_size;
10289     }
10290     payload.DataFrameCount = g.FrameCount;
10291 
10292     return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
10293 }
10294 
BeginDragDropTargetCustom(const ImRect & bb,ImGuiID id)10295 bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
10296 {
10297     ImGuiContext& g = *GImGui;
10298     if (!g.DragDropActive)
10299         return false;
10300 
10301     ImGuiWindow* window = g.CurrentWindow;
10302     ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
10303     if (hovered_window == NULL || window->RootWindow != hovered_window->RootWindow)
10304         return false;
10305     IM_ASSERT(id != 0);
10306     if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
10307         return false;
10308     if (window->SkipItems)
10309         return false;
10310 
10311     IM_ASSERT(g.DragDropWithinTarget == false);
10312     g.DragDropTargetRect = bb;
10313     g.DragDropTargetId = id;
10314     g.DragDropWithinTarget = true;
10315     return true;
10316 }
10317 
10318 // We don't use BeginDragDropTargetCustom() and duplicate its code because:
10319 // 1) we use LastItemRectHoveredRect which handles items that pushes a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
10320 // 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
10321 // Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
BeginDragDropTarget()10322 bool ImGui::BeginDragDropTarget()
10323 {
10324     ImGuiContext& g = *GImGui;
10325     if (!g.DragDropActive)
10326         return false;
10327 
10328     ImGuiWindow* window = g.CurrentWindow;
10329     if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
10330         return false;
10331     ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
10332     if (hovered_window == NULL || window->RootWindow != hovered_window->RootWindow || window->SkipItems)
10333         return false;
10334 
10335     const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
10336     ImGuiID id = g.LastItemData.ID;
10337     if (id == 0)
10338         id = window->GetIDFromRectangle(display_rect);
10339     if (g.DragDropPayload.SourceId == id)
10340         return false;
10341 
10342     IM_ASSERT(g.DragDropWithinTarget == false);
10343     g.DragDropTargetRect = display_rect;
10344     g.DragDropTargetId = id;
10345     g.DragDropWithinTarget = true;
10346     return true;
10347 }
10348 
IsDragDropPayloadBeingAccepted()10349 bool ImGui::IsDragDropPayloadBeingAccepted()
10350 {
10351     ImGuiContext& g = *GImGui;
10352     return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
10353 }
10354 
AcceptDragDropPayload(const char * type,ImGuiDragDropFlags flags)10355 const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
10356 {
10357     ImGuiContext& g = *GImGui;
10358     ImGuiWindow* window = g.CurrentWindow;
10359     ImGuiPayload& payload = g.DragDropPayload;
10360     IM_ASSERT(g.DragDropActive);                        // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
10361     IM_ASSERT(payload.DataFrameCount != -1);            // Forgot to call EndDragDropTarget() ?
10362     if (type != NULL && !payload.IsDataType(type))
10363         return NULL;
10364 
10365     // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
10366     // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
10367     const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
10368     ImRect r = g.DragDropTargetRect;
10369     float r_surface = r.GetWidth() * r.GetHeight();
10370     if (r_surface <= g.DragDropAcceptIdCurrRectSurface)
10371     {
10372         g.DragDropAcceptFlags = flags;
10373         g.DragDropAcceptIdCurr = g.DragDropTargetId;
10374         g.DragDropAcceptIdCurrRectSurface = r_surface;
10375     }
10376 
10377     // Render default drop visuals
10378     // FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
10379     payload.Preview = was_accepted_previously;
10380     flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that lives for 1 frame)
10381     if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
10382         window->DrawList->AddRect(r.Min - ImVec2(3.5f,3.5f), r.Max + ImVec2(3.5f, 3.5f), GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
10383 
10384     g.DragDropAcceptFrameCount = g.FrameCount;
10385     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()
10386     if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
10387         return NULL;
10388 
10389     return &payload;
10390 }
10391 
GetDragDropPayload()10392 const ImGuiPayload* ImGui::GetDragDropPayload()
10393 {
10394     ImGuiContext& g = *GImGui;
10395     return g.DragDropActive ? &g.DragDropPayload : NULL;
10396 }
10397 
10398 // We don't really use/need this now, but added it for the sake of consistency and because we might need it later.
EndDragDropTarget()10399 void ImGui::EndDragDropTarget()
10400 {
10401     ImGuiContext& g = *GImGui;
10402     IM_ASSERT(g.DragDropActive);
10403     IM_ASSERT(g.DragDropWithinTarget);
10404     g.DragDropWithinTarget = false;
10405 }
10406 
10407 //-----------------------------------------------------------------------------
10408 // [SECTION] LOGGING/CAPTURING
10409 //-----------------------------------------------------------------------------
10410 // All text output from the interface can be captured into tty/file/clipboard.
10411 // By default, tree nodes are automatically opened during logging.
10412 //-----------------------------------------------------------------------------
10413 
10414 // Pass text data straight to log (without being displayed)
LogTextV(ImGuiContext & g,const char * fmt,va_list args)10415 static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
10416 {
10417     if (g.LogFile)
10418     {
10419         g.LogBuffer.Buf.resize(0);
10420         g.LogBuffer.appendfv(fmt, args);
10421         ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
10422     }
10423     else
10424     {
10425         g.LogBuffer.appendfv(fmt, args);
10426     }
10427 }
10428 
LogText(const char * fmt,...)10429 void ImGui::LogText(const char* fmt, ...)
10430 {
10431     ImGuiContext& g = *GImGui;
10432     if (!g.LogEnabled)
10433         return;
10434 
10435     va_list args;
10436     va_start(args, fmt);
10437     LogTextV(g, fmt, args);
10438     va_end(args);
10439 }
10440 
LogTextV(const char * fmt,va_list args)10441 void ImGui::LogTextV(const char* fmt, va_list args)
10442 {
10443     ImGuiContext& g = *GImGui;
10444     if (!g.LogEnabled)
10445         return;
10446 
10447     LogTextV(g, fmt, args);
10448 }
10449 
10450 // Internal version that takes a position to decide on newline placement and pad items according to their depth.
10451 // We split text into individual lines to add current tree level padding
10452 // FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
LogRenderedText(const ImVec2 * ref_pos,const char * text,const char * text_end)10453 void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
10454 {
10455     ImGuiContext& g = *GImGui;
10456     ImGuiWindow* window = g.CurrentWindow;
10457 
10458     const char* prefix = g.LogNextPrefix;
10459     const char* suffix = g.LogNextSuffix;
10460     g.LogNextPrefix = g.LogNextSuffix = NULL;
10461 
10462     if (!text_end)
10463         text_end = FindRenderedTextEnd(text, text_end);
10464 
10465     const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
10466     if (ref_pos)
10467         g.LogLinePosY = ref_pos->y;
10468     if (log_new_line)
10469     {
10470         LogText(IM_NEWLINE);
10471         g.LogLineFirstItem = true;
10472     }
10473 
10474     if (prefix)
10475         LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure "##" are included here.
10476 
10477     // Re-adjust padding if we have popped out of our starting depth
10478     if (g.LogDepthRef > window->DC.TreeDepth)
10479         g.LogDepthRef = window->DC.TreeDepth;
10480     const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
10481 
10482     const char* text_remaining = text;
10483     for (;;)
10484     {
10485         // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
10486         // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
10487         const char* line_start = text_remaining;
10488         const char* line_end = ImStreolRange(line_start, text_end);
10489         const bool is_last_line = (line_end == text_end);
10490         if (line_start != line_end || !is_last_line)
10491         {
10492             const int line_length = (int)(line_end - line_start);
10493             const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
10494             LogText("%*s%.*s", indentation, "", line_length, line_start);
10495             g.LogLineFirstItem = false;
10496             if (*line_end == '\n')
10497             {
10498                 LogText(IM_NEWLINE);
10499                 g.LogLineFirstItem = true;
10500             }
10501         }
10502         if (is_last_line)
10503             break;
10504         text_remaining = line_end + 1;
10505     }
10506 
10507     if (suffix)
10508         LogRenderedText(ref_pos, suffix, suffix + strlen(suffix));
10509 }
10510 
10511 // Start logging/capturing text output
LogBegin(ImGuiLogType type,int auto_open_depth)10512 void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
10513 {
10514     ImGuiContext& g = *GImGui;
10515     ImGuiWindow* window = g.CurrentWindow;
10516     IM_ASSERT(g.LogEnabled == false);
10517     IM_ASSERT(g.LogFile == NULL);
10518     IM_ASSERT(g.LogBuffer.empty());
10519     g.LogEnabled = true;
10520     g.LogType = type;
10521     g.LogNextPrefix = g.LogNextSuffix = NULL;
10522     g.LogDepthRef = window->DC.TreeDepth;
10523     g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
10524     g.LogLinePosY = FLT_MAX;
10525     g.LogLineFirstItem = true;
10526 }
10527 
10528 // Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
LogSetNextTextDecoration(const char * prefix,const char * suffix)10529 void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
10530 {
10531     ImGuiContext& g = *GImGui;
10532     g.LogNextPrefix = prefix;
10533     g.LogNextSuffix = suffix;
10534 }
10535 
LogToTTY(int auto_open_depth)10536 void ImGui::LogToTTY(int auto_open_depth)
10537 {
10538     ImGuiContext& g = *GImGui;
10539     if (g.LogEnabled)
10540         return;
10541     IM_UNUSED(auto_open_depth);
10542 #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
10543     LogBegin(ImGuiLogType_TTY, auto_open_depth);
10544     g.LogFile = stdout;
10545 #endif
10546 }
10547 
10548 // Start logging/capturing text output to given file
LogToFile(int auto_open_depth,const char * filename)10549 void ImGui::LogToFile(int auto_open_depth, const char* filename)
10550 {
10551     ImGuiContext& g = *GImGui;
10552     if (g.LogEnabled)
10553         return;
10554 
10555     // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
10556     // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
10557     // By opening the file in binary mode "ab" we have consistent output everywhere.
10558     if (!filename)
10559         filename = g.IO.LogFilename;
10560     if (!filename || !filename[0])
10561         return;
10562     ImFileHandle f = ImFileOpen(filename, "ab");
10563     if (!f)
10564     {
10565         IM_ASSERT(0);
10566         return;
10567     }
10568 
10569     LogBegin(ImGuiLogType_File, auto_open_depth);
10570     g.LogFile = f;
10571 }
10572 
10573 // Start logging/capturing text output to clipboard
LogToClipboard(int auto_open_depth)10574 void ImGui::LogToClipboard(int auto_open_depth)
10575 {
10576     ImGuiContext& g = *GImGui;
10577     if (g.LogEnabled)
10578         return;
10579     LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
10580 }
10581 
LogToBuffer(int auto_open_depth)10582 void ImGui::LogToBuffer(int auto_open_depth)
10583 {
10584     ImGuiContext& g = *GImGui;
10585     if (g.LogEnabled)
10586         return;
10587     LogBegin(ImGuiLogType_Buffer, auto_open_depth);
10588 }
10589 
LogFinish()10590 void ImGui::LogFinish()
10591 {
10592     ImGuiContext& g = *GImGui;
10593     if (!g.LogEnabled)
10594         return;
10595 
10596     LogText(IM_NEWLINE);
10597     switch (g.LogType)
10598     {
10599     case ImGuiLogType_TTY:
10600 #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
10601         fflush(g.LogFile);
10602 #endif
10603         break;
10604     case ImGuiLogType_File:
10605         ImFileClose(g.LogFile);
10606         break;
10607     case ImGuiLogType_Buffer:
10608         break;
10609     case ImGuiLogType_Clipboard:
10610         if (!g.LogBuffer.empty())
10611             SetClipboardText(g.LogBuffer.begin());
10612         break;
10613     case ImGuiLogType_None:
10614         IM_ASSERT(0);
10615         break;
10616     }
10617 
10618     g.LogEnabled = false;
10619     g.LogType = ImGuiLogType_None;
10620     g.LogFile = NULL;
10621     g.LogBuffer.clear();
10622 }
10623 
10624 // Helper to display logging buttons
10625 // FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
LogButtons()10626 void ImGui::LogButtons()
10627 {
10628     ImGuiContext& g = *GImGui;
10629 
10630     PushID("LogButtons");
10631 #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
10632     const bool log_to_tty = Button("Log To TTY"); SameLine();
10633 #else
10634     const bool log_to_tty = false;
10635 #endif
10636     const bool log_to_file = Button("Log To File"); SameLine();
10637     const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
10638     PushAllowKeyboardFocus(false);
10639     SetNextItemWidth(80.0f);
10640     SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
10641     PopAllowKeyboardFocus();
10642     PopID();
10643 
10644     // Start logging at the end of the function so that the buttons don't appear in the log
10645     if (log_to_tty)
10646         LogToTTY();
10647     if (log_to_file)
10648         LogToFile();
10649     if (log_to_clipboard)
10650         LogToClipboard();
10651 }
10652 
10653 
10654 //-----------------------------------------------------------------------------
10655 // [SECTION] SETTINGS
10656 //-----------------------------------------------------------------------------
10657 // - UpdateSettings() [Internal]
10658 // - MarkIniSettingsDirty() [Internal]
10659 // - CreateNewWindowSettings() [Internal]
10660 // - FindWindowSettings() [Internal]
10661 // - FindOrCreateWindowSettings() [Internal]
10662 // - FindSettingsHandler() [Internal]
10663 // - ClearIniSettings() [Internal]
10664 // - LoadIniSettingsFromDisk()
10665 // - LoadIniSettingsFromMemory()
10666 // - SaveIniSettingsToDisk()
10667 // - SaveIniSettingsToMemory()
10668 // - WindowSettingsHandler_***() [Internal]
10669 //-----------------------------------------------------------------------------
10670 
10671 // Called by NewFrame()
UpdateSettings()10672 void ImGui::UpdateSettings()
10673 {
10674     // Load settings on first frame (if not explicitly loaded manually before)
10675     ImGuiContext& g = *GImGui;
10676     if (!g.SettingsLoaded)
10677     {
10678         IM_ASSERT(g.SettingsWindows.empty());
10679         if (g.IO.IniFilename)
10680             LoadIniSettingsFromDisk(g.IO.IniFilename);
10681         g.SettingsLoaded = true;
10682     }
10683 
10684     // Save settings (with a delay after the last modification, so we don't spam disk too much)
10685     if (g.SettingsDirtyTimer > 0.0f)
10686     {
10687         g.SettingsDirtyTimer -= g.IO.DeltaTime;
10688         if (g.SettingsDirtyTimer <= 0.0f)
10689         {
10690             if (g.IO.IniFilename != NULL)
10691                 SaveIniSettingsToDisk(g.IO.IniFilename);
10692             else
10693                 g.IO.WantSaveIniSettings = true;  // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
10694             g.SettingsDirtyTimer = 0.0f;
10695         }
10696     }
10697 }
10698 
MarkIniSettingsDirty()10699 void ImGui::MarkIniSettingsDirty()
10700 {
10701     ImGuiContext& g = *GImGui;
10702     if (g.SettingsDirtyTimer <= 0.0f)
10703         g.SettingsDirtyTimer = g.IO.IniSavingRate;
10704 }
10705 
MarkIniSettingsDirty(ImGuiWindow * window)10706 void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
10707 {
10708     ImGuiContext& g = *GImGui;
10709     if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
10710         if (g.SettingsDirtyTimer <= 0.0f)
10711             g.SettingsDirtyTimer = g.IO.IniSavingRate;
10712 }
10713 
CreateNewWindowSettings(const char * name)10714 ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
10715 {
10716     ImGuiContext& g = *GImGui;
10717 
10718 #if !IMGUI_DEBUG_INI_SETTINGS
10719     // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
10720     // Preserve the full string when IMGUI_DEBUG_INI_SETTINGS is set to make .ini inspection easier.
10721     if (const char* p = strstr(name, "###"))
10722         name = p;
10723 #endif
10724     const size_t name_len = strlen(name);
10725 
10726     // Allocate chunk
10727     const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
10728     ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
10729     IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
10730     settings->ID = ImHashStr(name, name_len);
10731     memcpy(settings->GetName(), name, name_len + 1);   // Store with zero terminator
10732 
10733     return settings;
10734 }
10735 
FindWindowSettings(ImGuiID id)10736 ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id)
10737 {
10738     ImGuiContext& g = *GImGui;
10739     for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
10740         if (settings->ID == id)
10741             return settings;
10742     return NULL;
10743 }
10744 
FindOrCreateWindowSettings(const char * name)10745 ImGuiWindowSettings* ImGui::FindOrCreateWindowSettings(const char* name)
10746 {
10747     if (ImGuiWindowSettings* settings = FindWindowSettings(ImHashStr(name)))
10748         return settings;
10749     return CreateNewWindowSettings(name);
10750 }
10751 
FindSettingsHandler(const char * type_name)10752 ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
10753 {
10754     ImGuiContext& g = *GImGui;
10755     const ImGuiID type_hash = ImHashStr(type_name);
10756     for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
10757         if (g.SettingsHandlers[handler_n].TypeHash == type_hash)
10758             return &g.SettingsHandlers[handler_n];
10759     return NULL;
10760 }
10761 
ClearIniSettings()10762 void ImGui::ClearIniSettings()
10763 {
10764     ImGuiContext& g = *GImGui;
10765     g.SettingsIniData.clear();
10766     for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
10767         if (g.SettingsHandlers[handler_n].ClearAllFn)
10768             g.SettingsHandlers[handler_n].ClearAllFn(&g, &g.SettingsHandlers[handler_n]);
10769 }
10770 
LoadIniSettingsFromDisk(const char * ini_filename)10771 void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
10772 {
10773     size_t file_data_size = 0;
10774     char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
10775     if (!file_data)
10776         return;
10777     LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
10778     IM_FREE(file_data);
10779 }
10780 
10781 // Zero-tolerance, no error reporting, cheap .ini parsing
LoadIniSettingsFromMemory(const char * ini_data,size_t ini_size)10782 void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
10783 {
10784     ImGuiContext& g = *GImGui;
10785     IM_ASSERT(g.Initialized);
10786     //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
10787     //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
10788 
10789     // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
10790     // 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..
10791     if (ini_size == 0)
10792         ini_size = strlen(ini_data);
10793     g.SettingsIniData.Buf.resize((int)ini_size + 1);
10794     char* const buf = g.SettingsIniData.Buf.Data;
10795     char* const buf_end = buf + ini_size;
10796     memcpy(buf, ini_data, ini_size);
10797     buf_end[0] = 0;
10798 
10799     // Call pre-read handlers
10800     // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
10801     for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
10802         if (g.SettingsHandlers[handler_n].ReadInitFn)
10803             g.SettingsHandlers[handler_n].ReadInitFn(&g, &g.SettingsHandlers[handler_n]);
10804 
10805     void* entry_data = NULL;
10806     ImGuiSettingsHandler* entry_handler = NULL;
10807 
10808     char* line_end = NULL;
10809     for (char* line = buf; line < buf_end; line = line_end + 1)
10810     {
10811         // Skip new lines markers, then find end of the line
10812         while (*line == '\n' || *line == '\r')
10813             line++;
10814         line_end = line;
10815         while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
10816             line_end++;
10817         line_end[0] = 0;
10818         if (line[0] == ';')
10819             continue;
10820         if (line[0] == '[' && line_end > line && line_end[-1] == ']')
10821         {
10822             // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
10823             line_end[-1] = 0;
10824             const char* name_end = line_end - 1;
10825             const char* type_start = line + 1;
10826             char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
10827             const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
10828             if (!type_end || !name_start)
10829                 continue;
10830             *type_end = 0; // Overwrite first ']'
10831             name_start++;  // Skip second '['
10832             entry_handler = FindSettingsHandler(type_start);
10833             entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
10834         }
10835         else if (entry_handler != NULL && entry_data != NULL)
10836         {
10837             // Let type handler parse the line
10838             entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
10839         }
10840     }
10841     g.SettingsLoaded = true;
10842 
10843     // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
10844     memcpy(buf, ini_data, ini_size);
10845 
10846     // Call post-read handlers
10847     for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
10848         if (g.SettingsHandlers[handler_n].ApplyAllFn)
10849             g.SettingsHandlers[handler_n].ApplyAllFn(&g, &g.SettingsHandlers[handler_n]);
10850 }
10851 
SaveIniSettingsToDisk(const char * ini_filename)10852 void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
10853 {
10854     ImGuiContext& g = *GImGui;
10855     g.SettingsDirtyTimer = 0.0f;
10856     if (!ini_filename)
10857         return;
10858 
10859     size_t ini_data_size = 0;
10860     const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
10861     ImFileHandle f = ImFileOpen(ini_filename, "wt");
10862     if (!f)
10863         return;
10864     ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
10865     ImFileClose(f);
10866 }
10867 
10868 // Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
SaveIniSettingsToMemory(size_t * out_size)10869 const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
10870 {
10871     ImGuiContext& g = *GImGui;
10872     g.SettingsDirtyTimer = 0.0f;
10873     g.SettingsIniData.Buf.resize(0);
10874     g.SettingsIniData.Buf.push_back(0);
10875     for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
10876     {
10877         ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n];
10878         handler->WriteAllFn(&g, handler, &g.SettingsIniData);
10879     }
10880     if (out_size)
10881         *out_size = (size_t)g.SettingsIniData.size();
10882     return g.SettingsIniData.c_str();
10883 }
10884 
WindowSettingsHandler_ClearAll(ImGuiContext * ctx,ImGuiSettingsHandler *)10885 static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
10886 {
10887     ImGuiContext& g = *ctx;
10888     for (int i = 0; i != g.Windows.Size; i++)
10889         g.Windows[i]->SettingsOffset = -1;
10890     g.SettingsWindows.clear();
10891 }
10892 
WindowSettingsHandler_ReadOpen(ImGuiContext *,ImGuiSettingsHandler *,const char * name)10893 static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
10894 {
10895     ImGuiWindowSettings* settings = ImGui::FindOrCreateWindowSettings(name);
10896     ImGuiID id = settings->ID;
10897     *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
10898     settings->ID = id;
10899     settings->WantApply = true;
10900     return (void*)settings;
10901 }
10902 
WindowSettingsHandler_ReadLine(ImGuiContext *,ImGuiSettingsHandler *,void * entry,const char * line)10903 static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
10904 {
10905     ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
10906     int x, y;
10907     int i;
10908     if (sscanf(line, "Pos=%i,%i", &x, &y) == 2)         { settings->Pos = ImVec2ih((short)x, (short)y); }
10909     else if (sscanf(line, "Size=%i,%i", &x, &y) == 2)   { settings->Size = ImVec2ih((short)x, (short)y); }
10910     else if (sscanf(line, "Collapsed=%d", &i) == 1)     { settings->Collapsed = (i != 0); }
10911 }
10912 
10913 // Apply to existing windows (if any)
WindowSettingsHandler_ApplyAll(ImGuiContext * ctx,ImGuiSettingsHandler *)10914 static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
10915 {
10916     ImGuiContext& g = *ctx;
10917     for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
10918         if (settings->WantApply)
10919         {
10920             if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
10921                 ApplyWindowSettings(window, settings);
10922             settings->WantApply = false;
10923         }
10924 }
10925 
WindowSettingsHandler_WriteAll(ImGuiContext * ctx,ImGuiSettingsHandler * handler,ImGuiTextBuffer * buf)10926 static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
10927 {
10928     // Gather data from windows that were active during this session
10929     // (if a window wasn't opened in this session we preserve its settings)
10930     ImGuiContext& g = *ctx;
10931     for (int i = 0; i != g.Windows.Size; i++)
10932     {
10933         ImGuiWindow* window = g.Windows[i];
10934         if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
10935             continue;
10936 
10937         ImGuiWindowSettings* settings = (window->SettingsOffset != -1) ? g.SettingsWindows.ptr_from_offset(window->SettingsOffset) : ImGui::FindWindowSettings(window->ID);
10938         if (!settings)
10939         {
10940             settings = ImGui::CreateNewWindowSettings(window->Name);
10941             window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
10942         }
10943         IM_ASSERT(settings->ID == window->ID);
10944         settings->Pos = ImVec2ih(window->Pos);
10945         settings->Size = ImVec2ih(window->SizeFull);
10946 
10947         settings->Collapsed = window->Collapsed;
10948     }
10949 
10950     // Write to text buffer
10951     buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
10952     for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
10953     {
10954         const char* settings_name = settings->GetName();
10955         buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
10956         buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
10957         buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
10958         buf->appendf("Collapsed=%d\n", settings->Collapsed);
10959         buf->append("\n");
10960     }
10961 }
10962 
10963 
10964 //-----------------------------------------------------------------------------
10965 // [SECTION] VIEWPORTS, PLATFORM WINDOWS
10966 //-----------------------------------------------------------------------------
10967 // - GetMainViewport()
10968 // - UpdateViewportsNewFrame() [Internal]
10969 // (this section is more complete in the 'docking' branch)
10970 //-----------------------------------------------------------------------------
10971 
GetMainViewport()10972 ImGuiViewport* ImGui::GetMainViewport()
10973 {
10974     ImGuiContext& g = *GImGui;
10975     return g.Viewports[0];
10976 }
10977 
10978 // Update viewports and monitor infos
UpdateViewportsNewFrame()10979 static void ImGui::UpdateViewportsNewFrame()
10980 {
10981     ImGuiContext& g = *GImGui;
10982     IM_ASSERT(g.Viewports.Size == 1);
10983 
10984     // Update main viewport with current platform position.
10985     // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
10986     ImGuiViewportP* main_viewport = g.Viewports[0];
10987     main_viewport->Flags = ImGuiViewportFlags_IsPlatformWindow | ImGuiViewportFlags_OwnedByApp;
10988     main_viewport->Pos = ImVec2(0.0f, 0.0f);
10989     main_viewport->Size = g.IO.DisplaySize;
10990 
10991     for (int n = 0; n < g.Viewports.Size; n++)
10992     {
10993         ImGuiViewportP* viewport = g.Viewports[n];
10994 
10995         // Lock down space taken by menu bars and status bars, reset the offset for fucntions like BeginMainMenuBar() to alter them again.
10996         viewport->WorkOffsetMin = viewport->BuildWorkOffsetMin;
10997         viewport->WorkOffsetMax = viewport->BuildWorkOffsetMax;
10998         viewport->BuildWorkOffsetMin = viewport->BuildWorkOffsetMax = ImVec2(0.0f, 0.0f);
10999         viewport->UpdateWorkRect();
11000     }
11001 }
11002 
11003 //-----------------------------------------------------------------------------
11004 // [SECTION] DOCKING
11005 //-----------------------------------------------------------------------------
11006 
11007 // (this section is filled in the 'docking' branch)
11008 
11009 
11010 //-----------------------------------------------------------------------------
11011 // [SECTION] PLATFORM DEPENDENT HELPERS
11012 //-----------------------------------------------------------------------------
11013 
11014 #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
11015 
11016 #ifdef _MSC_VER
11017 #pragma comment(lib, "user32")
11018 #pragma comment(lib, "kernel32")
11019 #endif
11020 
11021 // Win32 clipboard implementation
11022 // We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
GetClipboardTextFn_DefaultImpl(void *)11023 static const char* GetClipboardTextFn_DefaultImpl(void*)
11024 {
11025     ImGuiContext& g = *GImGui;
11026     g.ClipboardHandlerData.clear();
11027     if (!::OpenClipboard(NULL))
11028         return NULL;
11029     HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
11030     if (wbuf_handle == NULL)
11031     {
11032         ::CloseClipboard();
11033         return NULL;
11034     }
11035     if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
11036     {
11037         int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
11038         g.ClipboardHandlerData.resize(buf_len);
11039         ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
11040     }
11041     ::GlobalUnlock(wbuf_handle);
11042     ::CloseClipboard();
11043     return g.ClipboardHandlerData.Data;
11044 }
11045 
SetClipboardTextFn_DefaultImpl(void *,const char * text)11046 static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
11047 {
11048     if (!::OpenClipboard(NULL))
11049         return;
11050     const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
11051     HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
11052     if (wbuf_handle == NULL)
11053     {
11054         ::CloseClipboard();
11055         return;
11056     }
11057     WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
11058     ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
11059     ::GlobalUnlock(wbuf_handle);
11060     ::EmptyClipboard();
11061     if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
11062         ::GlobalFree(wbuf_handle);
11063     ::CloseClipboard();
11064 }
11065 
11066 #elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
11067 
11068 #include <Carbon/Carbon.h>  // Use old API to avoid need for separate .mm file
11069 static PasteboardRef main_clipboard = 0;
11070 
11071 // OSX clipboard implementation
11072 // If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
SetClipboardTextFn_DefaultImpl(void *,const char * text)11073 static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
11074 {
11075     if (!main_clipboard)
11076         PasteboardCreate(kPasteboardClipboard, &main_clipboard);
11077     PasteboardClear(main_clipboard);
11078     CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
11079     if (cf_data)
11080     {
11081         PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
11082         CFRelease(cf_data);
11083     }
11084 }
11085 
GetClipboardTextFn_DefaultImpl(void *)11086 static const char* GetClipboardTextFn_DefaultImpl(void*)
11087 {
11088     if (!main_clipboard)
11089         PasteboardCreate(kPasteboardClipboard, &main_clipboard);
11090     PasteboardSynchronize(main_clipboard);
11091 
11092     ItemCount item_count = 0;
11093     PasteboardGetItemCount(main_clipboard, &item_count);
11094     for (ItemCount i = 0; i < item_count; i++)
11095     {
11096         PasteboardItemID item_id = 0;
11097         PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
11098         CFArrayRef flavor_type_array = 0;
11099         PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
11100         for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
11101         {
11102             CFDataRef cf_data;
11103             if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
11104             {
11105                 ImGuiContext& g = *GImGui;
11106                 g.ClipboardHandlerData.clear();
11107                 int length = (int)CFDataGetLength(cf_data);
11108                 g.ClipboardHandlerData.resize(length + 1);
11109                 CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
11110                 g.ClipboardHandlerData[length] = 0;
11111                 CFRelease(cf_data);
11112                 return g.ClipboardHandlerData.Data;
11113             }
11114         }
11115     }
11116     return NULL;
11117 }
11118 
11119 #else
11120 
11121 // Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
GetClipboardTextFn_DefaultImpl(void *)11122 static const char* GetClipboardTextFn_DefaultImpl(void*)
11123 {
11124     ImGuiContext& g = *GImGui;
11125     return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
11126 }
11127 
SetClipboardTextFn_DefaultImpl(void *,const char * text)11128 static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
11129 {
11130     ImGuiContext& g = *GImGui;
11131     g.ClipboardHandlerData.clear();
11132     const char* text_end = text + strlen(text);
11133     g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
11134     memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
11135     g.ClipboardHandlerData[(int)(text_end - text)] = 0;
11136 }
11137 
11138 #endif
11139 
11140 // Win32 API IME support (for Asian languages, etc.)
11141 #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
11142 
11143 #include <imm.h>
11144 #ifdef _MSC_VER
11145 #pragma comment(lib, "imm32")
11146 #endif
11147 
ImeSetInputScreenPosFn_DefaultImpl(int x,int y)11148 static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y)
11149 {
11150     // Notify OS Input Method Editor of text input position
11151     ImGuiIO& io = ImGui::GetIO();
11152     if (HWND hwnd = (HWND)io.ImeWindowHandle)
11153         if (HIMC himc = ::ImmGetContext(hwnd))
11154         {
11155             COMPOSITIONFORM cf;
11156             cf.ptCurrentPos.x = x;
11157             cf.ptCurrentPos.y = y;
11158             cf.dwStyle = CFS_FORCE_POSITION;
11159             ::ImmSetCompositionWindow(himc, &cf);
11160             ::ImmReleaseContext(hwnd, himc);
11161         }
11162 }
11163 
11164 #else
11165 
ImeSetInputScreenPosFn_DefaultImpl(int,int)11166 static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {}
11167 
11168 #endif
11169 
11170 //-----------------------------------------------------------------------------
11171 // [SECTION] METRICS/DEBUGGER WINDOW
11172 //-----------------------------------------------------------------------------
11173 // - RenderViewportThumbnail() [Internal]
11174 // - RenderViewportsThumbnails() [Internal]
11175 // - MetricsHelpMarker() [Internal]
11176 // - ShowMetricsWindow()
11177 // - DebugNodeColumns() [Internal]
11178 // - DebugNodeDrawList() [Internal]
11179 // - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
11180 // - DebugNodeStorage() [Internal]
11181 // - DebugNodeTabBar() [Internal]
11182 // - DebugNodeViewport() [Internal]
11183 // - DebugNodeWindow() [Internal]
11184 // - DebugNodeWindowSettings() [Internal]
11185 // - DebugNodeWindowsList() [Internal]
11186 //-----------------------------------------------------------------------------
11187 
11188 #ifndef IMGUI_DISABLE_METRICS_WINDOW
11189 
DebugRenderViewportThumbnail(ImDrawList * draw_list,ImGuiViewportP * viewport,const ImRect & bb)11190 void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
11191 {
11192     ImGuiContext& g = *GImGui;
11193     ImGuiWindow* window = g.CurrentWindow;
11194 
11195     ImVec2 scale = bb.GetSize() / viewport->Size;
11196     ImVec2 off = bb.Min - viewport->Pos * scale;
11197     float alpha_mul = 1.0f;
11198     window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
11199     for (int i = 0; i != g.Windows.Size; i++)
11200     {
11201         ImGuiWindow* thumb_window = g.Windows[i];
11202         if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
11203             continue;
11204 
11205         ImRect thumb_r = thumb_window->Rect();
11206         ImRect title_r = thumb_window->TitleBarRect();
11207         thumb_r = ImRect(ImFloor(off + thumb_r.Min * scale), ImFloor(off +  thumb_r.Max * scale));
11208         title_r = ImRect(ImFloor(off + title_r.Min * scale), ImFloor(off +  ImVec2(title_r.Max.x, title_r.Min.y) * scale) + ImVec2(0,5)); // Exaggerate title bar height
11209         thumb_r.ClipWithFull(bb);
11210         title_r.ClipWithFull(bb);
11211         const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
11212         window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));
11213         window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
11214         window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
11215         window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));
11216     }
11217     draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
11218 }
11219 
RenderViewportsThumbnails()11220 static void RenderViewportsThumbnails()
11221 {
11222     ImGuiContext& g = *GImGui;
11223     ImGuiWindow* window = g.CurrentWindow;
11224 
11225     // We don't display full monitor bounds (we could, but it often looks awkward), instead we display just enough to cover all of our viewports.
11226     float SCALE = 1.0f / 8.0f;
11227     ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
11228     for (int n = 0; n < g.Viewports.Size; n++)
11229         bb_full.Add(g.Viewports[n]->GetMainRect());
11230     ImVec2 p = window->DC.CursorPos;
11231     ImVec2 off = p - bb_full.Min * SCALE;
11232     for (int n = 0; n < g.Viewports.Size; n++)
11233     {
11234         ImGuiViewportP* viewport = g.Viewports[n];
11235         ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
11236         ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
11237     }
11238     ImGui::Dummy(bb_full.GetSize() * SCALE);
11239 }
11240 
11241 // Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
MetricsHelpMarker(const char * desc)11242 static void MetricsHelpMarker(const char* desc)
11243 {
11244     ImGui::TextDisabled("(?)");
11245     if (ImGui::IsItemHovered())
11246     {
11247         ImGui::BeginTooltip();
11248         ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
11249         ImGui::TextUnformatted(desc);
11250         ImGui::PopTextWrapPos();
11251         ImGui::EndTooltip();
11252     }
11253 }
11254 
11255 #ifndef IMGUI_DISABLE_DEMO_WINDOWS
11256 namespace ImGui { void ShowFontAtlas(ImFontAtlas* atlas); }
11257 #endif
11258 
ShowMetricsWindow(bool * p_open)11259 void ImGui::ShowMetricsWindow(bool* p_open)
11260 {
11261     ImGuiContext& g = *GImGui;
11262     ImGuiIO& io = g.IO;
11263     ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
11264     if (cfg->ShowStackTool)
11265         ShowStackToolWindow(&cfg->ShowStackTool);
11266 
11267     if (!Begin("Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
11268     {
11269         End();
11270         return;
11271     }
11272 
11273     // Basic info
11274     Text("Dear ImGui %s", GetVersion());
11275     Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
11276     Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
11277     Text("%d visible windows, %d active allocations", io.MetricsRenderWindows, io.MetricsActiveAllocations);
11278     //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
11279 
11280     Separator();
11281 
11282     // Debugging enums
11283     enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
11284     const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
11285     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
11286     const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
11287     if (cfg->ShowWindowsRectsType < 0)
11288         cfg->ShowWindowsRectsType = WRT_WorkRect;
11289     if (cfg->ShowTablesRectsType < 0)
11290         cfg->ShowTablesRectsType = TRT_WorkRect;
11291 
11292     struct Funcs
11293     {
11294         static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
11295         {
11296             if (rect_type == TRT_OuterRect)                     { return table->OuterRect; }
11297             else if (rect_type == TRT_InnerRect)                { return table->InnerRect; }
11298             else if (rect_type == TRT_WorkRect)                 { return table->WorkRect; }
11299             else if (rect_type == TRT_HostClipRect)             { return table->HostClipRect; }
11300             else if (rect_type == TRT_InnerClipRect)            { return table->InnerClipRect; }
11301             else if (rect_type == TRT_BackgroundClipRect)       { return table->BgClipRect; }
11302             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->LastOuterHeight); }
11303             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); }
11304             else if (rect_type == TRT_ColumnsClipRect)          { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
11305             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->LastFirstRowHeight); } // Note: y1/y2 not always accurate
11306             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->LastFirstRowHeight); }
11307             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->LastFirstRowHeight); }
11308             else if (rect_type == TRT_ColumnsContentUnfrozen)   { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table->LastFirstRowHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); }
11309             IM_ASSERT(0);
11310             return ImRect();
11311         }
11312 
11313         static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
11314         {
11315             if (rect_type == WRT_OuterRect)                 { return window->Rect(); }
11316             else if (rect_type == WRT_OuterRectClipped)     { return window->OuterRectClipped; }
11317             else if (rect_type == WRT_InnerRect)            { return window->InnerRect; }
11318             else if (rect_type == WRT_InnerClipRect)        { return window->InnerClipRect; }
11319             else if (rect_type == WRT_WorkRect)             { return window->WorkRect; }
11320             else if (rect_type == WRT_Content)       { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
11321             else if (rect_type == WRT_ContentIdeal)         { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
11322             else if (rect_type == WRT_ContentRegionRect)    { return window->ContentRegionRect; }
11323             IM_ASSERT(0);
11324             return ImRect();
11325         }
11326     };
11327 
11328     // Tools
11329     if (TreeNode("Tools"))
11330     {
11331         // Stack Tool is your best friend!
11332         Checkbox("Show stack tool", &cfg->ShowStackTool);
11333         SameLine();
11334         MetricsHelpMarker("You can also call ImGui::ShowStackToolWindow() from your code.");
11335 
11336         Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
11337         Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
11338         SameLine();
11339         SetNextItemWidth(GetFontSize() * 12);
11340         cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
11341         if (cfg->ShowWindowsRects && g.NavWindow != NULL)
11342         {
11343             BulletText("'%s':", g.NavWindow->Name);
11344             Indent();
11345             for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
11346             {
11347                 ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
11348                 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]);
11349             }
11350             Unindent();
11351         }
11352 
11353         Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
11354         SameLine();
11355         SetNextItemWidth(GetFontSize() * 12);
11356         cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
11357         if (cfg->ShowTablesRects && g.NavWindow != NULL)
11358         {
11359             for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
11360             {
11361                 ImGuiTable* table = g.Tables.TryGetMapData(table_n);
11362                 if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
11363                     continue;
11364 
11365                 BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
11366                 if (IsItemHovered())
11367                     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);
11368                 Indent();
11369                 char buf[128];
11370                 for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
11371                 {
11372                     if (rect_n >= TRT_ColumnsRect)
11373                     {
11374                         if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
11375                             continue;
11376                         for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
11377                         {
11378                             ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
11379                             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]);
11380                             Selectable(buf);
11381                             if (IsItemHovered())
11382                                 GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
11383                         }
11384                     }
11385                     else
11386                     {
11387                         ImRect r = Funcs::GetTableRect(table, rect_n, -1);
11388                         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]);
11389                         Selectable(buf);
11390                         if (IsItemHovered())
11391                             GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
11392                     }
11393                 }
11394                 Unindent();
11395             }
11396         }
11397 
11398         // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
11399         if (Button("Item Picker.."))
11400             DebugStartItemPicker();
11401         SameLine();
11402         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.");
11403 
11404         TreePop();
11405     }
11406 
11407     // Windows
11408     DebugNodeWindowsList(&g.Windows, "Windows");
11409     //DebugNodeWindowsList(&g.WindowsFocusOrder, "WindowsFocusOrder");
11410 
11411     // DrawLists
11412     int drawlist_count = 0;
11413     for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++)
11414         drawlist_count += g.Viewports[viewport_i]->DrawDataBuilder.GetDrawListCount();
11415     if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count))
11416     {
11417         Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
11418         Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
11419         for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++)
11420         {
11421             ImGuiViewportP* viewport = g.Viewports[viewport_i];
11422             for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
11423                 for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
11424                     DebugNodeDrawList(NULL, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
11425         }
11426         TreePop();
11427     }
11428 
11429     // Viewports
11430     if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size))
11431     {
11432         Indent(GetTreeNodeToLabelSpacing());
11433         RenderViewportsThumbnails();
11434         Unindent(GetTreeNodeToLabelSpacing());
11435         for (int i = 0; i < g.Viewports.Size; i++)
11436             DebugNodeViewport(g.Viewports[i]);
11437         TreePop();
11438     }
11439 
11440     // Details for Popups
11441     if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
11442     {
11443         for (int i = 0; i < g.OpenPopupStack.Size; i++)
11444         {
11445             ImGuiWindow* window = g.OpenPopupStack[i].Window;
11446             BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenPopupStack[i].PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : "");
11447         }
11448         TreePop();
11449     }
11450 
11451     // Details for TabBars
11452     if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetAliveCount()))
11453     {
11454         for (int n = 0; n < g.TabBars.GetMapSize(); n++)
11455             if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
11456             {
11457                 PushID(tab_bar);
11458                 DebugNodeTabBar(tab_bar, "TabBar");
11459                 PopID();
11460             }
11461         TreePop();
11462     }
11463 
11464     // Details for Tables
11465     if (TreeNode("Tables", "Tables (%d)", g.Tables.GetAliveCount()))
11466     {
11467         for (int n = 0; n < g.Tables.GetMapSize(); n++)
11468             if (ImGuiTable* table = g.Tables.TryGetMapData(n))
11469                 DebugNodeTable(table);
11470         TreePop();
11471     }
11472 
11473     // Details for Fonts
11474 #ifndef IMGUI_DISABLE_DEMO_WINDOWS
11475     ImFontAtlas* atlas = g.IO.Fonts;
11476     if (TreeNode("Fonts", "Fonts (%d)", atlas->Fonts.Size))
11477     {
11478         ShowFontAtlas(atlas);
11479         TreePop();
11480     }
11481 #endif
11482 
11483     // Details for Docking
11484 #ifdef IMGUI_HAS_DOCK
11485     if (TreeNode("Docking"))
11486     {
11487         TreePop();
11488     }
11489 #endif // #ifdef IMGUI_HAS_DOCK
11490 
11491     // Settings
11492     if (TreeNode("Settings"))
11493     {
11494         if (SmallButton("Clear"))
11495             ClearIniSettings();
11496         SameLine();
11497         if (SmallButton("Save to memory"))
11498             SaveIniSettingsToMemory();
11499         SameLine();
11500         if (SmallButton("Save to disk"))
11501             SaveIniSettingsToDisk(g.IO.IniFilename);
11502         SameLine();
11503         if (g.IO.IniFilename)
11504             Text("\"%s\"", g.IO.IniFilename);
11505         else
11506             TextUnformatted("<NULL>");
11507         Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
11508         if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
11509         {
11510             for (int n = 0; n < g.SettingsHandlers.Size; n++)
11511                 BulletText("%s", g.SettingsHandlers[n].TypeName);
11512             TreePop();
11513         }
11514         if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
11515         {
11516             for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
11517                 DebugNodeWindowSettings(settings);
11518             TreePop();
11519         }
11520 
11521         if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
11522         {
11523             for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
11524                 DebugNodeTableSettings(settings);
11525             TreePop();
11526         }
11527 
11528 #ifdef IMGUI_HAS_DOCK
11529 #endif // #ifdef IMGUI_HAS_DOCK
11530 
11531         if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
11532         {
11533             InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
11534             TreePop();
11535         }
11536         TreePop();
11537     }
11538 
11539     // Misc Details
11540     if (TreeNode("Internal state"))
11541     {
11542         const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad", "Nav", "Clipboard" }; IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT);
11543 
11544         Text("WINDOWING");
11545         Indent();
11546         Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
11547         Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindow->Name : "NULL");
11548         Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
11549         Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
11550         Unindent();
11551 
11552         Text("ITEMS");
11553         Indent();
11554         Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, input_source_names[g.ActiveIdSource]);
11555         Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
11556         Text("ActiveIdUsing: Wheel: %d, NavDirMask: %X, NavInputMask: %X, KeyInputMask: %llX", g.ActiveIdUsingMouseWheel, g.ActiveIdUsingNavDirMask, g.ActiveIdUsingNavInputMask, g.ActiveIdUsingKeyInputMask);
11557         Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame
11558         Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
11559         Unindent();
11560 
11561         Text("NAV,FOCUS");
11562         Indent();
11563         Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
11564         Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
11565         Text("NavInputSource: %s", input_source_names[g.NavInputSource]);
11566         Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
11567         Text("NavActivateId/DownId/PressedId/InputId: %08X/%08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId, g.NavActivateInputId);
11568         Text("NavActivateFlags: %04X", g.NavActivateFlags);
11569         Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
11570         Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
11571         Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
11572         Unindent();
11573 
11574         TreePop();
11575     }
11576 
11577     // Overlay: Display windows Rectangles and Begin Order
11578     if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
11579     {
11580         for (int n = 0; n < g.Windows.Size; n++)
11581         {
11582             ImGuiWindow* window = g.Windows[n];
11583             if (!window->WasActive)
11584                 continue;
11585             ImDrawList* draw_list = GetForegroundDrawList(window);
11586             if (cfg->ShowWindowsRects)
11587             {
11588                 ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
11589                 draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
11590             }
11591             if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
11592             {
11593                 char buf[32];
11594                 ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
11595                 float font_size = GetFontSize();
11596                 draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
11597                 draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
11598             }
11599         }
11600     }
11601 
11602     // Overlay: Display Tables Rectangles
11603     if (cfg->ShowTablesRects)
11604     {
11605         for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
11606         {
11607             ImGuiTable* table = g.Tables.TryGetMapData(table_n);
11608             if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
11609                 continue;
11610             ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
11611             if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
11612             {
11613                 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
11614                 {
11615                     ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
11616                     ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
11617                     float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
11618                     draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness);
11619                 }
11620             }
11621             else
11622             {
11623                 ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
11624                 draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
11625             }
11626         }
11627     }
11628 
11629 #ifdef IMGUI_HAS_DOCK
11630     // Overlay: Display Docking info
11631     if (show_docking_nodes && g.IO.KeyCtrl)
11632     {
11633     }
11634 #endif // #ifdef IMGUI_HAS_DOCK
11635 
11636     End();
11637 }
11638 
11639 // [DEBUG] List fonts in a font atlas and display its texture
ShowFontAtlas(ImFontAtlas * atlas)11640 void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
11641 {
11642     for (int i = 0; i < atlas->Fonts.Size; i++)
11643     {
11644         ImFont* font = atlas->Fonts[i];
11645         PushID(font);
11646         DebugNodeFont(font);
11647         PopID();
11648     }
11649     if (TreeNode("Atlas texture", "Atlas texture (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
11650     {
11651         ImVec4 tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
11652         ImVec4 border_col = ImVec4(1.0f, 1.0f, 1.0f, 0.5f);
11653         Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), tint_col, border_col);
11654         TreePop();
11655     }
11656 }
11657 
11658 // [DEBUG] Display contents of Columns
DebugNodeColumns(ImGuiOldColumns * columns)11659 void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
11660 {
11661     if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
11662         return;
11663     BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
11664     for (int column_n = 0; column_n < columns->Columns.Size; column_n++)
11665         BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, GetColumnOffsetFromNorm(columns, columns->Columns[column_n].OffsetNorm));
11666     TreePop();
11667 }
11668 
11669 // [DEBUG] Display contents of ImDrawList
DebugNodeDrawList(ImGuiWindow * window,const ImDrawList * draw_list,const char * label)11670 void ImGui::DebugNodeDrawList(ImGuiWindow* window, const ImDrawList* draw_list, const char* label)
11671 {
11672     ImGuiContext& g = *GImGui;
11673     ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
11674     int cmd_count = draw_list->CmdBuffer.Size;
11675     if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
11676         cmd_count--;
11677     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);
11678     if (draw_list == GetWindowDrawList())
11679     {
11680         SameLine();
11681         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)
11682         if (node_open)
11683             TreePop();
11684         return;
11685     }
11686 
11687     ImDrawList* fg_draw_list = GetForegroundDrawList(window); // Render additional visuals into the top-most draw list
11688     if (window && IsItemHovered())
11689         fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
11690     if (!node_open)
11691         return;
11692 
11693     if (window && !window->WasActive)
11694         TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
11695 
11696     for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
11697     {
11698         if (pcmd->UserCallback)
11699         {
11700             BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
11701             continue;
11702         }
11703 
11704         char buf[300];
11705         ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
11706             pcmd->ElemCount / 3, (void*)(intptr_t)pcmd->TextureId,
11707             pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
11708         bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
11709         if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
11710             DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
11711         if (!pcmd_node_open)
11712             continue;
11713 
11714         // Calculate approximate coverage area (touched pixel count)
11715         // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
11716         const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
11717         const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
11718         float total_area = 0.0f;
11719         for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
11720         {
11721             ImVec2 triangle[3];
11722             for (int n = 0; n < 3; n++, idx_n++)
11723                 triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
11724             total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
11725         }
11726 
11727         // Display vertex information summary. Hover to get all triangles drawn in wire-frame
11728         ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
11729         Selectable(buf);
11730         if (IsItemHovered() && fg_draw_list)
11731             DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);
11732 
11733         // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
11734         ImGuiListClipper clipper;
11735         clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
11736         while (clipper.Step())
11737             for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
11738             {
11739                 char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
11740                 ImVec2 triangle[3];
11741                 for (int n = 0; n < 3; n++, idx_i++)
11742                 {
11743                     const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
11744                     triangle[n] = v.pos;
11745                     buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
11746                         (n == 0) ? "Vert:" : "     ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
11747                 }
11748 
11749                 Selectable(buf, false);
11750                 if (fg_draw_list && IsItemHovered())
11751                 {
11752                     ImDrawListFlags backup_flags = fg_draw_list->Flags;
11753                     fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
11754                     fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f);
11755                     fg_draw_list->Flags = backup_flags;
11756                 }
11757             }
11758         TreePop();
11759     }
11760     TreePop();
11761 }
11762 
11763 // [DEBUG] Display mesh/aabb of a ImDrawCmd
DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList * out_draw_list,const ImDrawList * draw_list,const ImDrawCmd * draw_cmd,bool show_mesh,bool show_aabb)11764 void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
11765 {
11766     IM_ASSERT(show_mesh || show_aabb);
11767 
11768     // Draw wire-frame version of all triangles
11769     ImRect clip_rect = draw_cmd->ClipRect;
11770     ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
11771     ImDrawListFlags backup_flags = out_draw_list->Flags;
11772     out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
11773     for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
11774     {
11775         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
11776         ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
11777 
11778         ImVec2 triangle[3];
11779         for (int n = 0; n < 3; n++, idx_n++)
11780             vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
11781         if (show_mesh)
11782             out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles
11783     }
11784     // Draw bounding boxes
11785     if (show_aabb)
11786     {
11787         out_draw_list->AddRect(ImFloor(clip_rect.Min), ImFloor(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
11788         out_draw_list->AddRect(ImFloor(vtxs_rect.Min), ImFloor(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
11789     }
11790     out_draw_list->Flags = backup_flags;
11791 }
11792 
11793 // [DEBUG] Display details for a single font, called by ShowStyleEditor().
DebugNodeFont(ImFont * font)11794 void ImGui::DebugNodeFont(ImFont* font)
11795 {
11796     bool opened = TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)",
11797         font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
11798     SameLine();
11799     if (SmallButton("Set as default"))
11800         GetIO().FontDefault = font;
11801     if (!opened)
11802         return;
11803 
11804     // Display preview text
11805     PushFont(font);
11806     Text("The quick brown fox jumps over the lazy dog");
11807     PopFont();
11808 
11809     // Display details
11810     SetNextItemWidth(GetFontSize() * 8);
11811     DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f");
11812     SameLine(); MetricsHelpMarker(
11813         "Note than the default embedded font is NOT meant to be scaled.\n\n"
11814         "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
11815         "You may oversample them to get some flexibility with scaling. "
11816         "You can also render at multiple sizes and select which one to use at runtime.\n\n"
11817         "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");
11818     Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
11819     char c_str[5];
11820     Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar);
11821     Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar);
11822     const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface);
11823     Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);
11824     for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
11825         if (font->ConfigData)
11826             if (const ImFontConfig* cfg = &font->ConfigData[config_i])
11827                 BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
11828                     config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);
11829 
11830     // Display all glyphs of the fonts in separate pages of 256 characters
11831     if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
11832     {
11833         ImDrawList* draw_list = GetWindowDrawList();
11834         const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
11835         const float cell_size = font->FontSize * 1;
11836         const float cell_spacing = GetStyle().ItemSpacing.y;
11837         for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
11838         {
11839             // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
11840             // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
11841             // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
11842             if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095))
11843             {
11844                 base += 4096 - 256;
11845                 continue;
11846             }
11847 
11848             int count = 0;
11849             for (unsigned int n = 0; n < 256; n++)
11850                 if (font->FindGlyphNoFallback((ImWchar)(base + n)))
11851                     count++;
11852             if (count <= 0)
11853                 continue;
11854             if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
11855                 continue;
11856 
11857             // Draw a 16x16 grid of glyphs
11858             ImVec2 base_pos = GetCursorScreenPos();
11859             for (unsigned int n = 0; n < 256; n++)
11860             {
11861                 // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
11862                 // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
11863                 ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
11864                 ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
11865                 const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n));
11866                 draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
11867                 if (glyph)
11868                     font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
11869                 if (glyph && IsMouseHoveringRect(cell_p1, cell_p2))
11870                 {
11871                     BeginTooltip();
11872                     Text("Codepoint: U+%04X", base + n);
11873                     Separator();
11874                     Text("Visible: %d", glyph->Visible);
11875                     Text("AdvanceX: %.1f", glyph->AdvanceX);
11876                     Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
11877                     Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
11878                     EndTooltip();
11879                 }
11880             }
11881             Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
11882             TreePop();
11883         }
11884         TreePop();
11885     }
11886     TreePop();
11887 }
11888 
11889 // [DEBUG] Display contents of ImGuiStorage
DebugNodeStorage(ImGuiStorage * storage,const char * label)11890 void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
11891 {
11892     if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
11893         return;
11894     for (int n = 0; n < storage->Data.Size; n++)
11895     {
11896         const ImGuiStorage::ImGuiStoragePair& p = storage->Data[n];
11897         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.
11898     }
11899     TreePop();
11900 }
11901 
11902 // [DEBUG] Display contents of ImGuiTabBar
DebugNodeTabBar(ImGuiTabBar * tab_bar,const char * label)11903 void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
11904 {
11905     // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
11906     char buf[256];
11907     char* p = buf;
11908     const char* buf_end = buf + IM_ARRAYSIZE(buf);
11909     const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
11910     p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
11911     p += ImFormatString(p, buf_end - p, "  { ");
11912     for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
11913     {
11914         ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
11915         p += ImFormatString(p, buf_end - p, "%s'%s'",
11916             tab_n > 0 ? ", " : "", (tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "???");
11917     }
11918     p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
11919     if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
11920     bool open = TreeNode(label, "%s", buf);
11921     if (!is_active) { PopStyleColor(); }
11922     if (is_active && IsItemHovered())
11923     {
11924         ImDrawList* draw_list = GetForegroundDrawList();
11925         draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
11926         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));
11927         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));
11928     }
11929     if (open)
11930     {
11931         for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
11932         {
11933             const ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
11934             PushID(tab);
11935             if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
11936             if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
11937             Text("%02d%c Tab 0x%08X '%s' Offset: %.1f, Width: %.1f/%.1f",
11938                 tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, (tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "???", tab->Offset, tab->Width, tab->ContentWidth);
11939             PopID();
11940         }
11941         TreePop();
11942     }
11943 }
11944 
DebugNodeViewport(ImGuiViewportP * viewport)11945 void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
11946 {
11947     SetNextItemOpen(true, ImGuiCond_Once);
11948     if (TreeNode("viewport0", "Viewport #%d", 0))
11949     {
11950         ImGuiWindowFlags flags = viewport->Flags;
11951         BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f",
11952             viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
11953             viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y);
11954         BulletText("Flags: 0x%04X =%s%s%s", viewport->Flags,
11955             (flags & ImGuiViewportFlags_IsPlatformWindow)  ? " IsPlatformWindow"  : "",
11956             (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
11957             (flags & ImGuiViewportFlags_OwnedByApp)        ? " OwnedByApp"        : "");
11958         for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
11959             for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
11960                 DebugNodeDrawList(NULL, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
11961         TreePop();
11962     }
11963 }
11964 
DebugNodeWindow(ImGuiWindow * window,const char * label)11965 void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
11966 {
11967     if (window == NULL)
11968     {
11969         BulletText("%s: NULL", label);
11970         return;
11971     }
11972 
11973     ImGuiContext& g = *GImGui;
11974     const bool is_active = window->WasActive;
11975     ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
11976     if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
11977     const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
11978     if (!is_active) { PopStyleColor(); }
11979     if (IsItemHovered() && is_active)
11980         GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
11981     if (!open)
11982         return;
11983 
11984     if (window->MemoryCompacted)
11985         TextDisabled("Note: some memory buffers have been compacted/freed.");
11986 
11987     ImGuiWindowFlags flags = window->Flags;
11988     DebugNodeDrawList(window, window->DrawList, "DrawList");
11989     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);
11990     BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
11991         (flags & ImGuiWindowFlags_ChildWindow)  ? "Child " : "",      (flags & ImGuiWindowFlags_Tooltip)     ? "Tooltip "   : "",  (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
11992         (flags & ImGuiWindowFlags_Modal)        ? "Modal " : "",      (flags & ImGuiWindowFlags_ChildMenu)   ? "ChildMenu " : "",  (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
11993         (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
11994     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" : "");
11995     BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
11996     BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
11997     for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
11998     {
11999         ImRect r = window->NavRectRel[layer];
12000         if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)
12001         {
12002             BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
12003             continue;
12004         }
12005         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);
12006         if (IsItemHovered())
12007             GetForegroundDrawList(window)->AddRect(r.Min + window->Pos, r.Max + window->Pos, IM_COL32(255, 255, 0, 255));
12008     }
12009     BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
12010     if (window->RootWindow != window)       { DebugNodeWindow(window->RootWindow, "RootWindow"); }
12011     if (window->ParentWindow != NULL)       { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
12012     if (window->DC.ChildWindows.Size > 0)   { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
12013     if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
12014     {
12015         for (int n = 0; n < window->ColumnsStorage.Size; n++)
12016             DebugNodeColumns(&window->ColumnsStorage[n]);
12017         TreePop();
12018     }
12019     DebugNodeStorage(&window->StateStorage, "Storage");
12020     TreePop();
12021 }
12022 
DebugNodeWindowSettings(ImGuiWindowSettings * settings)12023 void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
12024 {
12025     Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
12026         settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
12027 }
12028 
DebugNodeWindowsList(ImVector<ImGuiWindow * > * windows,const char * label)12029 void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
12030 {
12031     if (!TreeNode(label, "%s (%d)", label, windows->Size))
12032         return;
12033     Text("(In front-to-back order:)");
12034     for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
12035     {
12036         PushID((*windows)[i]);
12037         DebugNodeWindow((*windows)[i], "Window");
12038         PopID();
12039     }
12040     TreePop();
12041 }
12042 
12043 //-----------------------------------------------------------------------------
12044 // [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, STACK TOOL)
12045 //-----------------------------------------------------------------------------
12046 
12047 // [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
UpdateDebugToolItemPicker()12048 void ImGui::UpdateDebugToolItemPicker()
12049 {
12050     ImGuiContext& g = *GImGui;
12051     g.DebugItemPickerBreakId = 0;
12052     if (!g.DebugItemPickerActive)
12053         return;
12054 
12055     const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
12056     SetMouseCursor(ImGuiMouseCursor_Hand);
12057     if (IsKeyPressedMap(ImGuiKey_Escape))
12058         g.DebugItemPickerActive = false;
12059     if (IsMouseClicked(0) && hovered_id)
12060     {
12061         g.DebugItemPickerBreakId = hovered_id;
12062         g.DebugItemPickerActive = false;
12063     }
12064     SetNextWindowBgAlpha(0.60f);
12065     BeginTooltip();
12066     Text("HoveredId: 0x%08X", hovered_id);
12067     Text("Press ESC to abort picking.");
12068     TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click to break in debugger!");
12069     EndTooltip();
12070 }
12071 
12072 // [DEBUG] Stack Tool: update queries. Called by NewFrame()
UpdateDebugToolStackQueries()12073 void ImGui::UpdateDebugToolStackQueries()
12074 {
12075     ImGuiContext& g = *GImGui;
12076     ImGuiStackTool* tool = &g.DebugStackTool;
12077 
12078     // Clear hook when stack tool is not visible
12079     g.DebugHookIdInfo = 0;
12080     if (g.FrameCount != tool->LastActiveFrame + 1)
12081         return;
12082 
12083     // Update queries. The steps are: -1: query Stack, >= 0: query each stack item
12084     // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
12085     const ImGuiID query_id = g.ActiveId ? g.ActiveId : g.HoveredIdPreviousFrame;
12086     if (tool->QueryId != query_id)
12087     {
12088         tool->QueryId = query_id;
12089         tool->StackLevel = -1;
12090         tool->Results.resize(0);
12091     }
12092     if (query_id == 0)
12093         return;
12094 
12095     // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
12096     int stack_level = tool->StackLevel;
12097     if (stack_level >= 0 && stack_level < tool->Results.Size)
12098         if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)
12099             tool->StackLevel++;
12100 
12101     // Update hook
12102     stack_level = tool->StackLevel;
12103     if (stack_level == -1)
12104         g.DebugHookIdInfo = query_id;
12105     if (stack_level >= 0 && stack_level < tool->Results.Size)
12106     {
12107         g.DebugHookIdInfo = tool->Results[stack_level].ID;
12108         tool->Results[stack_level].QueryFrameCount++;
12109     }
12110 }
12111 
12112 // [DEBUG] Stack tool: hooks called by GetID() family functions
DebugHookIdInfo(ImGuiID id,ImGuiDataType data_type,const void * data_id,const void * data_id_end)12113 void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
12114 {
12115     ImGuiContext& g = *GImGui;
12116     ImGuiWindow* window = g.CurrentWindow;
12117     ImGuiStackTool* tool = &g.DebugStackTool;
12118 
12119     // Step 0: stack query
12120     // This assume that the ID was computed with the current ID stack, which tends to be the case for our widget.
12121     if (tool->StackLevel == -1)
12122     {
12123         tool->StackLevel++;
12124         tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo());
12125         for (int n = 0; n < window->IDStack.Size + 1; n++)
12126             tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
12127         return;
12128     }
12129 
12130     // Step 1+: query for individual level
12131     IM_ASSERT(tool->StackLevel >= 0);
12132     if (tool->StackLevel != window->IDStack.Size)
12133         return;
12134     ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
12135     IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
12136 
12137     int data_len;
12138     switch (data_type)
12139     {
12140     case ImGuiDataType_S32:
12141         ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%d", (int)(intptr_t)data_id);
12142         break;
12143     case ImGuiDataType_String:
12144         data_len = data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)strlen((const char*)data_id);
12145         ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "\"%.*s\"", data_len, (const char*)data_id);
12146         break;
12147     case ImGuiDataType_Pointer:
12148         ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "(void*)0x%p", data_id);
12149         break;
12150     case ImGuiDataType_ID:
12151         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.
12152             ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "0x%08X [override]", id);
12153         break;
12154     default:
12155         IM_ASSERT(0);
12156     }
12157     info->QuerySuccess = true;
12158 }
12159 
12160 // Stack Tool: Display UI
ShowStackToolWindow(bool * p_open)12161 void ImGui::ShowStackToolWindow(bool* p_open)
12162 {
12163     if (!Begin("Dear ImGui Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
12164     {
12165         End();
12166         return;
12167     }
12168 
12169     // Display hovered/active status
12170     ImGuiContext& g = *GImGui;
12171     const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
12172     const ImGuiID active_id = g.ActiveId;
12173 #ifdef IMGUI_ENABLE_TEST_ENGINE
12174     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) : "");
12175 #else
12176     Text("HoveredId: 0x%08X, ActiveId:  0x%08X", hovered_id, active_id);
12177 #endif
12178     SameLine();
12179     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.");
12180 
12181     // Display decorated stack
12182     ImGuiStackTool* tool = &g.DebugStackTool;
12183     tool->LastActiveFrame = g.FrameCount;
12184     if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders))
12185     {
12186         const float id_width = CalcTextSize("0xDDDDDDDD").x;
12187         TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width);
12188         TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch);
12189         TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width);
12190         TableHeadersRow();
12191         for (int n = 0; n < tool->Results.Size; n++)
12192         {
12193             ImGuiStackLevelInfo* info = &tool->Results[n];
12194             TableNextColumn();
12195             Text("0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0);
12196 
12197             TableNextColumn();
12198             ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? FindWindowByID(info->ID) : NULL;
12199             if (window)                                         // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
12200                 Text("\"%s\" [window]", window->Name);
12201             else if (info->QuerySuccess)                        // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
12202                 TextUnformatted(info->Desc);
12203             else if (tool->StackLevel >= tool->Results.Size)    // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
12204             {
12205 #ifdef IMGUI_ENABLE_TEST_ENGINE
12206                 if (const char* label = ImGuiTestEngine_FindItemDebugLabel(&g, info->ID))    // Source: ImGuiTestEngine's ItemInfo()
12207                     Text("??? \"%s\"", label);
12208                 else
12209 #endif
12210                     TextUnformatted("???");
12211             }
12212 
12213             TableNextColumn();
12214             Text("0x%08X", info->ID);
12215             if (n == tool->Results.Size - 1)
12216                 TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header));
12217         }
12218         EndTable();
12219     }
12220     End();
12221 }
12222 
12223 #else
12224 
ShowMetricsWindow(bool *)12225 void ImGui::ShowMetricsWindow(bool*) {}
ShowFontAtlas(ImFontAtlas *)12226 void ImGui::ShowFontAtlas(ImFontAtlas*) {}
DebugNodeColumns(ImGuiOldColumns *)12227 void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
DebugNodeDrawList(ImGuiWindow *,const ImDrawList *,const char *)12228 void ImGui::DebugNodeDrawList(ImGuiWindow*, const ImDrawList*, const char*) {}
DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList *,const ImDrawList *,const ImDrawCmd *,bool,bool)12229 void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
DebugNodeFont(ImFont *)12230 void ImGui::DebugNodeFont(ImFont*) {}
DebugNodeStorage(ImGuiStorage *,const char *)12231 void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
DebugNodeTabBar(ImGuiTabBar *,const char *)12232 void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
DebugNodeWindow(ImGuiWindow *,const char *)12233 void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
DebugNodeWindowSettings(ImGuiWindowSettings *)12234 void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
DebugNodeWindowsList(ImVector<ImGuiWindow * > *,const char *)12235 void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
DebugNodeViewport(ImGuiViewportP *)12236 void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
12237 
ShowStackToolWindow(bool *)12238 void ImGui::ShowStackToolWindow(bool*) {}
DebugHookIdInfo(ImGuiID,ImGuiDataType,const void *,const void *)12239 void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
UpdateDebugToolItemPicker()12240 void ImGui::UpdateDebugToolItemPicker() {}
UpdateDebugToolStackQueries()12241 void ImGui::UpdateDebugToolStackQueries() {}
12242 
12243 #endif // #ifndef IMGUI_DISABLE_METRICS_WINDOW
12244 
12245 //-----------------------------------------------------------------------------
12246 
12247 // Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
12248 // 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.
12249 #ifdef IMGUI_INCLUDE_IMGUI_USER_INL
12250 #include "imgui_user.inl"
12251 #endif
12252 
12253 //-----------------------------------------------------------------------------
12254 
12255 #endif // #ifndef IMGUI_DISABLE
12256