openMSX
imgui.cc
Go to the documentation of this file.
1// dear imgui, v1.90.5 WIP
2// (main code and documentation)
3
4// Help:
5// - See links below.
6// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
7// - Read top of imgui.cpp for more details, links and comments.
8
9// Resources:
10// - FAQ ........................ https://dearimgui.com/faq (in repository as docs/FAQ.md)
11// - Homepage ................... https://github.com/ocornut/imgui
12// - Releases & changelog ....... https://github.com/ocornut/imgui/releases
13// - Gallery .................... https://github.com/ocornut/imgui/issues/6897 (please post your screenshots/video there!)
14// - Wiki ....................... https://github.com/ocornut/imgui/wiki (lots of good stuff there)
15// - Getting Started https://github.com/ocornut/imgui/wiki/Getting-Started (how to integrate in an existing app by adding ~25 lines of code)
16// - Third-party Extensions https://github.com/ocornut/imgui/wiki/Useful-Extensions (ImPlot & many more)
17// - Bindings/Backends https://github.com/ocornut/imgui/wiki/Bindings (language bindings, backends for various tech/engines)
18// - Glossary https://github.com/ocornut/imgui/wiki/Glossary
19// - Debug Tools https://github.com/ocornut/imgui/wiki/Debug-Tools
20// - Software using Dear ImGui https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui
21// - Issues & support ........... https://github.com/ocornut/imgui/issues
22// - Test Engine & Automation ... https://github.com/ocornut/imgui_test_engine (test suite, test engine to automate your apps)
23
24// For first-time users having issues compiling/linking/running/loading fonts:
25// please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
26// Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there.
27
28// Copyright (c) 2014-2024 Omar Cornut
29// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
30// See LICENSE.txt for copyright and licensing details (standard MIT License).
31// This library is free but needs your support to sustain development and maintenance.
32// Businesses: you can support continued development via B2B invoiced technical support, maintenance and sponsoring contracts.
33// PLEASE reach out at omar AT dearimgui DOT com. See https://github.com/ocornut/imgui/wiki/Sponsors
34// Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
35
36// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
37// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
38// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
39// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
40// to a better solution or official support for them.
41
42/*
43
44Index of this file:
45
46DOCUMENTATION
47
48- MISSION STATEMENT
49- CONTROLS GUIDE
50- PROGRAMMER GUIDE
51 - READ FIRST
52 - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
53 - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
54 - HOW A SIMPLE APPLICATION MAY LOOK LIKE
55 - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
56- API BREAKING CHANGES (read me when you update!)
57- FREQUENTLY ASKED QUESTIONS (FAQ)
58 - Read all answers online: https://www.dearimgui.com/faq, or in docs/FAQ.md (with a Markdown viewer)
59
60CODE
61(search for "[SECTION]" in the code to find them)
62
63// [SECTION] INCLUDES
64// [SECTION] FORWARD DECLARATIONS
65// [SECTION] CONTEXT AND MEMORY ALLOCATORS
66// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
67// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
68// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
69// [SECTION] MISC HELPERS/UTILITIES (File functions)
70// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
71// [SECTION] MISC HELPERS/UTILITIES (Color functions)
72// [SECTION] ImGuiStorage
73// [SECTION] ImGuiTextFilter
74// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
75// [SECTION] ImGuiListClipper
76// [SECTION] STYLING
77// [SECTION] RENDER HELPERS
78// [SECTION] INITIALIZATION, SHUTDOWN
79// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
80// [SECTION] INPUTS
81// [SECTION] ERROR CHECKING
82// [SECTION] ITEM SUBMISSION
83// [SECTION] LAYOUT
84// [SECTION] SCROLLING
85// [SECTION] TOOLTIPS
86// [SECTION] POPUPS
87// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
88// [SECTION] DRAG AND DROP
89// [SECTION] LOGGING/CAPTURING
90// [SECTION] SETTINGS
91// [SECTION] LOCALIZATION
92// [SECTION] VIEWPORTS, PLATFORM WINDOWS
93// [SECTION] DOCKING
94// [SECTION] PLATFORM DEPENDENT HELPERS
95// [SECTION] METRICS/DEBUGGER WINDOW
96// [SECTION] DEBUG LOG WINDOW
97// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
98
99*/
100
101//-----------------------------------------------------------------------------
102// DOCUMENTATION
103//-----------------------------------------------------------------------------
104
105/*
106
107 MISSION STATEMENT
108 =================
109
110 - Easy to use to create code-driven and data-driven tools.
111 - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
112 - Easy to hack and improve.
113 - Minimize setup and maintenance.
114 - Minimize state storage on user side.
115 - Minimize state synchronization.
116 - Portable, minimize dependencies, run on target (consoles, phones, etc.).
117 - Efficient runtime and memory consumption.
118
119 Designed primarily for developers and content-creators, not the typical end-user!
120 Some of the current weaknesses (which we aim to address in the future) includes:
121
122 - Doesn't look fancy.
123 - Limited layout features, intricate layouts are typically crafted in code.
124
125
126 CONTROLS GUIDE
127 ==============
128
129 - MOUSE CONTROLS
130 - Mouse wheel: Scroll vertically.
131 - SHIFT+Mouse wheel: Scroll horizontally.
132 - Click [X]: Close a window, available when 'bool* p_open' is passed to ImGui::Begin().
133 - Click ^, Double-Click title: Collapse window.
134 - Drag on corner/border: Resize window (double-click to auto fit window to its contents).
135 - Drag on any empty space: Move window (unless io.ConfigWindowsMoveFromTitleBarOnly = true).
136 - Left-click outside popup: Close popup stack (right-click over underlying popup: Partially close popup stack).
137
138 - TEXT EDITOR
139 - Hold SHIFT or Drag Mouse: Select text.
140 - CTRL+Left/Right: Word jump.
141 - CTRL+Shift+Left/Right: Select words.
142 - CTRL+A or Double-Click: Select All.
143 - CTRL+X, CTRL+C, CTRL+V: Use OS clipboard.
144 - CTRL+Z, CTRL+Y: Undo, Redo.
145 - ESCAPE: Revert text to its original value.
146 - On OSX, controls are automatically adjusted to match standard OSX text editing shortcuts and behaviors.
147
148 - KEYBOARD CONTROLS
149 - Basic:
150 - Tab, SHIFT+Tab Cycle through text editable fields.
151 - CTRL+Tab, CTRL+Shift+Tab Cycle through windows.
152 - CTRL+Click Input text into a Slider or Drag widget.
153 - Extended features with `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard`:
154 - Tab, SHIFT+Tab: Cycle through every items.
155 - Arrow keys Move through items using directional navigation. Tweak value.
156 - Arrow keys + Alt, Shift Tweak slower, tweak faster (when using arrow keys).
157 - Enter Activate item (prefer text input when possible).
158 - Space Activate item (prefer tweaking with arrows when possible).
159 - Escape Deactivate item, leave child window, close popup.
160 - Page Up, Page Down Previous page, next page.
161 - Home, End Scroll to top, scroll to bottom.
162 - Alt Toggle between scrolling layer and menu layer.
163 - CTRL+Tab then Ctrl+Arrows Move window. Hold SHIFT to resize instead of moving.
164 - Output when ImGuiConfigFlags_NavEnableKeyboard set,
165 - io.WantCaptureKeyboard flag is set when keyboard is claimed.
166 - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
167 - io.NavVisible: true when the navigation cursor is visible (usually goes to back false when mouse is used).
168
169 - GAMEPAD CONTROLS
170 - Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
171 - Particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse!
172 - Download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets
173 - Backend support: backend needs to:
174 - Set 'io.BackendFlags |= ImGuiBackendFlags_HasGamepad' + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
175 - For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
176 Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
177 - BEFORE 1.87, BACKENDS USED TO WRITE TO io.NavInputs[]. This is now obsolete. Please call io functions instead!
178 - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
179 with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
180
181 - REMOTE INPUTS SHARING & MOUSE EMULATION
182 - PS4/PS5 users: Consider emulating a mouse cursor with DualShock touch pad or a spare analog stick as a mouse-emulation fallback.
183 - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + run examples/libs/synergy/uSynergy.c (on your console/tablet/phone app)
184 in order to share your PC mouse/keyboard.
185 - See https://github.com/ocornut/imgui/wiki/Useful-Extensions#remoting for other remoting solutions.
186 - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
187 Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements.
188 When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
189 When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that.
190 (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, Dear ImGui will misbehave as it will see your mouse moving back & forth!)
191 (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
192 to set a boolean to ignore your other external mouse positions until the external source is moved again.)
193
194
195 PROGRAMMER GUIDE
196 ================
197
198 READ FIRST
199 ----------
200 - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
201 - Your code creates the UI every frame of your application loop, if your code doesn't run the UI is gone!
202 The UI can be highly dynamic, there are no construction or destruction steps, less superfluous
203 data retention on your side, less state duplication, less state synchronization, fewer bugs.
204 - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
205 Or browse https://pthom.github.io/imgui_manual_online/manual/imgui_manual.html for interactive web version.
206 - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
207 - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
208 You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
209 - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
210 For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI,
211 where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
212 - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
213 - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
214 If you get an assert, read the messages and comments around the assert.
215 - This codebase aims to be highly optimized:
216 - A typical idle frame should never call malloc/free.
217 - We rely on a maximum of constant-time or O(N) algorithms. Limiting searches/scans as much as possible.
218 - We put particular energy in making sure performances are decent with typical "Debug" build settings as well.
219 Which mean we tend to avoid over-relying on "zero-cost abstraction" as they aren't zero-cost at all.
220 - This codebase aims to be both highly opinionated and highly flexible:
221 - This code works because of the things it choose to solve or not solve.
222 - C++: this is a pragmatic C-ish codebase: we don't use fancy C++ features, we don't include C++ headers,
223 and ImGui:: is a namespace. We rarely use member functions (and when we did, I am mostly regretting it now).
224 This is to increase compatibility, increase maintainability and facilitate use from other languages.
225 - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
226 See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
227 We can can optionally export math operators for ImVec2/ImVec4 using IMGUI_DEFINE_MATH_OPERATORS, which we use internally.
228 - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction
229 (so don't use ImVector in your code or at our own risk!).
230 - Building: We don't use nor mandate a build system for the main library.
231 This is in an effort to ensure that it works in the real world aka with any esoteric build setup.
232 This is also because providing a build system for the main library would be of little-value.
233 The build problems are almost never coming from the main library but from specific backends.
234
235
236 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
237 ----------------------------------------------
238 - Update submodule or copy/overwrite every file.
239 - About imconfig.h:
240 - You may modify your copy of imconfig.h, in this case don't overwrite it.
241 - or you may locally branch to modify imconfig.h and merge/rebase latest.
242 - or you may '#define IMGUI_USER_CONFIG "my_config_file.h"' globally from your build system to
243 specify a custom path for your imconfig.h file and instead not have to modify the default one.
244
245 - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
246 - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
247 - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
248 - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
249 If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
250 from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
251 likely be a comment about it. Please report any issue to the GitHub page!
252 - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
253 - Try to keep your copy of Dear ImGui reasonably up to date!
254
255
256 GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
257 ---------------------------------------------------------------
258 - See https://github.com/ocornut/imgui/wiki/Getting-Started.
259 - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
260 - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
261 - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
262 It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
263 - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
264 - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
265 - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
266 Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
267 phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
268 - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
269 - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
270
271
272 HOW A SIMPLE APPLICATION MAY LOOK LIKE
273 --------------------------------------
274 EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
275 The sub-folders in examples/ contain examples applications following this structure.
276
277 // Application init: create a dear imgui context, setup some options, load fonts
278 ImGui::CreateContext();
279 ImGuiIO& io = ImGui::GetIO();
280 // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
281 // TODO: Fill optional fields of the io structure later.
282 // TODO: Load TTF/OTF fonts if you don't want to use the default font.
283
284 // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
285 ImGui_ImplWin32_Init(hwnd);
286 ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
287
288 // Application main loop
289 while (true)
290 {
291 // Feed inputs to dear imgui, start new frame
292 ImGui_ImplDX11_NewFrame();
293 ImGui_ImplWin32_NewFrame();
294 ImGui::NewFrame();
295
296 // Any application code here
297 ImGui::Text("Hello, world!");
298
299 // Render dear imgui into screen
300 ImGui::Render();
301 ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
302 g_pSwapChain->Present(1, 0);
303 }
304
305 // Shutdown
306 ImGui_ImplDX11_Shutdown();
307 ImGui_ImplWin32_Shutdown();
308 ImGui::DestroyContext();
309
310 EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
311
312 // Application init: create a dear imgui context, setup some options, load fonts
313 ImGui::CreateContext();
314 ImGuiIO& io = ImGui::GetIO();
315 // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
316 // TODO: Fill optional fields of the io structure later.
317 // TODO: Load TTF/OTF fonts if you don't want to use the default font.
318
319 // Build and load the texture atlas into a texture
320 // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
321 int width, height;
322 unsigned char* pixels = nullptr;
323 io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
324
325 // At this point you've got the texture data and you need to upload that to your graphic system:
326 // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
327 // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
328 MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
329 io.Fonts->SetTexID((void*)texture);
330
331 // Application main loop
332 while (true)
333 {
334 // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
335 // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
336 io.DeltaTime = 1.0f/60.0f; // set the time elapsed since the previous frame (in seconds)
337 io.DisplaySize.x = 1920.0f; // set the current display width
338 io.DisplaySize.y = 1280.0f; // set the current display height here
339 io.AddMousePosEvent(mouse_x, mouse_y); // update mouse position
340 io.AddMouseButtonEvent(0, mouse_b[0]); // update mouse button states
341 io.AddMouseButtonEvent(1, mouse_b[1]); // update mouse button states
342
343 // Call NewFrame(), after this point you can use ImGui::* functions anytime
344 // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
345 ImGui::NewFrame();
346
347 // Most of your application code here
348 ImGui::Text("Hello, world!");
349 MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
350 MyGameRender(); // may use any Dear ImGui functions as well!
351
352 // Render dear imgui, swap buffers
353 // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
354 ImGui::EndFrame();
355 ImGui::Render();
356 ImDrawData* draw_data = ImGui::GetDrawData();
357 MyImGuiRenderFunction(draw_data);
358 SwapBuffers();
359 }
360
361 // Shutdown
362 ImGui::DestroyContext();
363
364 To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
365 you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
366 Please read the FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" about this.
367
368
369 HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
370 ---------------------------------------------
371 The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
372
373 void MyImGuiRenderFunction(ImDrawData* draw_data)
374 {
375 // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
376 // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering.
377 // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
378 // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
379 // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
380 ImVec2 clip_off = draw_data->DisplayPos;
381 for (int n = 0; n < draw_data->CmdListsCount; n++)
382 {
383 const ImDrawList* cmd_list = draw_data->CmdLists[n];
384 const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by Dear ImGui
385 const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by Dear ImGui
386 for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
387 {
388 const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
389 if (pcmd->UserCallback)
390 {
391 pcmd->UserCallback(cmd_list, pcmd);
392 }
393 else
394 {
395 // Project scissor/clipping rectangles into framebuffer space
396 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
397 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
398 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
399 continue;
400
401 // We are using scissoring to clip some objects. All low-level graphics API should support it.
402 // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
403 // (some elements visible outside their bounds) but you can fix that once everything else works!
404 // - Clipping coordinates are provided in imgui coordinates space:
405 // - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
406 // - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values.
407 // - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
408 // always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
409 // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
410 MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y);
411
412 // The texture for the draw call is specified by pcmd->GetTexID().
413 // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
414 MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
415
416 // Render 'pcmd->ElemCount/3' indexed triangles.
417 // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
418 MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset);
419 }
420 }
421 }
422 }
423
424
425 API BREAKING CHANGES
426 ====================
427
428 Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
429 Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
430 When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
431 You can read releases logs https://github.com/ocornut/imgui/releases for more details.
432
433(Docking/Viewport Branch)
434 - 2024/XX/XX (1.XXXX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
435 - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore.
436 you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos)
437 - likewise io.MousePos and GetMousePos() will use OS coordinates.
438 If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos.
439
440 - 2024/01/15 (1.90.2) - commented out obsolete ImGuiIO::ImeWindowHandle marked obsolete in 1.87, favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
441 - 2023/12/19 (1.90.1) - commented out obsolete ImGuiKey_KeyPadEnter redirection to ImGuiKey_KeypadEnter.
442 - 2023/11/06 (1.90.1) - removed CalcListClipping() marked obsolete in 1.86. Prefer using ImGuiListClipper which can return non-contiguous ranges.
443 - 2023/11/05 (1.90.1) - imgui_freetype: commented out ImGuiFreeType::BuildFontAtlas() obsoleted in 1.81. prefer using #define IMGUI_ENABLE_FREETYPE or see commented code for manual calls.
444 - 2023/11/05 (1.90.1) - internals,columns: commented out legacy ImGuiColumnsFlags_XXX symbols redirecting to ImGuiOldColumnsFlags_XXX, obsoleted from imgui_internal.h in 1.80.
445 - 2023/11/09 (1.90.0) - removed IM_OFFSETOF() macro in favor of using offsetof() available in C++11. Kept redirection define (will obsolete).
446 - 2023/11/07 (1.90.0) - removed BeginChildFrame()/EndChildFrame() in favor of using BeginChild() with the ImGuiChildFlags_FrameStyle flag. kept inline redirection function (will obsolete).
447 those functions were merely PushStyle/PopStyle helpers, the removal isn't so much motivated by needing to add the feature in BeginChild(), but by the necessity to avoid BeginChildFrame() signature mismatching BeginChild() signature and features.
448 - 2023/11/02 (1.90.0) - BeginChild: upgraded 'bool border = true' parameter to 'ImGuiChildFlags flags' type, added ImGuiChildFlags_Border equivalent. As with our prior "bool-to-flags" API updates, the ImGuiChildFlags_Border value is guaranteed to be == true forever to ensure a smoother transition, meaning all existing calls will still work.
449 - old: BeginChild("Name", size, true)
450 - new: BeginChild("Name", size, ImGuiChildFlags_Border)
451 - old: BeginChild("Name", size, false)
452 - new: BeginChild("Name", size) or BeginChild("Name", 0) or BeginChild("Name", size, ImGuiChildFlags_None)
453 - 2023/11/02 (1.90.0) - BeginChild: added child-flag ImGuiChildFlags_AlwaysUseWindowPadding as a replacement for the window-flag ImGuiWindowFlags_AlwaysUseWindowPadding: the feature only ever made sense for BeginChild() anyhow.
454 - old: BeginChild("Name", size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding);
455 - new: BeginChild("Name", size, ImGuiChildFlags_AlwaysUseWindowPadding, 0);
456 - 2023/09/27 (1.90.0) - io: removed io.MetricsActiveAllocations introduced in 1.63. Same as 'g.DebugMemAllocCount - g.DebugMemFreeCount' (still displayed in Metrics, unlikely to be accessed by end-user).
457 - 2023/09/26 (1.90.0) - debug tools: Renamed ShowStackToolWindow() ("Stack Tool") to ShowIDStackToolWindow() ("ID Stack Tool"), as earlier name was misleading. Kept inline redirection function. (#4631)
458 - 2023/09/15 (1.90.0) - ListBox, Combo: changed signature of "name getter" callback in old one-liner ListBox()/Combo() apis. kept inline redirection function (will obsolete).
459 - old: bool Combo(const char* label, int* current_item, bool (*getter)(void* user_data, int idx, const char** out_text), ...)
460 - new: bool Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
461 - old: bool ListBox(const char* label, int* current_item, bool (*getting)(void* user_data, int idx, const char** out_text), ...);
462 - new: bool ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
463 - 2023/09/08 (1.90.0) - commented out obsolete redirecting functions:
464 - GetWindowContentRegionWidth() -> use GetWindowContentRegionMax().x - GetWindowContentRegionMin().x. Consider that generally 'GetContentRegionAvail().x' is more useful.
465 - ImDrawCornerFlags_XXX -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details + grep commented names in sources.
466 - commented out runtime support for hardcoded ~0 or 0x01..0x0F rounding flags values for AddRect()/AddRectFilled()/PathRect()/AddImageRounded() -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details
467 - 2023/08/25 (1.89.9) - clipper: Renamed IncludeRangeByIndices() (also called ForceDisplayRangeByIndices() before 1.89.6) to IncludeItemsByIndex(). Kept inline redirection function. Sorry!
468 - 2023/07/12 (1.89.8) - ImDrawData: CmdLists now owned, changed from ImDrawList** to ImVector<ImDrawList*>. Majority of users shouldn't be affected, but you cannot compare to NULL nor reassign manually anymore. Instead use AddDrawList(). (#6406, #4879, #1878)
469 - 2023/06/28 (1.89.7) - overlapping items: obsoleted 'SetItemAllowOverlap()' (called after item) in favor of calling 'SetNextItemAllowOverlap()' (called before item). 'SetItemAllowOverlap()' didn't and couldn't work reliably since 1.89 (2022-11-15).
470 - 2023/06/28 (1.89.7) - overlapping items: renamed 'ImGuiTreeNodeFlags_AllowItemOverlap' to 'ImGuiTreeNodeFlags_AllowOverlap', 'ImGuiSelectableFlags_AllowItemOverlap' to 'ImGuiSelectableFlags_AllowOverlap'. Kept redirecting enums (will obsolete).
471 - 2023/06/28 (1.89.7) - overlapping items: IsItemHovered() now by default return false when querying an item using AllowOverlap mode which is being overlapped. Use ImGuiHoveredFlags_AllowWhenOverlappedByItem to revert to old behavior.
472 - 2023/06/28 (1.89.7) - overlapping items: Selectable and TreeNode don't allow overlap when active so overlapping widgets won't appear as hovered. While this fixes a common small visual issue, it also means that calling IsItemHovered() after a non-reactive elements - e.g. Text() - overlapping an active one may fail if you don't use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem). (#6610)
473 - 2023/06/20 (1.89.7) - moved io.HoverDelayShort/io.HoverDelayNormal to style.HoverDelayShort/style.HoverDelayNormal. As the fields were added in 1.89 and expected to be left unchanged by most users, or only tweaked once during app initialization, we are exceptionally accepting the breakage.
474 - 2023/05/30 (1.89.6) - backends: renamed "imgui_impl_sdlrenderer.cpp" to "imgui_impl_sdlrenderer2.cpp" and "imgui_impl_sdlrenderer.h" to "imgui_impl_sdlrenderer2.h". This is in prevision for the future release of SDL3.
475 - 2023/05/22 (1.89.6) - listbox: commented out obsolete/redirecting functions that were marked obsolete more than two years ago:
476 - ListBoxHeader() -> use BeginListBox() (note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for reference)
477 - ListBoxFooter() -> use EndListBox()
478 - 2023/05/15 (1.89.6) - clipper: commented out obsolete redirection constructor 'ImGuiListClipper(int items_count, float items_height = -1.0f)' that was marked obsolete in 1.79. Use default constructor + clipper.Begin().
479 - 2023/05/15 (1.89.6) - clipper: renamed ImGuiListClipper::ForceDisplayRangeByIndices() to ImGuiListClipper::IncludeRangeByIndices().
480 - 2023/03/14 (1.89.4) - commented out redirecting enums/functions names that were marked obsolete two years ago:
481 - ImGuiSliderFlags_ClampOnInput -> use ImGuiSliderFlags_AlwaysClamp
482 - ImGuiInputTextFlags_AlwaysInsertMode -> use ImGuiInputTextFlags_AlwaysOverwrite
483 - ImDrawList::AddBezierCurve() -> use ImDrawList::AddBezierCubic()
484 - ImDrawList::PathBezierCurveTo() -> use ImDrawList::PathBezierCubicCurveTo()
485 - 2023/03/09 (1.89.4) - renamed PushAllowKeyboardFocus()/PopAllowKeyboardFocus() to PushTabStop()/PopTabStop(). Kept inline redirection functions (will obsolete).
486 - 2023/03/09 (1.89.4) - tooltips: Added 'bool' return value to BeginTooltip() for API consistency. Please only submit contents and call EndTooltip() if BeginTooltip() returns true. In reality the function will _currently_ always return true, but further changes down the line may change this, best to clarify API sooner.
487 - 2023/02/15 (1.89.4) - moved the optional "courtesy maths operators" implementation from imgui_internal.h in imgui.h.
488 Even though we encourage using your own maths types and operators by setting up IM_VEC2_CLASS_EXTRA,
489 it has been frequently requested by people to use our own. We had an opt-in define which was
490 previously fulfilled in imgui_internal.h. It is now fulfilled in imgui.h. (#6164)
491 - OK: #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui.h" / #include "imgui_internal.h"
492 - Error: #include "imgui.h" / #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui_internal.h"
493 - 2023/02/07 (1.89.3) - backends: renamed "imgui_impl_sdl.cpp" to "imgui_impl_sdl2.cpp" and "imgui_impl_sdl.h" to "imgui_impl_sdl2.h". (#6146) This is in prevision for the future release of SDL3.
494 - 2022/10/26 (1.89) - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
495 - 2022/10/12 (1.89) - removed runtime patching of invalid "%f"/"%0.f" format strings for DragInt()/SliderInt(). This was obsoleted in 1.61 (May 2018). See 1.61 changelog for details.
496 - 2022/09/26 (1.89) - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
497 - ImGuiKey_ModCtrl and ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl
498 - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
499 - ImGuiKey_ModAlt and ImGuiModFlags_Alt -> ImGuiMod_Alt
500 - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
501 the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
502 the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
503 exceptionally commenting out the older ImGuiKeyModFlags_XXX names ahead of obsolescence schedule to reduce confusion and because they were not meant to be used anyway.
504 - 2022/09/20 (1.89) - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers.
505 this will require uses of legacy backend-dependent indices to be casted, e.g.
506 - with imgui_impl_glfw: IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A);
507 - with imgui_impl_win32: IsKeyPressed('A') -> IsKeyPressed((ImGuiKey)'A')
508 - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now!
509 - 2022/09/12 (1.89) - removed the bizarre legacy default argument for 'TreePush(const void* ptr = NULL)', always pass a pointer value explicitly. NULL/nullptr is ok but require cast, e.g. TreePush((void*)nullptr);
510 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
511 - DragScalar(), DragScalarN(), DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
512 - SliderScalar(), SliderScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
513 - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
514 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
515 this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
516 - previously this would make the window content size ~200x200:
517 Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
518 - instead, please submit an item:
519 Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
520 - alternative:
521 Begin(...) + Dummy(ImVec2(200,200)) + End();
522 - content size is now only extended when submitting an item!
523 - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
524 - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
525 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
526 - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
527 - old signature: bool ImageButton(ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), int frame_padding = -1, ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
528 - used the ImTextureID value to create an ID. This was inconsistent with other functions, led to ID conflicts, and caused problems with engines using transient ImTextureID values.
529 - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
530 - new signature: bool ImageButton(const char* str_id, ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
531 - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
532 - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
533 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
534 - Official backends from 1.87+ -> no issue.
535 - Official backends from 1.60 to 1.86 -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
536 - Custom backends not writing to io.NavInputs[] -> no issue.
537 - Custom backends writing to io.NavInputs[] -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
538 - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
539 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
540 - 2022/05/03 (1.88) - backends: osx: removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture. All ImGui_ImplOSX_HandleEvent() calls should be removed as they are now unnecessary.
541 - 2022/04/05 (1.88) - inputs: renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). This was never used in public API functions but technically present in imgui.h and ImGuiIO.
542 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
543 - Backend writing to io.NavInputs[] -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
544 - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputing text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
545 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
546 - Backend writing to io.MousePos -> backend should call io.AddMousePosEvent()
547 - Backend writing to io.MouseDown[] -> backend should call io.AddMouseButtonEvent()
548 - Backend writing to io.MouseWheel -> backend should call io.AddMouseWheelEvent()
549 - Backend writing to io.MouseHoveredViewport -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
550 note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
551 read https://github.com/ocornut/imgui/issues/4921 for details.
552 - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.
553 - IsKeyPressed(MY_NATIVE_KEY_XXX) -> use IsKeyPressed(ImGuiKey_XXX)
554 - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX)
555 - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes).
556 - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiMod_XXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiMod_XXX values.*
557 - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert.
558 - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper.
559 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
560 - 2022/01/05 (1.87) - removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn(). Removed 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
561 - 2022/01/01 (1.87) - commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019)
562 - ImGui::SetNextTreeNodeOpen() -> use ImGui::SetNextItemOpen()
563 - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
564 - ImGui::TreeAdvanceToLabelPos() -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
565 - ImFontAtlas::CustomRect -> use ImFontAtlasCustomRect
566 - ImGuiColorEditFlags_RGB/HSV/HEX -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
567 - 2021/12/20 (1.86) - backends: removed obsolete Marmalade backend (imgui_impl_marmalade.cpp) + example. Find last supported version at https://github.com/ocornut/imgui/wiki/Bindings
568 - 2021/11/04 (1.86) - removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. Please open an issue if you think you really need this function.
569 - 2021/08/23 (1.85) - removed GetWindowContentRegionWidth() function. keep inline redirection helper. can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead for generally 'GetContentRegionAvail().x' is more useful.
570 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
571 - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
572 - ImFont::GlyphRangesBuilder -> use ImFontGlyphRangesBuilder
573 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
574 - if you are using official backends from the source tree: you have nothing to do.
575 - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
576 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
577 - ImDrawCornerFlags_TopLeft -> use ImDrawFlags_RoundCornersTopLeft
578 - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
579 - ImDrawCornerFlags_None -> use ImDrawFlags_RoundCornersNone etc.
580 flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
581 breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
582 - rounding == 0.0f + flags == 0 --> meant no rounding --> unchanged (common use)
583 - rounding > 0.0f + flags != 0 --> meant rounding --> unchanged (common use)
584 - rounding == 0.0f + flags != 0 --> meant no rounding --> unchanged (unlikely use)
585 - rounding > 0.0f + flags == 0 --> meant no rounding --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
586 this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
587 the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify "round all corners" and we sometimes encouraged using them as shortcuts.
588 legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise).
589 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
590 - ImGui::SetScrollHere() -> use ImGui::SetScrollHereY()
591 - 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing.
592 - 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() "bool closed" parameter to "ImDrawFlags flags". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future.
593 - 2021/02/22 (1.82) - (*undone in 1.84*) win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'.
594 - 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed.
595 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
596 - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
597 - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
598 - 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags.
599 - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
600 - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
601 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
602 - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
603 - ImGuiCol_ModalWindowDarkening -> use ImGuiCol_ModalWindowDimBg
604 - ImGuiInputTextCallback -> use ImGuiTextEditCallback
605 - ImGuiInputTextCallbackData -> use ImGuiTextEditCallbackData
606 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
607 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
608 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
609 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
610 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
611 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
612 - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your backend
613 - ImGui::IsAnyWindowFocused() -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
614 - ImGui::IsAnyWindowHovered() -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
615 - ImGuiStyleVar_Count_ -> use ImGuiStyleVar_COUNT
616 - ImGuiMouseCursor_Count_ -> use ImGuiMouseCursor_COUNT
617 - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
618 - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
619 - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
620 - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed).
621 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
622 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
623 - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory.
624 - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result.
625 - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now!
626 - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar().
627 replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
628 worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
629 - if you omitted the 'power' parameter (likely!), you are not affected.
630 - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct.
631 - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f.
632 see https://github.com/ocornut/imgui/issues/3361 for all details.
633 kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used.
634 for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
635 - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime.
636 - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.
637 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
638 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
639 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
640 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
641 - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
642 - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
643 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
644 - ShowTestWindow() -> use ShowDemoWindow()
645 - IsRootWindowFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
646 - IsRootWindowOrAnyChildFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
647 - SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
648 - GetItemsLineHeightWithSpacing() -> use GetFrameHeightWithSpacing()
649 - ImGuiCol_ChildWindowBg -> use ImGuiCol_ChildBg
650 - ImGuiStyleVar_ChildWindowRounding -> use ImGuiStyleVar_ChildRounding
651 - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
652 - IMGUI_DISABLE_TEST_WINDOWS -> use IMGUI_DISABLE_DEMO_WINDOWS
653 - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API.
654 - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
655 - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
656 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
657 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
658 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
659 - Begin() [old 5 args version] -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
660 - IsRootWindowOrAnyChildHovered() -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
661 - AlignFirstTextHeightToWidgets() -> use AlignTextToFramePadding()
662 - SetNextWindowPosCenter() -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
663 - ImFont::Glyph -> use ImFontGlyph
664 - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
665 if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
666 The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
667 If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
668 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
669 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
670 - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
671 - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
672 overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
673 This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
674 Please reach out if you are affected.
675 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
676 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
677 - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
678 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
679 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
680 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
681 - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrarily small value!
682 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
683 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
684 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
685 - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
686 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
687 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
688 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
689 - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
690 If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
691 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
692 - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
693 NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
694 Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
695 - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
696 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
697 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
698 - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
699 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
700 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
701 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
702 - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan, etc.).
703 old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
704 when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
705 in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
706 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
707 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
708 - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
709 If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
710 To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
711 If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
712 - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
713 consistent with other functions. Kept redirection functions (will obsolete).
714 - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
715 - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch).
716 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
717 - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
718 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
719 - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
720 - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
721 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
722 - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
723 - removed Shutdown() function, as DestroyContext() serve this purpose.
724 - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
725 - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
726 - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
727 - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
728 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
729 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
730 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
731 - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
732 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
733 - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
734 - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
735 - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
736 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
737 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
738 - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
739 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
740 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
741 - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
742 - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
743 Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
744 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
745 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
746 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
747 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
748 - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
749 - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
750 - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
751 removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
752 IsItemHoveredRect() --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
753 IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
754 IsMouseHoveringWindow() --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
755 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
756 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
757 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
758 - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
759 - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
760 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
761 - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
762 - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
763 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
764 - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
765 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
766 - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
767 - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
768 - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
769 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
770 - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
771 - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
772 - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))'
773 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
774 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
775 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
776 - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetID() and use it instead of passing string to BeginChild().
777 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
778 - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
779 - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully, breakage should be minimal.
780 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
781 If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
782 This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color:
783 ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
784 If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
785 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
786 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
787 - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
788 - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
789 - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref GitHub issue #337).
790 - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
791 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
792 - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
793 - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
794 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
795 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
796 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
797 GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
798 GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
799 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
800 - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
801 - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
802 - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
803 you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
804 - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
805 this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
806 - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
807 - the signature of the io.RenderDrawListsFn handler has changed!
808 old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
809 new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
810 parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
811 ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
812 ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
813 - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
814 - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
815 - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
816 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
817 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
818 - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
819 - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
820 - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely used. Sorry!
821 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
822 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
823 - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
824 - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
825 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
826 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
827 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
828 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
829 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
830 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
831 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
832 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
833 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
834 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
835 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
836 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
837 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
838 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
839 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
840 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
841 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
842 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
843 - old: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
844 - new: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
845 you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
846 - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID()
847 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
848 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
849 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
850 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
851 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
852 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
853 - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
854 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
855 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
856 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
857 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
858 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
859 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
860
861
862 FREQUENTLY ASKED QUESTIONS (FAQ)
863 ================================
864
865 Read all answers online:
866 https://www.dearimgui.com/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
867 Read all answers locally (with a text editor or ideally a Markdown viewer):
868 docs/FAQ.md
869 Some answers are copied down here to facilitate searching in code.
870
871 Q&A: Basics
872 ===========
873
874 Q: Where is the documentation?
875 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
876 - Run the examples/ applications and explore them.
877 - Read Getting Started (https://github.com/ocornut/imgui/wiki/Getting-Started) guide.
878 - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
879 - The demo covers most features of Dear ImGui, so you can read the code and see its output.
880 - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
881 - 20+ standalone example applications using e.g. OpenGL/DirectX are provided in the
882 examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
883 - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
884 - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
885 - Your programming IDE is your friend, find the type or function declaration to find comments
886 associated with it.
887
888 Q: What is this library called?
889 Q: Which version should I get?
890 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
891 >> See https://www.dearimgui.com/faq for details.
892
893 Q&A: Integration
894 ================
895
896 Q: How to get started?
897 A: Read https://github.com/ocornut/imgui/wiki/Getting-Started. Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
898
899 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
900 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
901 >> See https://www.dearimgui.com/faq for a fully detailed answer. You really want to read this.
902
903 Q. How can I enable keyboard or gamepad controls?
904 Q: How can I use this on a machine without mouse, keyboard or screen? (input share, remote display)
905 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
906 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
907 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
908 >> See https://www.dearimgui.com/faq
909
910 Q&A: Usage
911 ----------
912
913 Q: About the ID Stack system..
914 - Why is my widget not reacting when I click on it?
915 - How can I have widgets with an empty label?
916 - How can I have multiple widgets with the same label?
917 - How can I have multiple windows with the same label?
918 Q: How can I display an image? What is ImTextureID, how does it work?
919 Q: How can I use my own math types instead of ImVec2?
920 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
921 Q: How can I display custom shapes? (using low-level ImDrawList API)
922 >> See https://www.dearimgui.com/faq
923
924 Q&A: Fonts, Text
925 ================
926
927 Q: How should I handle DPI in my application?
928 Q: How can I load a different font than the default?
929 Q: How can I easily use icons in my application?
930 Q: How can I load multiple fonts?
931 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
932 >> See https://www.dearimgui.com/faq and https://github.com/ocornut/imgui/blob/master/docs/FONTS.md
933
934 Q&A: Concerns
935 =============
936
937 Q: Who uses Dear ImGui?
938 Q: Can you create elaborate/serious tools with Dear ImGui?
939 Q: Can you reskin the look of Dear ImGui?
940 Q: Why using C++ (as opposed to C)?
941 >> See https://www.dearimgui.com/faq
942
943 Q&A: Community
944 ==============
945
946 Q: How can I help?
947 A: - Businesses: please reach out to "omar AT dearimgui DOT com" if you work in a place using Dear ImGui!
948 We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
949 This is among the most useful thing you can do for Dear ImGui. With increased funding, we sustain and grow work on this project.
950 Also see https://github.com/ocornut/imgui/wiki/Sponsors
951 - Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
952 - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, and see how you want to help and can help!
953 - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
954 You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
955 But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
956 - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on GitHub or privately).
957
958*/
959
960//-------------------------------------------------------------------------
961// [SECTION] INCLUDES
962//-------------------------------------------------------------------------
963
964#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
965#define _CRT_SECURE_NO_WARNINGS
966#endif
967
968#ifndef IMGUI_DEFINE_MATH_OPERATORS
969#define IMGUI_DEFINE_MATH_OPERATORS
970#endif
971
972#include "imgui.h"
973#ifndef IMGUI_DISABLE
974#include "imgui_internal.h"
975
976// System includes
977#include <stdio.h> // vsnprintf, sscanf, printf
978#include <stdint.h> // intptr_t
979
980// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
981#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
982#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
983#endif
984
985// [Windows] OS specific includes (optional)
986#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
987#define IMGUI_DISABLE_WIN32_FUNCTIONS
988#endif
989#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
990#ifndef WIN32_LEAN_AND_MEAN
991#define WIN32_LEAN_AND_MEAN
992#endif
993#ifndef NOMINMAX
994#define NOMINMAX
995#endif
996#ifndef __MINGW32__
997#include <Windows.h> // _wfopen, OpenClipboard
998#else
999#include <windows.h>
1000#endif
1001#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have all Win32 functions
1002#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
1003#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
1004#endif
1005#endif
1006
1007// [Apple] OS specific includes
1008#if defined(__APPLE__)
1009#include <TargetConditionals.h>
1010#endif
1011
1012// Visual Studio warnings
1013#ifdef _MSC_VER
1014#pragma warning (disable: 4127) // condition expression is constant
1015#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
1016#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later
1017#pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types
1018#endif
1019#pragma warning (disable: 26451) // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to an 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
1020#pragma warning (disable: 26495) // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
1021#pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
1022#endif
1023
1024// Clang/GCC warnings with -Weverything
1025#if defined(__clang__)
1026#if __has_warning("-Wunknown-warning-option")
1027#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
1028#endif
1029#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
1030#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
1031#pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
1032#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning: format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
1033#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning: declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
1034#pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is.
1035#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
1036#pragma clang diagnostic ignored "-Wformat-pedantic" // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
1037#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type 'int'
1038#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
1039#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
1040#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
1041#elif defined(__GNUC__)
1042// We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
1043#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
1044#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
1045#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
1046#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
1047#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
1048#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
1049#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
1050#pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
1051#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
1052#endif
1053
1054// Debug options
1055#define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
1056#define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window
1057
1058// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
1059static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in
1060static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear
1061
1062static const float NAV_ACTIVATE_HIGHLIGHT_TIMER = 0.10f; // Time to highlight an item activated by a shortcut.
1063
1064// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
1065static const float WINDOWS_HOVER_PADDING = 4.0f; // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
1066static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time.
1067static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 0.70f; // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
1068
1069// Tooltip offset
1070static const ImVec2 TOOLTIP_DEFAULT_OFFSET = ImVec2(16, 10); // Multiplied by g.Style.MouseCursorScale
1071
1072// Docking
1073static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA = 0.50f; // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
1074
1075//-------------------------------------------------------------------------
1076// [SECTION] FORWARD DECLARATIONS
1077//-------------------------------------------------------------------------
1078
1079static void SetCurrentWindow(ImGuiWindow* window);
1080static void FindHoveredWindow();
1081static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags);
1082static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
1083
1084static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
1085
1086// Settings
1087static void WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
1088static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
1089static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
1090static void WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
1091static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
1092
1093// Platform Dependents default implementation for IO functions
1094static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx);
1095static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text);
1096static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
1097
1098namespace ImGui
1099{
1100// Navigation
1101static void NavUpdate();
1102static void NavUpdateWindowing();
1103static void NavUpdateWindowingOverlay();
1104static void NavUpdateCancelRequest();
1105static void NavUpdateCreateMoveRequest();
1106static void NavUpdateCreateTabbingRequest();
1107static float NavUpdatePageUpPageDown();
1108static inline void NavUpdateAnyRequestFlag();
1109static void NavUpdateCreateWrappingRequest();
1110static void NavEndFrame();
1111static bool NavScoreItem(ImGuiNavItemData* result);
1112static void NavApplyItemToResult(ImGuiNavItemData* result);
1113static void NavProcessItem();
1114static void NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags);
1115static ImVec2 NavCalcPreferredRefPos();
1116static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1117static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window);
1118static void NavRestoreLayer(ImGuiNavLayer layer);
1119static int FindWindowFocusIndex(ImGuiWindow* window);
1120
1121// Error Checking and Debug Tools
1122static void ErrorCheckNewFrameSanityChecks();
1123static void ErrorCheckEndFrameSanityChecks();
1124static void UpdateDebugToolItemPicker();
1125static void UpdateDebugToolStackQueries();
1126static void UpdateDebugToolFlashStyleColor();
1127
1128// Inputs
1129static void UpdateKeyboardInputs();
1130static void UpdateMouseInputs();
1131static void UpdateMouseWheel();
1132static void UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
1133
1134// Misc
1135static void UpdateSettings();
1136static int UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
1137static void RenderWindowOuterBorders(ImGuiWindow* window);
1138static void RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
1139static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1140static void RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1141static void RenderDimmedBackgrounds();
1142
1143// Viewports
1144const ImGuiID IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter.
1145static ImGuiViewportP* AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
1146static void DestroyViewport(ImGuiViewportP* viewport);
1147static void UpdateViewportsNewFrame();
1148static void UpdateViewportsEndFrame();
1149static void WindowSelectViewport(ImGuiWindow* window);
1150static void WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack);
1151static bool UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
1152static bool UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
1153static bool GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
1154static int FindPlatformMonitorForPos(const ImVec2& pos);
1155static int FindPlatformMonitorForRect(const ImRect& r);
1156static void UpdateViewportPlatformMonitor(ImGuiViewportP* viewport);
1157
1158}
1159
1160//-----------------------------------------------------------------------------
1161// [SECTION] CONTEXT AND MEMORY ALLOCATORS
1162//-----------------------------------------------------------------------------
1163
1164// DLL users:
1165// - Heaps and globals are not shared across DLL boundaries!
1166// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1167// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1168// - Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
1169// - Confused? In a debugger: add GImGui to your watch window and notice how its value changes depending on your current location (which DLL boundary you are in).
1170
1171// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1172// - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1173// Change to a different context by calling ImGui::SetCurrentContext().
1174// - Important: Dear ImGui functions are not thread-safe because of this pointer.
1175// If you want thread-safety to allow N threads to access N different contexts:
1176// - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1177// struct ImGuiContext;
1178// extern thread_local ImGuiContext* MyImGuiTLS;
1179// #define GImGui MyImGuiTLS
1180// And then define MyImGuiTLS in one of your cpp files. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
1181// - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1182// - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1183// - DLL users: read comments above.
1184#ifndef GImGui
1185ImGuiContext* GImGui = NULL;
1186#endif
1187
1188// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1189// - You probably don't want to modify that mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
1190// - DLL users: read comments above.
1191#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1192static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); return malloc(size); }
1193static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); free(ptr); }
1194#else
1195static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1196static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1197#endif
1198static ImGuiMemAllocFunc GImAllocatorAllocFunc = MallocWrapper;
1199static ImGuiMemFreeFunc GImAllocatorFreeFunc = FreeWrapper;
1200static void* GImAllocatorUserData = NULL;
1201
1202//-----------------------------------------------------------------------------
1203// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
1204//-----------------------------------------------------------------------------
1205
1206ImGuiStyle::ImGuiStyle()
1207{
1208 Alpha = 1.0f; // Global alpha applies to everything in Dear ImGui.
1209 DisabledAlpha = 0.60f; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1210 WindowPadding = ImVec2(8,8); // Padding within a window
1211 WindowRounding = 0.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
1212 WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1213 WindowMinSize = ImVec2(32,32); // Minimum window size
1214 WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
1215 WindowMenuButtonPosition= ImGuiDir_Left; // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1216 ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1217 ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1218 PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1219 PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1220 FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets)
1221 FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1222 FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1223 ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
1224 ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1225 CellPadding = ImVec2(4,2); // Padding within a table cell. CellPadding.y may be altered between different rows.
1226 TouchExtraPadding = ImVec2(0,0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
1227 IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1228 ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1229 ScrollbarSize = 14.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
1230 ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
1231 GrabMinSize = 12.0f; // Minimum width/height of a grab box for slider/scrollbar
1232 GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1233 LogSliderDeadzone = 4.0f; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1234 TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1235 TabBorderSize = 0.0f; // Thickness of border around tabs.
1236 TabMinWidthForCloseButton = 0.0f; // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
1237 TabBarBorderSize = 1.0f; // Thickness of tab-bar separator, which takes on the tab active color to denote focus.
1238 TableAngledHeadersAngle = 35.0f * (IM_PI / 180.0f); // Angle of angled headers (supported values range from -50 degrees to +50 degrees).
1239 ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1240 ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1241 SelectableTextAlign = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
1242 SeparatorTextBorderSize = 3.0f; // Thickkness of border in SeparatorText()
1243 SeparatorTextAlign = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center).
1244 SeparatorTextPadding = ImVec2(20.0f,3.f);// Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y.
1245 DisplayWindowPadding = ImVec2(19,19); // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
1246 DisplaySafeAreaPadding = ImVec2(3,3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
1247 DockingSeparatorSize = 2.0f; // Thickness of resizing border between docked windows
1248 MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1249 AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1250 AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
1251 AntiAliasedFill = true; // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1252 CurveTessellationTol = 1.25f; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
1253 CircleTessellationMaxError = 0.30f; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
1254
1255 // Behaviors
1256 HoverStationaryDelay = 0.15f; // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary.
1257 HoverDelayShort = 0.15f; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayShort). Usually used along with HoverStationaryDelay.
1258 HoverDelayNormal = 0.40f; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayNormal). "
1259 HoverFlagsForTooltipMouse = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse.
1260 HoverFlagsForTooltipNav = ImGuiHoveredFlags_NoSharedDelay | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad.
1261
1262 // Default theme
1263 ImGui::StyleColorsDark(this);
1264}
1265
1266// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
1267// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
1268void ImGuiStyle::ScaleAllSizes(float scale_factor)
1269{
1270 WindowPadding = ImTrunc(WindowPadding * scale_factor);
1271 WindowRounding = ImTrunc(WindowRounding * scale_factor);
1272 WindowMinSize = ImTrunc(WindowMinSize * scale_factor);
1273 ChildRounding = ImTrunc(ChildRounding * scale_factor);
1274 PopupRounding = ImTrunc(PopupRounding * scale_factor);
1275 FramePadding = ImTrunc(FramePadding * scale_factor);
1276 FrameRounding = ImTrunc(FrameRounding * scale_factor);
1277 ItemSpacing = ImTrunc(ItemSpacing * scale_factor);
1278 ItemInnerSpacing = ImTrunc(ItemInnerSpacing * scale_factor);
1279 CellPadding = ImTrunc(CellPadding * scale_factor);
1280 TouchExtraPadding = ImTrunc(TouchExtraPadding * scale_factor);
1281 IndentSpacing = ImTrunc(IndentSpacing * scale_factor);
1282 ColumnsMinSpacing = ImTrunc(ColumnsMinSpacing * scale_factor);
1283 ScrollbarSize = ImTrunc(ScrollbarSize * scale_factor);
1284 ScrollbarRounding = ImTrunc(ScrollbarRounding * scale_factor);
1285 GrabMinSize = ImTrunc(GrabMinSize * scale_factor);
1286 GrabRounding = ImTrunc(GrabRounding * scale_factor);
1287 LogSliderDeadzone = ImTrunc(LogSliderDeadzone * scale_factor);
1288 TabRounding = ImTrunc(TabRounding * scale_factor);
1289 TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImTrunc(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
1290 SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor);
1291 DockingSeparatorSize = ImTrunc(DockingSeparatorSize * scale_factor);
1292 DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor);
1293 DisplaySafeAreaPadding = ImTrunc(DisplaySafeAreaPadding * scale_factor);
1294 MouseCursorScale = ImTrunc(MouseCursorScale * scale_factor);
1295}
1296
1297ImGuiIO::ImGuiIO()
1298{
1299 // Most fields are initialized with zero
1300 memset(this, 0, sizeof(*this));
1301 IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1302
1303 // Settings
1304 ConfigFlags = ImGuiConfigFlags_None;
1305 BackendFlags = ImGuiBackendFlags_None;
1306 DisplaySize = ImVec2(-1.0f, -1.0f);
1307 DeltaTime = 1.0f / 60.0f;
1308 IniSavingRate = 5.0f;
1309 IniFilename = "imgui.ini"; // Important: "imgui.ini" is relative to current working dir, most apps will want to lock this to an absolute path (e.g. same path as executables).
1310 LogFilename = "imgui_log.txt";
1311#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1312 for (int i = 0; i < ImGuiKey_COUNT; i++)
1313 KeyMap[i] = -1;
1314#endif
1315 UserData = NULL;
1316
1317 Fonts = NULL;
1318 FontGlobalScale = 1.0f;
1319 FontDefault = NULL;
1320 FontAllowUserScaling = false;
1321 DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1322
1323 // Docking options (when ImGuiConfigFlags_DockingEnable is set)
1324 ConfigDockingNoSplit = false;
1325 ConfigDockingWithShift = false;
1326 ConfigDockingAlwaysTabBar = false;
1327 ConfigDockingTransparentPayload = false;
1328
1329 // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
1330 ConfigViewportsNoAutoMerge = false;
1331 ConfigViewportsNoTaskBarIcon = false;
1332 ConfigViewportsNoDecoration = true;
1333 ConfigViewportsNoDefaultParent = false;
1334
1335 // Miscellaneous options
1336 MouseDrawCursor = false;
1337#ifdef __APPLE__
1338 ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag
1339#else
1340 ConfigMacOSXBehaviors = false;
1341#endif
1342 ConfigInputTrickleEventQueue = true;
1343 ConfigInputTextCursorBlink = true;
1344 ConfigInputTextEnterKeepActive = false;
1345 ConfigDragClickToInputText = false;
1346 ConfigWindowsResizeFromEdges = true;
1347 ConfigWindowsMoveFromTitleBarOnly = false;
1348 ConfigMemoryCompactTimer = 60.0f;
1349 ConfigDebugBeginReturnValueOnce = false;
1350 ConfigDebugBeginReturnValueLoop = false;
1351
1352 // Inputs Behaviors
1353 MouseDoubleClickTime = 0.30f;
1354 MouseDoubleClickMaxDist = 6.0f;
1355 MouseDragThreshold = 6.0f;
1356 KeyRepeatDelay = 0.275f;
1357 KeyRepeatRate = 0.050f;
1358
1359 // Platform Functions
1360 // Note: Initialize() will setup default clipboard/ime handlers.
1361 BackendPlatformName = BackendRendererName = NULL;
1362 BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1363 PlatformLocaleDecimalPoint = '.';
1364
1365 // Input (NB: we already have memset zero the entire structure!)
1366 MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1367 MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1368 MouseSource = ImGuiMouseSource_Mouse;
1369 for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1370 for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1371 AppAcceptingEvents = true;
1372 BackendUsingLegacyKeyArrays = (ImS8)-1;
1373 BackendUsingLegacyNavInputArray = true; // assume using legacy array until proven wrong
1374}
1375
1376// Pass in translated ASCII characters for text input.
1377// - with glfw you can get those from the callback set in glfwSetCharCallback()
1378// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1379// FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1380void ImGuiIO::AddInputCharacter(unsigned int c)
1381{
1382 IM_ASSERT(Ctx != NULL);
1383 ImGuiContext& g = *Ctx;
1384 if (c == 0 || !AppAcceptingEvents)
1385 return;
1386
1387 ImGuiInputEvent e;
1388 e.Type = ImGuiInputEventType_Text;
1389 e.Source = ImGuiInputSource_Keyboard;
1390 e.EventId = g.InputEventsNextEventId++;
1391 e.Text.Char = c;
1392 g.InputEventsQueue.push_back(e);
1393}
1394
1395// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1396// we should save the high surrogate.
1397void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1398{
1399 if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1400 return;
1401
1402 if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1403 {
1404 if (InputQueueSurrogate != 0)
1405 AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1406 InputQueueSurrogate = c;
1407 return;
1408 }
1409
1410 ImWchar cp = c;
1411 if (InputQueueSurrogate != 0)
1412 {
1413 if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1414 {
1415 AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1416 }
1417 else
1418 {
1419#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1420 cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1421#else
1422 cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1423#endif
1424 }
1425
1426 InputQueueSurrogate = 0;
1427 }
1428 AddInputCharacter((unsigned)cp);
1429}
1430
1431void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1432{
1433 if (!AppAcceptingEvents)
1434 return;
1435 while (*utf8_chars != 0)
1436 {
1437 unsigned int c = 0;
1438 utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
1439 AddInputCharacter(c);
1440 }
1441}
1442
1443// Clear all incoming events.
1444void ImGuiIO::ClearEventsQueue()
1445{
1446 IM_ASSERT(Ctx != NULL);
1447 ImGuiContext& g = *Ctx;
1448 g.InputEventsQueue.clear();
1449}
1450
1451// Clear current keyboard/mouse/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons.
1452void ImGuiIO::ClearInputKeys()
1453{
1454#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1455 memset(KeysDown, 0, sizeof(KeysDown));
1456#endif
1457 for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)
1458 {
1459 KeysData[n].Down = false;
1460 KeysData[n].DownDuration = -1.0f;
1461 KeysData[n].DownDurationPrev = -1.0f;
1462 }
1463 KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1464 KeyMods = ImGuiMod_None;
1465 MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1466 for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++)
1467 {
1468 MouseDown[n] = false;
1469 MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1470 }
1471 MouseWheel = MouseWheelH = 0.0f;
1472 InputQueueCharacters.resize(0); // Behavior of old ClearInputCharacters().
1473}
1474
1475// Removed this as it is ambiguous/misleading and generally incorrect to use with the existence of a higher-level input queue.
1476// Current frame character buffer is now also cleared by ClearInputKeys().
1477#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1478void ImGuiIO::ClearInputCharacters()
1479{
1480 InputQueueCharacters.resize(0);
1481}
1482#endif
1483
1484static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1)
1485{
1486 ImGuiContext& g = *ctx;
1487 for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1488 {
1489 ImGuiInputEvent* e = &g.InputEventsQueue[n];
1490 if (e->Type != type)
1491 continue;
1492 if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1493 continue;
1494 if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1495 continue;
1496 return e;
1497 }
1498 return NULL;
1499}
1500
1501// Queue a new key down/up event.
1502// - ImGuiKey key: Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1503// - bool down: Is the key down? use false to signify a key release.
1504// - float analog_value: 0.0f..1.0f
1505// IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE.
1506// WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULLFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT.
1507void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1508{
1509 //if (e->Down) { IMGUI_DEBUG_LOG_IO("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); }
1510 IM_ASSERT(Ctx != NULL);
1511 if (key == ImGuiKey_None || !AppAcceptingEvents)
1512 return;
1513 ImGuiContext& g = *Ctx;
1514 IM_ASSERT(ImGui::IsNamedKeyOrModKey(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API.
1515 IM_ASSERT(ImGui::IsAliasKey(key) == false); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1516 IM_ASSERT(key != ImGuiMod_Shortcut); // We could easily support the translation here but it seems saner to not accept it (TestEngine perform a translation itself)
1517
1518 // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data.
1519#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1520 IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1521 if (BackendUsingLegacyKeyArrays == -1)
1522 for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
1523 IM_ASSERT(KeyMap[n] == -1 && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1524 BackendUsingLegacyKeyArrays = 0;
1525#endif
1526 if (ImGui::IsGamepadKey(key))
1527 BackendUsingLegacyNavInputArray = false;
1528
1529 // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1530 const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key);
1531 const ImGuiKeyData* key_data = ImGui::GetKeyData(&g, key);
1532 const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1533 const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1534 if (latest_key_down == down && latest_key_analog == analog_value)
1535 return;
1536
1537 // Add event
1538 ImGuiInputEvent e;
1539 e.Type = ImGuiInputEventType_Key;
1540 e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1541 e.EventId = g.InputEventsNextEventId++;
1542 e.Key.Key = key;
1543 e.Key.Down = down;
1544 e.Key.AnalogValue = analog_value;
1545 g.InputEventsQueue.push_back(e);
1546}
1547
1548void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1549{
1550 if (!AppAcceptingEvents)
1551 return;
1552 AddKeyAnalogEvent(key, down, down ? 1.0f : 0.0f);
1553}
1554
1555// [Optional] Call after AddKeyEvent().
1556// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1557// If you are writing a backend in 2022 or don't use IsKeyXXX() with native values that are not ImGuiKey values, you can avoid calling this.
1558void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1559{
1560 if (key == ImGuiKey_None)
1561 return;
1562 IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1563 IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1564 IM_UNUSED(native_keycode); // Yet unused
1565 IM_UNUSED(native_scancode); // Yet unused
1566
1567 // Build native->imgui map so old user code can still call key functions with native 0..511 values.
1568#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1569 const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode;
1570 if (!ImGui::IsLegacyKey((ImGuiKey)legacy_key))
1571 return;
1572 KeyMap[legacy_key] = key;
1573 KeyMap[key] = legacy_key;
1574#else
1575 IM_UNUSED(key);
1576 IM_UNUSED(native_legacy_index);
1577#endif
1578}
1579
1580// Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen.
1581void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1582{
1583 AppAcceptingEvents = accepting_events;
1584}
1585
1586// Queue a mouse move event
1587void ImGuiIO::AddMousePosEvent(float x, float y)
1588{
1589 IM_ASSERT(Ctx != NULL);
1590 ImGuiContext& g = *Ctx;
1591 if (!AppAcceptingEvents)
1592 return;
1593
1594 // Apply same flooring as UpdateMouseInputs()
1595 ImVec2 pos((x > -FLT_MAX) ? ImFloor(x) : x, (y > -FLT_MAX) ? ImFloor(y) : y);
1596
1597 // Filter duplicate
1598 const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MousePos);
1599 const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1600 if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1601 return;
1602
1603 ImGuiInputEvent e;
1604 e.Type = ImGuiInputEventType_MousePos;
1605 e.Source = ImGuiInputSource_Mouse;
1606 e.EventId = g.InputEventsNextEventId++;
1607 e.MousePos.PosX = pos.x;
1608 e.MousePos.PosY = pos.y;
1609 e.MousePos.MouseSource = g.InputEventsNextMouseSource;
1610 g.InputEventsQueue.push_back(e);
1611}
1612
1613void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1614{
1615 IM_ASSERT(Ctx != NULL);
1616 ImGuiContext& g = *Ctx;
1617 IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1618 if (!AppAcceptingEvents)
1619 return;
1620
1621 // Filter duplicate
1622 const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseButton, (int)mouse_button);
1623 const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1624 if (latest_button_down == down)
1625 return;
1626
1627 ImGuiInputEvent e;
1628 e.Type = ImGuiInputEventType_MouseButton;
1629 e.Source = ImGuiInputSource_Mouse;
1630 e.EventId = g.InputEventsNextEventId++;
1631 e.MouseButton.Button = mouse_button;
1632 e.MouseButton.Down = down;
1633 e.MouseButton.MouseSource = g.InputEventsNextMouseSource;
1634 g.InputEventsQueue.push_back(e);
1635}
1636
1637// Queue a mouse wheel event (some mouse/API may only have a Y component)
1638void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
1639{
1640 IM_ASSERT(Ctx != NULL);
1641 ImGuiContext& g = *Ctx;
1642
1643 // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
1644 if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
1645 return;
1646
1647 ImGuiInputEvent e;
1648 e.Type = ImGuiInputEventType_MouseWheel;
1649 e.Source = ImGuiInputSource_Mouse;
1650 e.EventId = g.InputEventsNextEventId++;
1651 e.MouseWheel.WheelX = wheel_x;
1652 e.MouseWheel.WheelY = wheel_y;
1653 e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1654 g.InputEventsQueue.push_back(e);
1655}
1656
1657// This is not a real event, the data is latched in order to be stored in actual Mouse events.
1658// This is so that duplicate events (e.g. Windows sending extraneous WM_MOUSEMOVE) gets filtered and are not leading to actual source changes.
1659void ImGuiIO::AddMouseSourceEvent(ImGuiMouseSource source)
1660{
1661 IM_ASSERT(Ctx != NULL);
1662 ImGuiContext& g = *Ctx;
1663 g.InputEventsNextMouseSource = source;
1664}
1665
1666void ImGuiIO::AddMouseViewportEvent(ImGuiID viewport_id)
1667{
1668 IM_ASSERT(Ctx != NULL);
1669 ImGuiContext& g = *Ctx;
1670 //IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport);
1671 if (!AppAcceptingEvents)
1672 return;
1673
1674 // Filter duplicate
1675 const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseViewport);
1676 const ImGuiID latest_viewport_id = latest_event ? latest_event->MouseViewport.HoveredViewportID : g.IO.MouseHoveredViewport;
1677 if (latest_viewport_id == viewport_id)
1678 return;
1679
1680 ImGuiInputEvent e;
1681 e.Type = ImGuiInputEventType_MouseViewport;
1682 e.Source = ImGuiInputSource_Mouse;
1683 e.MouseViewport.HoveredViewportID = viewport_id;
1684 g.InputEventsQueue.push_back(e);
1685}
1686
1687void ImGuiIO::AddFocusEvent(bool focused)
1688{
1689 IM_ASSERT(Ctx != NULL);
1690 ImGuiContext& g = *Ctx;
1691
1692 // Filter duplicate
1693 const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Focus);
1694 const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
1695 if (latest_focused == focused || (ConfigDebugIgnoreFocusLoss && !focused))
1696 return;
1697
1698 ImGuiInputEvent e;
1699 e.Type = ImGuiInputEventType_Focus;
1700 e.EventId = g.InputEventsNextEventId++;
1701 e.AppFocused.Focused = focused;
1702 g.InputEventsQueue.push_back(e);
1703}
1704
1705//-----------------------------------------------------------------------------
1706// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
1707//-----------------------------------------------------------------------------
1708
1709ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
1710{
1711 IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
1712 ImVec2 p_last = p1;
1713 ImVec2 p_closest;
1714 float p_closest_dist2 = FLT_MAX;
1715 float t_step = 1.0f / (float)num_segments;
1716 for (int i_step = 1; i_step <= num_segments; i_step++)
1717 {
1718 ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
1719 ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1720 float dist2 = ImLengthSqr(p - p_line);
1721 if (dist2 < p_closest_dist2)
1722 {
1723 p_closest = p_line;
1724 p_closest_dist2 = dist2;
1725 }
1726 p_last = p_current;
1727 }
1728 return p_closest;
1729}
1730
1731// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
1732static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
1733{
1734 float dx = x4 - x1;
1735 float dy = y4 - y1;
1736 float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
1737 float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
1738 d2 = (d2 >= 0) ? d2 : -d2;
1739 d3 = (d3 >= 0) ? d3 : -d3;
1740 if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
1741 {
1742 ImVec2 p_current(x4, y4);
1743 ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1744 float dist2 = ImLengthSqr(p - p_line);
1745 if (dist2 < p_closest_dist2)
1746 {
1747 p_closest = p_line;
1748 p_closest_dist2 = dist2;
1749 }
1750 p_last = p_current;
1751 }
1752 else if (level < 10)
1753 {
1754 float x12 = (x1 + x2)*0.5f, y12 = (y1 + y2)*0.5f;
1755 float x23 = (x2 + x3)*0.5f, y23 = (y2 + y3)*0.5f;
1756 float x34 = (x3 + x4)*0.5f, y34 = (y3 + y4)*0.5f;
1757 float x123 = (x12 + x23)*0.5f, y123 = (y12 + y23)*0.5f;
1758 float x234 = (x23 + x34)*0.5f, y234 = (y23 + y34)*0.5f;
1759 float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
1760 ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
1761 ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
1762 }
1763}
1764
1765// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
1766// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
1767ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
1768{
1769 IM_ASSERT(tess_tol > 0.0f);
1770 ImVec2 p_last = p1;
1771 ImVec2 p_closest;
1772 float p_closest_dist2 = FLT_MAX;
1773 ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
1774 return p_closest;
1775}
1776
1777ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
1778{
1779 ImVec2 ap = p - a;
1780 ImVec2 ab_dir = b - a;
1781 float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
1782 if (dot < 0.0f)
1783 return a;
1784 float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
1785 if (dot > ab_len_sqr)
1786 return b;
1787 return a + ab_dir * dot / ab_len_sqr;
1788}
1789
1790bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1791{
1792 bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
1793 bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
1794 bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
1795 return ((b1 == b2) && (b2 == b3));
1796}
1797
1798void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
1799{
1800 ImVec2 v0 = b - a;
1801 ImVec2 v1 = c - a;
1802 ImVec2 v2 = p - a;
1803 const float denom = v0.x * v1.y - v1.x * v0.y;
1804 out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
1805 out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
1806 out_u = 1.0f - out_v - out_w;
1807}
1808
1809ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1810{
1811 ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
1812 ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
1813 ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
1814 float dist2_ab = ImLengthSqr(p - proj_ab);
1815 float dist2_bc = ImLengthSqr(p - proj_bc);
1816 float dist2_ca = ImLengthSqr(p - proj_ca);
1817 float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
1818 if (m == dist2_ab)
1819 return proj_ab;
1820 if (m == dist2_bc)
1821 return proj_bc;
1822 return proj_ca;
1823}
1824
1825//-----------------------------------------------------------------------------
1826// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
1827//-----------------------------------------------------------------------------
1828
1829// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
1830int ImStricmp(const char* str1, const char* str2)
1831{
1832 int d;
1833 while ((d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; }
1834 return d;
1835}
1836
1837int ImStrnicmp(const char* str1, const char* str2, size_t count)
1838{
1839 int d = 0;
1840 while (count > 0 && (d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
1841 return d;
1842}
1843
1844void ImStrncpy(char* dst, const char* src, size_t count)
1845{
1846 if (count < 1)
1847 return;
1848 if (count > 1)
1849 strncpy(dst, src, count - 1);
1850 dst[count - 1] = 0;
1851}
1852
1853char* ImStrdup(const char* str)
1854{
1855 size_t len = strlen(str);
1856 void* buf = IM_ALLOC(len + 1);
1857 return (char*)memcpy(buf, (const void*)str, len + 1);
1858}
1859
1860char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
1861{
1862 size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
1863 size_t src_size = strlen(src) + 1;
1864 if (dst_buf_size < src_size)
1865 {
1866 IM_FREE(dst);
1867 dst = (char*)IM_ALLOC(src_size);
1868 if (p_dst_size)
1869 *p_dst_size = src_size;
1870 }
1871 return (char*)memcpy(dst, (const void*)src, src_size);
1872}
1873
1874const char* ImStrchrRange(const char* str, const char* str_end, char c)
1875{
1876 const char* p = (const char*)memchr(str, (int)c, str_end - str);
1877 return p;
1878}
1879
1880int ImStrlenW(const ImWchar* str)
1881{
1882 //return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bit
1883 int n = 0;
1884 while (*str++) n++;
1885 return n;
1886}
1887
1888// Find end-of-line. Return pointer will point to either first \n, either str_end.
1889const char* ImStreolRange(const char* str, const char* str_end)
1890{
1891 const char* p = (const char*)memchr(str, '\n', str_end - str);
1892 return p ? p : str_end;
1893}
1894
1895const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
1896{
1897 while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
1898 buf_mid_line--;
1899 return buf_mid_line;
1900}
1901
1902const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
1903{
1904 if (!needle_end)
1905 needle_end = needle + strlen(needle);
1906
1907 const char un0 = (char)ImToUpper(*needle);
1908 while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
1909 {
1910 if (ImToUpper(*haystack) == un0)
1911 {
1912 const char* b = needle + 1;
1913 for (const char* a = haystack + 1; b < needle_end; a++, b++)
1914 if (ImToUpper(*a) != ImToUpper(*b))
1915 break;
1916 if (b == needle_end)
1917 return haystack;
1918 }
1919 haystack++;
1920 }
1921 return NULL;
1922}
1923
1924// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
1925void ImStrTrimBlanks(char* buf)
1926{
1927 char* p = buf;
1928 while (p[0] == ' ' || p[0] == '\t') // Leading blanks
1929 p++;
1930 char* p_start = p;
1931 while (*p != 0) // Find end of string
1932 p++;
1933 while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks
1934 p--;
1935 if (p_start != buf) // Copy memory if we had leading blanks
1936 memmove(buf, p_start, p - p_start);
1937 buf[p - p_start] = 0; // Zero terminate
1938}
1939
1940const char* ImStrSkipBlank(const char* str)
1941{
1942 while (str[0] == ' ' || str[0] == '\t')
1943 str++;
1944 return str;
1945}
1946
1947// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
1948// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
1949// B) When buf==NULL vsnprintf() will return the output size.
1950#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1951
1952// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
1953// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1954// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
1955// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
1956#ifdef IMGUI_USE_STB_SPRINTF
1957#ifndef IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION
1958#define STB_SPRINTF_IMPLEMENTATION
1959#endif
1960#ifdef IMGUI_STB_SPRINTF_FILENAME
1961#include IMGUI_STB_SPRINTF_FILENAME
1962#else
1963#include "stb_sprintf.h"
1964#endif
1965#endif // #ifdef IMGUI_USE_STB_SPRINTF
1966
1967#if defined(_MSC_VER) && !defined(vsnprintf)
1968#define vsnprintf _vsnprintf
1969#endif
1970
1971int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
1972{
1973 va_list args;
1974 va_start(args, fmt);
1975#ifdef IMGUI_USE_STB_SPRINTF
1976 int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1977#else
1978 int w = vsnprintf(buf, buf_size, fmt, args);
1979#endif
1980 va_end(args);
1981 if (buf == NULL)
1982 return w;
1983 if (w == -1 || w >= (int)buf_size)
1984 w = (int)buf_size - 1;
1985 buf[w] = 0;
1986 return w;
1987}
1988
1989int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
1990{
1991#ifdef IMGUI_USE_STB_SPRINTF
1992 int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1993#else
1994 int w = vsnprintf(buf, buf_size, fmt, args);
1995#endif
1996 if (buf == NULL)
1997 return w;
1998 if (w == -1 || w >= (int)buf_size)
1999 w = (int)buf_size - 1;
2000 buf[w] = 0;
2001 return w;
2002}
2003#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2004
2005void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
2006{
2007 va_list args;
2008 va_start(args, fmt);
2009 ImFormatStringToTempBufferV(out_buf, out_buf_end, fmt, args);
2010 va_end(args);
2011}
2012
2013void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
2014{
2015 ImGuiContext& g = *GImGui;
2016 if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
2017 {
2018 const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
2019 if (buf == NULL)
2020 buf = "(null)";
2021 *out_buf = buf;
2022 if (out_buf_end) { *out_buf_end = buf + strlen(buf); }
2023 }
2024 else if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '*' && fmt[3] == 's' && fmt[4] == 0)
2025 {
2026 int buf_len = va_arg(args, int); // Skip formatting when using "%.*s"
2027 const char* buf = va_arg(args, const char*);
2028 if (buf == NULL)
2029 {
2030 buf = "(null)";
2031 buf_len = ImMin(buf_len, 6);
2032 }
2033 *out_buf = buf;
2034 *out_buf_end = buf + buf_len; // Disallow not passing 'out_buf_end' here. User is expected to use it.
2035 }
2036 else
2037 {
2038 int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
2039 *out_buf = g.TempBuffer.Data;
2040 if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
2041 }
2042}
2043
2044// CRC32 needs a 1KB lookup table (not cache friendly)
2045// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
2046// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
2047static const ImU32 GCrc32LookupTable[256] =
2048{
2049 0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
2050 0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
2051 0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
2052 0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
2053 0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
2054 0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
2055 0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
2056 0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
2057 0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
2058 0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
2059 0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
2060 0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
2061 0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
2062 0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
2063 0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
2064 0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
2065};
2066
2067// Known size hash
2068// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
2069// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2070ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
2071{
2072 ImU32 crc = ~seed;
2073 const unsigned char* data = (const unsigned char*)data_p;
2074 const ImU32* crc32_lut = GCrc32LookupTable;
2075 while (data_size-- != 0)
2076 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
2077 return ~crc;
2078}
2079
2080// Zero-terminated string hash, with support for ### to reset back to seed value
2081// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
2082// Because this syntax is rarely used we are optimizing for the common case.
2083// - If we reach ### in the string we discard the hash so far and reset to the seed.
2084// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
2085// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2086ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
2087{
2088 seed = ~seed;
2089 ImU32 crc = seed;
2090 const unsigned char* data = (const unsigned char*)data_p;
2091 const ImU32* crc32_lut = GCrc32LookupTable;
2092 if (data_size != 0)
2093 {
2094 while (data_size-- != 0)
2095 {
2096 unsigned char c = *data++;
2097 if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
2098 crc = seed;
2099 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2100 }
2101 }
2102 else
2103 {
2104 while (unsigned char c = *data++)
2105 {
2106 if (c == '#' && data[0] == '#' && data[1] == '#')
2107 crc = seed;
2108 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2109 }
2110 }
2111 return ~crc;
2112}
2113
2114//-----------------------------------------------------------------------------
2115// [SECTION] MISC HELPERS/UTILITIES (File functions)
2116//-----------------------------------------------------------------------------
2117
2118// Default file functions
2119#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2120
2121ImFileHandle ImFileOpen(const char* filename, const char* mode)
2122{
2123#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
2124 // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
2125 // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
2126 const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
2127 const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
2128
2129 // Use stack buffer if possible, otherwise heap buffer. Sizes include zero terminator.
2130 // We don't rely on current ImGuiContext as this is implied to be a helper function which doesn't depend on it (see #7314).
2131 wchar_t local_temp_stack[FILENAME_MAX];
2132 ImVector<wchar_t> local_temp_heap;
2133 if (filename_wsize + mode_wsize > IM_ARRAYSIZE(local_temp_stack))
2134 local_temp_heap.resize(filename_wsize + mode_wsize);
2135 wchar_t* filename_wbuf = local_temp_heap.Data ? local_temp_heap.Data : local_temp_stack;
2136 wchar_t* mode_wbuf = filename_wbuf + filename_wsize;
2137 ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, filename_wbuf, filename_wsize);
2138 ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, mode_wbuf, mode_wsize);
2139 return ::_wfopen(filename_wbuf, mode_wbuf);
2140#else
2141 return fopen(filename, mode);
2142#endif
2143}
2144
2145// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
2146bool ImFileClose(ImFileHandle f) { return fclose(f) == 0; }
2147ImU64 ImFileGetSize(ImFileHandle f) { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
2148ImU64 ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fread(data, (size_t)sz, (size_t)count, f); }
2149ImU64 ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fwrite(data, (size_t)sz, (size_t)count, f); }
2150#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2151
2152// Helper: Load file content into memory
2153// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
2154// This can't really be used with "rt" because fseek size won't match read size.
2155void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
2156{
2157 IM_ASSERT(filename && mode);
2158 if (out_file_size)
2159 *out_file_size = 0;
2160
2161 ImFileHandle f;
2162 if ((f = ImFileOpen(filename, mode)) == NULL)
2163 return NULL;
2164
2165 size_t file_size = (size_t)ImFileGetSize(f);
2166 if (file_size == (size_t)-1)
2167 {
2168 ImFileClose(f);
2169 return NULL;
2170 }
2171
2172 void* file_data = IM_ALLOC(file_size + padding_bytes);
2173 if (file_data == NULL)
2174 {
2175 ImFileClose(f);
2176 return NULL;
2177 }
2178 if (ImFileRead(file_data, 1, file_size, f) != file_size)
2179 {
2180 ImFileClose(f);
2181 IM_FREE(file_data);
2182 return NULL;
2183 }
2184 if (padding_bytes > 0)
2185 memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
2186
2187 ImFileClose(f);
2188 if (out_file_size)
2189 *out_file_size = file_size;
2190
2191 return file_data;
2192}
2193
2194//-----------------------------------------------------------------------------
2195// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2196//-----------------------------------------------------------------------------
2197
2198IM_MSVC_RUNTIME_CHECKS_OFF
2199
2200// Convert UTF-8 to 32-bit character, process single character input.
2201// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2202// We handle UTF-8 decoding error by skipping forward.
2203int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2204{
2205 static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 };
2206 static const int masks[] = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2207 static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2208 static const int shiftc[] = { 0, 18, 12, 6, 0 };
2209 static const int shifte[] = { 0, 6, 4, 2, 0 };
2210 int len = lengths[*(const unsigned char*)in_text >> 3];
2211 int wanted = len + (len ? 0 : 1);
2212
2213 if (in_text_end == NULL)
2214 in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2215
2216 // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2217 // so it is fast even with excessive branching.
2218 unsigned char s[4];
2219 s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2220 s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2221 s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2222 s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2223
2224 // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2225 *out_char = (uint32_t)(s[0] & masks[len]) << 18;
2226 *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2227 *out_char |= (uint32_t)(s[2] & 0x3f) << 6;
2228 *out_char |= (uint32_t)(s[3] & 0x3f) << 0;
2229 *out_char >>= shiftc[len];
2230
2231 // Accumulate the various error conditions.
2232 int e = 0;
2233 e = (*out_char < mins[len]) << 6; // non-canonical encoding
2234 e |= ((*out_char >> 11) == 0x1b) << 7; // surrogate half?
2235 e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8; // out of range?
2236 e |= (s[1] & 0xc0) >> 2;
2237 e |= (s[2] & 0xc0) >> 4;
2238 e |= (s[3] ) >> 6;
2239 e ^= 0x2a; // top two bits of each tail byte correct?
2240 e >>= shifte[len];
2241
2242 if (e)
2243 {
2244 // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2245 // One byte is consumed in case of invalid first byte of in_text.
2246 // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2247 // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2248 wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2249 *out_char = IM_UNICODE_CODEPOINT_INVALID;
2250 }
2251
2252 return wanted;
2253}
2254
2255int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2256{
2257 ImWchar* buf_out = buf;
2258 ImWchar* buf_end = buf + buf_size;
2259 while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2260 {
2261 unsigned int c;
2262 in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2263 *buf_out++ = (ImWchar)c;
2264 }
2265 *buf_out = 0;
2266 if (in_text_remaining)
2267 *in_text_remaining = in_text;
2268 return (int)(buf_out - buf);
2269}
2270
2271int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2272{
2273 int char_count = 0;
2274 while ((!in_text_end || in_text < in_text_end) && *in_text)
2275 {
2276 unsigned int c;
2277 in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2278 char_count++;
2279 }
2280 return char_count;
2281}
2282
2283// Based on stb_to_utf8() from github.com/nothings/stb/
2284static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2285{
2286 if (c < 0x80)
2287 {
2288 buf[0] = (char)c;
2289 return 1;
2290 }
2291 if (c < 0x800)
2292 {
2293 if (buf_size < 2) return 0;
2294 buf[0] = (char)(0xc0 + (c >> 6));
2295 buf[1] = (char)(0x80 + (c & 0x3f));
2296 return 2;
2297 }
2298 if (c < 0x10000)
2299 {
2300 if (buf_size < 3) return 0;
2301 buf[0] = (char)(0xe0 + (c >> 12));
2302 buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2303 buf[2] = (char)(0x80 + ((c ) & 0x3f));
2304 return 3;
2305 }
2306 if (c <= 0x10FFFF)
2307 {
2308 if (buf_size < 4) return 0;
2309 buf[0] = (char)(0xf0 + (c >> 18));
2310 buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2311 buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2312 buf[3] = (char)(0x80 + ((c ) & 0x3f));
2313 return 4;
2314 }
2315 // Invalid code point, the max unicode is 0x10FFFF
2316 return 0;
2317}
2318
2319const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
2320{
2321 int count = ImTextCharToUtf8_inline(out_buf, 5, c);
2322 out_buf[count] = 0;
2323 return out_buf;
2324}
2325
2326// Not optimal but we very rarely use this function.
2327int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2328{
2329 unsigned int unused = 0;
2330 return ImTextCharFromUtf8(&unused, in_text, in_text_end);
2331}
2332
2333static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2334{
2335 if (c < 0x80) return 1;
2336 if (c < 0x800) return 2;
2337 if (c < 0x10000) return 3;
2338 if (c <= 0x10FFFF) return 4;
2339 return 3;
2340}
2341
2342int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2343{
2344 char* buf_p = out_buf;
2345 const char* buf_end = out_buf + out_buf_size;
2346 while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2347 {
2348 unsigned int c = (unsigned int)(*in_text++);
2349 if (c < 0x80)
2350 *buf_p++ = (char)c;
2351 else
2352 buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);
2353 }
2354 *buf_p = 0;
2355 return (int)(buf_p - out_buf);
2356}
2357
2358int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2359{
2360 int bytes_count = 0;
2361 while ((!in_text_end || in_text < in_text_end) && *in_text)
2362 {
2363 unsigned int c = (unsigned int)(*in_text++);
2364 if (c < 0x80)
2365 bytes_count++;
2366 else
2367 bytes_count += ImTextCountUtf8BytesFromChar(c);
2368 }
2369 return bytes_count;
2370}
2371
2372const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_text_curr)
2373{
2374 while (in_text_curr > in_text_start)
2375 {
2376 in_text_curr--;
2377 if ((*in_text_curr & 0xC0) != 0x80)
2378 return in_text_curr;
2379 }
2380 return in_text_start;
2381}
2382
2383IM_MSVC_RUNTIME_CHECKS_RESTORE
2384
2385//-----------------------------------------------------------------------------
2386// [SECTION] MISC HELPERS/UTILITIES (Color functions)
2387// Note: The Convert functions are early design which are not consistent with other API.
2388//-----------------------------------------------------------------------------
2389
2390IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2391{
2392 float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2393 int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2394 int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2395 int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2396 return IM_COL32(r, g, b, 0xFF);
2397}
2398
2399ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2400{
2401 float s = 1.0f / 255.0f;
2402 return ImVec4(
2403 ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2404 ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2405 ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2406 ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2407}
2408
2409ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2410{
2411 ImU32 out;
2412 out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2413 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2414 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2415 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2416 return out;
2417}
2418
2419// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2420// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2421void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2422{
2423 float K = 0.f;
2424 if (g < b)
2425 {
2426 ImSwap(g, b);
2427 K = -1.f;
2428 }
2429 if (r < g)
2430 {
2431 ImSwap(r, g);
2432 K = -2.f / 6.f - K;
2433 }
2434
2435 const float chroma = r - (g < b ? g : b);
2436 out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2437 out_s = chroma / (r + 1e-20f);
2438 out_v = r;
2439}
2440
2441// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2442// also http://en.wikipedia.org/wiki/HSL_and_HSV
2443void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2444{
2445 if (s == 0.0f)
2446 {
2447 // gray
2448 out_r = out_g = out_b = v;
2449 return;
2450 }
2451
2452 h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2453 int i = (int)h;
2454 float f = h - (float)i;
2455 float p = v * (1.0f - s);
2456 float q = v * (1.0f - s * f);
2457 float t = v * (1.0f - s * (1.0f - f));
2458
2459 switch (i)
2460 {
2461 case 0: out_r = v; out_g = t; out_b = p; break;
2462 case 1: out_r = q; out_g = v; out_b = p; break;
2463 case 2: out_r = p; out_g = v; out_b = t; break;
2464 case 3: out_r = p; out_g = q; out_b = v; break;
2465 case 4: out_r = t; out_g = p; out_b = v; break;
2466 case 5: default: out_r = v; out_g = p; out_b = q; break;
2467 }
2468}
2469
2470//-----------------------------------------------------------------------------
2471// [SECTION] ImGuiStorage
2472// Helper: Key->value storage
2473//-----------------------------------------------------------------------------
2474
2475// std::lower_bound but without the bullshit
2476static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)
2477{
2478 ImGuiStorage::ImGuiStoragePair* first = data.Data;
2479 ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;
2480 size_t count = (size_t)(last - first);
2481 while (count > 0)
2482 {
2483 size_t count2 = count >> 1;
2484 ImGuiStorage::ImGuiStoragePair* mid = first + count2;
2485 if (mid->key < key)
2486 {
2487 first = ++mid;
2488 count -= count2 + 1;
2489 }
2490 else
2491 {
2492 count = count2;
2493 }
2494 }
2495 return first;
2496}
2497
2498// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2499void ImGuiStorage::BuildSortByKey()
2500{
2501 struct StaticFunc
2502 {
2503 static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2504 {
2505 // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2506 if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;
2507 if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;
2508 return 0;
2509 }
2510 };
2511 ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairComparerByID);
2512}
2513
2514int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2515{
2516 ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2517 if (it == Data.end() || it->key != key)
2518 return default_val;
2519 return it->val_i;
2520}
2521
2522bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2523{
2524 return GetInt(key, default_val ? 1 : 0) != 0;
2525}
2526
2527float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2528{
2529 ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2530 if (it == Data.end() || it->key != key)
2531 return default_val;
2532 return it->val_f;
2533}
2534
2535void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
2536{
2537 ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2538 if (it == Data.end() || it->key != key)
2539 return NULL;
2540 return it->val_p;
2541}
2542
2543// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
2544int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
2545{
2546 ImGuiStoragePair* it = LowerBound(Data, key);
2547 if (it == Data.end() || it->key != key)
2548 it = Data.insert(it, ImGuiStoragePair(key, default_val));
2549 return &it->val_i;
2550}
2551
2552bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
2553{
2554 return (bool*)GetIntRef(key, default_val ? 1 : 0);
2555}
2556
2557float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
2558{
2559 ImGuiStoragePair* it = LowerBound(Data, key);
2560 if (it == Data.end() || it->key != key)
2561 it = Data.insert(it, ImGuiStoragePair(key, default_val));
2562 return &it->val_f;
2563}
2564
2565void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2566{
2567 ImGuiStoragePair* it = LowerBound(Data, key);
2568 if (it == Data.end() || it->key != key)
2569 it = Data.insert(it, ImGuiStoragePair(key, default_val));
2570 return &it->val_p;
2571}
2572
2573// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
2574void ImGuiStorage::SetInt(ImGuiID key, int val)
2575{
2576 ImGuiStoragePair* it = LowerBound(Data, key);
2577 if (it == Data.end() || it->key != key)
2578 Data.insert(it, ImGuiStoragePair(key, val));
2579 else
2580 it->val_i = val;
2581}
2582
2583void ImGuiStorage::SetBool(ImGuiID key, bool val)
2584{
2585 SetInt(key, val ? 1 : 0);
2586}
2587
2588void ImGuiStorage::SetFloat(ImGuiID key, float val)
2589{
2590 ImGuiStoragePair* it = LowerBound(Data, key);
2591 if (it == Data.end() || it->key != key)
2592 Data.insert(it, ImGuiStoragePair(key, val));
2593 else
2594 it->val_f = val;
2595}
2596
2597void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2598{
2599 ImGuiStoragePair* it = LowerBound(Data, key);
2600 if (it == Data.end() || it->key != key)
2601 Data.insert(it, ImGuiStoragePair(key, val));
2602 else
2603 it->val_p = val;
2604}
2605
2606void ImGuiStorage::SetAllInt(int v)
2607{
2608 for (int i = 0; i < Data.Size; i++)
2609 Data[i].val_i = v;
2610}
2611
2612//-----------------------------------------------------------------------------
2613// [SECTION] ImGuiTextFilter
2614//-----------------------------------------------------------------------------
2615
2616// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2617ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
2618{
2619 InputBuf[0] = 0;
2620 CountGrep = 0;
2621 if (default_filter)
2622 {
2623 ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
2624 Build();
2625 }
2626}
2627
2628bool ImGuiTextFilter::Draw(const char* label, float width)
2629{
2630 if (width != 0.0f)
2631 ImGui::SetNextItemWidth(width);
2632 bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
2633 if (value_changed)
2634 Build();
2635 return value_changed;
2636}
2637
2638void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
2639{
2640 out->resize(0);
2641 const char* wb = b;
2642 const char* we = wb;
2643 while (we < e)
2644 {
2645 if (*we == separator)
2646 {
2647 out->push_back(ImGuiTextRange(wb, we));
2648 wb = we + 1;
2649 }
2650 we++;
2651 }
2652 if (wb != we)
2653 out->push_back(ImGuiTextRange(wb, we));
2654}
2655
2656void ImGuiTextFilter::Build()
2657{
2658 Filters.resize(0);
2659 ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
2660 input_range.split(',', &Filters);
2661
2662 CountGrep = 0;
2663 for (ImGuiTextRange& f : Filters)
2664 {
2665 while (f.b < f.e && ImCharIsBlankA(f.b[0]))
2666 f.b++;
2667 while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
2668 f.e--;
2669 if (f.empty())
2670 continue;
2671 if (f.b[0] != '-')
2672 CountGrep += 1;
2673 }
2674}
2675
2676bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
2677{
2678 if (Filters.empty())
2679 return true;
2680
2681 if (text == NULL)
2682 text = "";
2683
2684 for (const ImGuiTextRange& f : Filters)
2685 {
2686 if (f.empty())
2687 continue;
2688 if (f.b[0] == '-')
2689 {
2690 // Subtract
2691 if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
2692 return false;
2693 }
2694 else
2695 {
2696 // Grep
2697 if (ImStristr(text, text_end, f.b, f.e) != NULL)
2698 return true;
2699 }
2700 }
2701
2702 // Implicit * grep
2703 if (CountGrep == 0)
2704 return true;
2705
2706 return false;
2707}
2708
2709//-----------------------------------------------------------------------------
2710// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
2711//-----------------------------------------------------------------------------
2712
2713// On some platform vsnprintf() takes va_list by reference and modifies it.
2714// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
2715#ifndef va_copy
2716#if defined(__GNUC__) || defined(__clang__)
2717#define va_copy(dest, src) __builtin_va_copy(dest, src)
2718#else
2719#define va_copy(dest, src) (dest = src)
2720#endif
2721#endif
2722
2723char ImGuiTextBuffer::EmptyString[1] = { 0 };
2724
2725void ImGuiTextBuffer::append(const char* str, const char* str_end)
2726{
2727 int len = str_end ? (int)(str_end - str) : (int)strlen(str);
2728
2729 // Add zero-terminator the first time
2730 const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2731 const int needed_sz = write_off + len;
2732 if (write_off + len >= Buf.Capacity)
2733 {
2734 int new_capacity = Buf.Capacity * 2;
2735 Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2736 }
2737
2738 Buf.resize(needed_sz);
2739 memcpy(&Buf[write_off - 1], str, (size_t)len);
2740 Buf[write_off - 1 + len] = 0;
2741}
2742
2743void ImGuiTextBuffer::appendf(const char* fmt, ...)
2744{
2745 va_list args;
2746 va_start(args, fmt);
2747 appendfv(fmt, args);
2748 va_end(args);
2749}
2750
2751// Helper: Text buffer for logging/accumulating text
2752void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
2753{
2754 va_list args_copy;
2755 va_copy(args_copy, args);
2756
2757 int len = ImFormatStringV(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
2758 if (len <= 0)
2759 {
2760 va_end(args_copy);
2761 return;
2762 }
2763
2764 // Add zero-terminator the first time
2765 const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2766 const int needed_sz = write_off + len;
2767 if (write_off + len >= Buf.Capacity)
2768 {
2769 int new_capacity = Buf.Capacity * 2;
2770 Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2771 }
2772
2773 Buf.resize(needed_sz);
2774 ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
2775 va_end(args_copy);
2776}
2777
2778void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
2779{
2780 IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
2781 if (old_size == new_size)
2782 return;
2783 if (EndOffset == 0 || base[EndOffset - 1] == '\n')
2784 LineOffsets.push_back(EndOffset);
2785 const char* base_end = base + new_size;
2786 for (const char* p = base + old_size; (p = (const char*)memchr(p, '\n', base_end - p)) != 0; )
2787 if (++p < base_end) // Don't push a trailing offset on last \n
2788 LineOffsets.push_back((int)(intptr_t)(p - base));
2789 EndOffset = ImMax(EndOffset, new_size);
2790}
2791
2792//-----------------------------------------------------------------------------
2793// [SECTION] ImGuiListClipper
2794//-----------------------------------------------------------------------------
2795
2796// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
2797// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
2798static bool GetSkipItemForListClipping()
2799{
2800 ImGuiContext& g = *GImGui;
2801 return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
2802}
2803
2804static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
2805{
2806 if (ranges.Size - offset <= 1)
2807 return;
2808
2809 // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
2810 for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
2811 for (int i = offset; i < sort_end + offset; ++i)
2812 if (ranges[i].Min > ranges[i + 1].Min)
2813 ImSwap(ranges[i], ranges[i + 1]);
2814
2815 // Now fuse ranges together as much as possible.
2816 for (int i = 1 + offset; i < ranges.Size; i++)
2817 {
2818 IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
2819 if (ranges[i - 1].Max < ranges[i].Min)
2820 continue;
2821 ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min);
2822 ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max);
2823 ranges.erase(ranges.Data + i);
2824 i--;
2825 }
2826}
2827
2828static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
2829{
2830 // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
2831 // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
2832 // The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek?
2833 ImGuiContext& g = *GImGui;
2834 ImGuiWindow* window = g.CurrentWindow;
2835 float off_y = pos_y - window->DC.CursorPos.y;
2836 window->DC.CursorPos.y = pos_y;
2837 window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y);
2838 window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
2839 window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
2840 if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
2841 columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
2842 if (ImGuiTable* table = g.CurrentTable)
2843 {
2844 if (table->IsInsideRow)
2845 ImGui::TableEndRow(table);
2846 table->RowPosY2 = window->DC.CursorPos.y;
2847 const int row_increase = (int)((off_y / line_height) + 0.5f);
2848 //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
2849 table->RowBgColorCounter += row_increase;
2850 }
2851}
2852
2853static void ImGuiListClipper_SeekCursorForItem(ImGuiListClipper* clipper, int item_n)
2854{
2855 // StartPosY starts from ItemsFrozen hence the subtraction
2856 // Perform the add and multiply with double to allow seeking through larger ranges
2857 ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2858 float pos_y = (float)((double)clipper->StartPosY + data->LossynessOffset + (double)(item_n - data->ItemsFrozen) * clipper->ItemsHeight);
2859 ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, clipper->ItemsHeight);
2860}
2861
2862ImGuiListClipper::ImGuiListClipper()
2863{
2864 memset(this, 0, sizeof(*this));
2865}
2866
2867ImGuiListClipper::~ImGuiListClipper()
2868{
2869 End();
2870}
2871
2872void ImGuiListClipper::Begin(int items_count, float items_height)
2873{
2874 if (Ctx == NULL)
2875 Ctx = ImGui::GetCurrentContext();
2876
2877 ImGuiContext& g = *Ctx;
2878 ImGuiWindow* window = g.CurrentWindow;
2879 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
2880
2881 if (ImGuiTable* table = g.CurrentTable)
2882 if (table->IsInsideRow)
2883 ImGui::TableEndRow(table);
2884
2885 StartPosY = window->DC.CursorPos.y;
2886 ItemsHeight = items_height;
2887 ItemsCount = items_count;
2888 DisplayStart = -1;
2889 DisplayEnd = 0;
2890
2891 // Acquire temporary buffer
2892 if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
2893 g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData());
2894 ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2895 data->Reset(this);
2896 data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
2897 TempData = data;
2898}
2899
2900void ImGuiListClipper::End()
2901{
2902 if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
2903 {
2904 // In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user.
2905 ImGuiContext& g = *Ctx;
2906 IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
2907 if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
2908 ImGuiListClipper_SeekCursorForItem(this, ItemsCount);
2909
2910 // Restore temporary buffer and fix back pointers which may be invalidated when nesting
2911 IM_ASSERT(data->ListClipper == this);
2912 data->StepNo = data->Ranges.Size;
2913 if (--g.ClipperTempDataStacked > 0)
2914 {
2915 data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2916 data->ListClipper->TempData = data;
2917 }
2918 TempData = NULL;
2919 }
2920 ItemsCount = -1;
2921}
2922
2923void ImGuiListClipper::IncludeItemsByIndex(int item_begin, int item_end)
2924{
2925 ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
2926 IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
2927 IM_ASSERT(item_begin <= item_end);
2928 if (item_begin < item_end)
2929 data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_begin, item_end));
2930}
2931
2932static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
2933{
2934 ImGuiContext& g = *clipper->Ctx;
2935 ImGuiWindow* window = g.CurrentWindow;
2936 ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2937 IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
2938
2939 ImGuiTable* table = g.CurrentTable;
2940 if (table && table->IsInsideRow)
2941 ImGui::TableEndRow(table);
2942
2943 // No items
2944 if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
2945 return false;
2946
2947 // While we are in frozen row state, keep displaying items one by one, unclipped
2948 // FIXME: Could be stored as a table-agnostic state.
2949 if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
2950 {
2951 clipper->DisplayStart = data->ItemsFrozen;
2952 clipper->DisplayEnd = ImMin(data->ItemsFrozen + 1, clipper->ItemsCount);
2953 if (clipper->DisplayStart < clipper->DisplayEnd)
2954 data->ItemsFrozen++;
2955 return true;
2956 }
2957
2958 // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
2959 bool calc_clipping = false;
2960 if (data->StepNo == 0)
2961 {
2962 clipper->StartPosY = window->DC.CursorPos.y;
2963 if (clipper->ItemsHeight <= 0.0f)
2964 {
2965 // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
2966 data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1));
2967 clipper->DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen);
2968 clipper->DisplayEnd = ImMin(data->Ranges[0].Max, clipper->ItemsCount);
2969 data->StepNo = 1;
2970 return true;
2971 }
2972 calc_clipping = true; // If on the first step with known item height, calculate clipping.
2973 }
2974
2975 // Step 1: Let the clipper infer height from first range
2976 if (clipper->ItemsHeight <= 0.0f)
2977 {
2978 IM_ASSERT(data->StepNo == 1);
2979 if (table)
2980 IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
2981
2982 clipper->ItemsHeight = (window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
2983 bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);
2984 if (affected_by_floating_point_precision)
2985 clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
2986
2987 IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
2988 calc_clipping = true; // If item height had to be calculated, calculate clipping afterwards.
2989 }
2990
2991 // Step 0 or 1: Calculate the actual ranges of visible elements.
2992 const int already_submitted = clipper->DisplayEnd;
2993 if (calc_clipping)
2994 {
2995 if (g.LogEnabled)
2996 {
2997 // If logging is active, do not perform any clipping
2998 data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, clipper->ItemsCount));
2999 }
3000 else
3001 {
3002 // Add range selected to be included for navigation
3003 const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
3004 if (is_nav_request)
3005 data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0));
3006 if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && g.NavTabbingDir == -1)
3007 data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount));
3008
3009 // Add focused/active item
3010 ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]);
3011 if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
3012 data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0));
3013
3014 // Add visible range
3015 const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
3016 const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
3017 data->Ranges.push_back(ImGuiListClipperRange::FromPositions(window->ClipRect.Min.y, window->ClipRect.Max.y, off_min, off_max));
3018 }
3019
3020 // Convert position ranges to item index ranges
3021 // - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping.
3022 // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
3023 // which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
3024 for (ImGuiListClipperRange& range : data->Ranges)
3025 if (range.PosToIndexConvert)
3026 {
3027 int m1 = (int)(((double)range.Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
3028 int m2 = (int)((((double)range.Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
3029 range.Min = ImClamp(already_submitted + m1 + range.PosToIndexOffsetMin, already_submitted, clipper->ItemsCount - 1);
3030 range.Max = ImClamp(already_submitted + m2 + range.PosToIndexOffsetMax, range.Min + 1, clipper->ItemsCount);
3031 range.PosToIndexConvert = false;
3032 }
3033 ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo);
3034 }
3035
3036 // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
3037 while (data->StepNo < data->Ranges.Size)
3038 {
3039 clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted);
3040 clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount);
3041 if (clipper->DisplayStart > already_submitted) //-V1051
3042 ImGuiListClipper_SeekCursorForItem(clipper, clipper->DisplayStart);
3043 data->StepNo++;
3044 if (clipper->DisplayStart == clipper->DisplayEnd && data->StepNo < data->Ranges.Size)
3045 continue;
3046 return true;
3047 }
3048
3049 // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
3050 // Advance the cursor to the end of the list and then returns 'false' to end the loop.
3051 if (clipper->ItemsCount < INT_MAX)
3052 ImGuiListClipper_SeekCursorForItem(clipper, clipper->ItemsCount);
3053
3054 return false;
3055}
3056
3057bool ImGuiListClipper::Step()
3058{
3059 ImGuiContext& g = *Ctx;
3060 bool need_items_height = (ItemsHeight <= 0.0f);
3061 bool ret = ImGuiListClipper_StepInternal(this);
3062 if (ret && (DisplayStart == DisplayEnd))
3063 ret = false;
3064 if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
3065 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
3066 if (need_items_height && ItemsHeight > 0.0f)
3067 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
3068 if (ret)
3069 {
3070 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
3071 }
3072 else
3073 {
3074 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
3075 End();
3076 }
3077 return ret;
3078}
3079
3080//-----------------------------------------------------------------------------
3081// [SECTION] STYLING
3082//-----------------------------------------------------------------------------
3083
3084ImGuiStyle& ImGui::GetStyle()
3085{
3086 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
3087 return GImGui->Style;
3088}
3089
3090ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
3091{
3092 ImGuiStyle& style = GImGui->Style;
3093 ImVec4 c = style.Colors[idx];
3094 c.w *= style.Alpha * alpha_mul;
3095 return ColorConvertFloat4ToU32(c);
3096}
3097
3098ImU32 ImGui::GetColorU32(const ImVec4& col)
3099{
3100 ImGuiStyle& style = GImGui->Style;
3101 ImVec4 c = col;
3102 c.w *= style.Alpha;
3103 return ColorConvertFloat4ToU32(c);
3104}
3105
3106const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
3107{
3108 ImGuiStyle& style = GImGui->Style;
3109 return style.Colors[idx];
3110}
3111
3112ImU32 ImGui::GetColorU32(ImU32 col, float alpha_mul)
3113{
3114 ImGuiStyle& style = GImGui->Style;
3115 alpha_mul *= style.Alpha;
3116 if (alpha_mul >= 1.0f)
3117 return col;
3118 ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
3119 a = (ImU32)(a * alpha_mul); // We don't need to clamp 0..255 because alpha is in 0..1 range.
3120 return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
3121}
3122
3123// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
3124void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
3125{
3126 ImGuiContext& g = *GImGui;
3127 ImGuiColorMod backup;
3128 backup.Col = idx;
3129 backup.BackupValue = g.Style.Colors[idx];
3130 g.ColorStack.push_back(backup);
3131 if (g.DebugFlashStyleColorIdx != idx)
3132 g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
3133}
3134
3135void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
3136{
3137 ImGuiContext& g = *GImGui;
3138 ImGuiColorMod backup;
3139 backup.Col = idx;
3140 backup.BackupValue = g.Style.Colors[idx];
3141 g.ColorStack.push_back(backup);
3142 if (g.DebugFlashStyleColorIdx != idx)
3143 g.Style.Colors[idx] = col;
3144}
3145
3146void ImGui::PopStyleColor(int count)
3147{
3148 ImGuiContext& g = *GImGui;
3149 if (g.ColorStack.Size < count)
3150 {
3151 IM_ASSERT_USER_ERROR(g.ColorStack.Size > count, "Calling PopStyleColor() too many times!");
3152 count = g.ColorStack.Size;
3153 }
3154 while (count > 0)
3155 {
3156 ImGuiColorMod& backup = g.ColorStack.back();
3157 g.Style.Colors[backup.Col] = backup.BackupValue;
3158 g.ColorStack.pop_back();
3159 count--;
3160 }
3161}
3162
3163static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] =
3164{
3165 ImGuiCol_Text, ImGuiCol_Tab, ImGuiCol_TabHovered, ImGuiCol_TabActive, ImGuiCol_TabUnfocused, ImGuiCol_TabUnfocusedActive
3166};
3167
3168static const ImGuiDataVarInfo GStyleVarInfo[] =
3169{
3170 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
3171 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, DisabledAlpha) }, // ImGuiStyleVar_DisabledAlpha
3172 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
3173 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
3174 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
3175 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
3176 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
3177 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
3178 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
3179 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
3180 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
3181 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
3182 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
3183 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
3184 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
3185 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
3186 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
3187 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, CellPadding) }, // ImGuiStyleVar_CellPadding
3188 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
3189 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
3190 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
3191 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
3192 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding
3193 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBarBorderSize) }, // ImGuiStyleVar_TabBarBorderSize
3194 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
3195 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
3196 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize) },// ImGuiStyleVar_SeparatorTextBorderSize
3197 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextAlign) }, // ImGuiStyleVar_SeparatorTextAlign
3198 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextPadding) }, // ImGuiStyleVar_SeparatorTextPadding
3199 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, DockingSeparatorSize) }, // ImGuiStyleVar_DockingSeparatorSize
3200};
3201
3202const ImGuiDataVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx)
3203{
3204 IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3205 IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
3206 return &GStyleVarInfo[idx];
3207}
3208
3209void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3210{
3211 ImGuiContext& g = *GImGui;
3212 const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3213 if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
3214 {
3215 float* pvar = (float*)var_info->GetVarPtr(&g.Style);
3216 g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3217 *pvar = val;
3218 return;
3219 }
3220 IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3221}
3222
3223void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3224{
3225 ImGuiContext& g = *GImGui;
3226 const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3227 if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
3228 {
3229 ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3230 g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3231 *pvar = val;
3232 return;
3233 }
3234 IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3235}
3236
3237void ImGui::PopStyleVar(int count)
3238{
3239 ImGuiContext& g = *GImGui;
3240 if (g.StyleVarStack.Size < count)
3241 {
3242 IM_ASSERT_USER_ERROR(g.StyleVarStack.Size > count, "Calling PopStyleVar() too many times!");
3243 count = g.StyleVarStack.Size;
3244 }
3245 while (count > 0)
3246 {
3247 // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3248 ImGuiStyleMod& backup = g.StyleVarStack.back();
3249 const ImGuiDataVarInfo* info = GetStyleVarInfo(backup.VarIdx);
3250 void* data = info->GetVarPtr(&g.Style);
3251 if (info->Type == ImGuiDataType_Float && info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; }
3252 else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3253 g.StyleVarStack.pop_back();
3254 count--;
3255 }
3256}
3257
3258const char* ImGui::GetStyleColorName(ImGuiCol idx)
3259{
3260 // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3261 switch (idx)
3262 {
3263 case ImGuiCol_Text: return "Text";
3264 case ImGuiCol_TextDisabled: return "TextDisabled";
3265 case ImGuiCol_WindowBg: return "WindowBg";
3266 case ImGuiCol_ChildBg: return "ChildBg";
3267 case ImGuiCol_PopupBg: return "PopupBg";
3268 case ImGuiCol_Border: return "Border";
3269 case ImGuiCol_BorderShadow: return "BorderShadow";
3270 case ImGuiCol_FrameBg: return "FrameBg";
3271 case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3272 case ImGuiCol_FrameBgActive: return "FrameBgActive";
3273 case ImGuiCol_TitleBg: return "TitleBg";
3274 case ImGuiCol_TitleBgActive: return "TitleBgActive";
3275 case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3276 case ImGuiCol_MenuBarBg: return "MenuBarBg";
3277 case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3278 case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3279 case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3280 case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3281 case ImGuiCol_CheckMark: return "CheckMark";
3282 case ImGuiCol_SliderGrab: return "SliderGrab";
3283 case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3284 case ImGuiCol_Button: return "Button";
3285 case ImGuiCol_ButtonHovered: return "ButtonHovered";
3286 case ImGuiCol_ButtonActive: return "ButtonActive";
3287 case ImGuiCol_Header: return "Header";
3288 case ImGuiCol_HeaderHovered: return "HeaderHovered";
3289 case ImGuiCol_HeaderActive: return "HeaderActive";
3290 case ImGuiCol_Separator: return "Separator";
3291 case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3292 case ImGuiCol_SeparatorActive: return "SeparatorActive";
3293 case ImGuiCol_ResizeGrip: return "ResizeGrip";
3294 case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3295 case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3296 case ImGuiCol_Tab: return "Tab";
3297 case ImGuiCol_TabHovered: return "TabHovered";
3298 case ImGuiCol_TabActive: return "TabActive";
3299 case ImGuiCol_TabUnfocused: return "TabUnfocused";
3300 case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
3301 case ImGuiCol_DockingPreview: return "DockingPreview";
3302 case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
3303 case ImGuiCol_PlotLines: return "PlotLines";
3304 case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3305 case ImGuiCol_PlotHistogram: return "PlotHistogram";
3306 case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3307 case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3308 case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3309 case ImGuiCol_TableBorderLight: return "TableBorderLight";
3310 case ImGuiCol_TableRowBg: return "TableRowBg";
3311 case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3312 case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3313 case ImGuiCol_DragDropTarget: return "DragDropTarget";
3314 case ImGuiCol_NavHighlight: return "NavHighlight";
3315 case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3316 case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3317 case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3318 }
3319 IM_ASSERT(0);
3320 return "Unknown";
3321}
3322
3323
3324//-----------------------------------------------------------------------------
3325// [SECTION] RENDER HELPERS
3326// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3327// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3328// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3329//-----------------------------------------------------------------------------
3330
3331const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3332{
3333 const char* text_display_end = text;
3334 if (!text_end)
3335 text_end = (const char*)-1;
3336
3337 while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3338 text_display_end++;
3339 return text_display_end;
3340}
3341
3342// Internal ImGui functions to render text
3343// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3344void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3345{
3346 ImGuiContext& g = *GImGui;
3347 ImGuiWindow* window = g.CurrentWindow;
3348
3349 // Hide anything after a '##' string
3350 const char* text_display_end;
3351 if (hide_text_after_hash)
3352 {
3353 text_display_end = FindRenderedTextEnd(text, text_end);
3354 }
3355 else
3356 {
3357 if (!text_end)
3358 text_end = text + strlen(text); // FIXME-OPT
3359 text_display_end = text_end;
3360 }
3361
3362 if (text != text_display_end)
3363 {
3364 window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
3365 if (g.LogEnabled)
3366 LogRenderedText(&pos, text, text_display_end);
3367 }
3368}
3369
3370void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3371{
3372 ImGuiContext& g = *GImGui;
3373 ImGuiWindow* window = g.CurrentWindow;
3374
3375 if (!text_end)
3376 text_end = text + strlen(text); // FIXME-OPT
3377
3378 if (text != text_end)
3379 {
3380 window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
3381 if (g.LogEnabled)
3382 LogRenderedText(&pos, text, text_end);
3383 }
3384}
3385
3386// Default clip_rect uses (pos_min,pos_max)
3387// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3388// FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especally for text above draw_list->DrawList.
3389// Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take
3390// better advantage of the render function taking size into account for coarse clipping.
3391void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3392{
3393 // Perform CPU side clipping for single clipped element to avoid using scissor state
3394 ImVec2 pos = pos_min;
3395 const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
3396
3397 const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3398 const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3399 bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3400 if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3401 need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3402
3403 // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3404 if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3405 if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3406
3407 // Render
3408 if (need_clipping)
3409 {
3410 ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3411 draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
3412 }
3413 else
3414 {
3415 draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
3416 }
3417}
3418
3419void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3420{
3421 // Hide anything after a '##' string
3422 const char* text_display_end = FindRenderedTextEnd(text, text_end);
3423 const int text_len = (int)(text_display_end - text);
3424 if (text_len == 0)
3425 return;
3426
3427 ImGuiContext& g = *GImGui;
3428 ImGuiWindow* window = g.CurrentWindow;
3429 RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3430 if (g.LogEnabled)
3431 LogRenderedText(&pos_min, text, text_display_end);
3432}
3433
3434// Another overly complex function until we reorganize everything into a nice all-in-one helper.
3435// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
3436// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
3437void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
3438{
3439 ImGuiContext& g = *GImGui;
3440 if (text_end_full == NULL)
3441 text_end_full = FindRenderedTextEnd(text);
3442 const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
3443
3444 //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
3445 //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
3446 //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
3447 // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3448 if (text_size.x > pos_max.x - pos_min.x)
3449 {
3450 // Hello wo...
3451 // | | |
3452 // min max ellipsis_max
3453 // <-> this is generally some padding value
3454
3455 const ImFont* font = draw_list->_Data->Font;
3456 const float font_size = draw_list->_Data->FontSize;
3457 const float font_scale = font_size / font->FontSize;
3458 const char* text_end_ellipsis = NULL;
3459 const float ellipsis_width = font->EllipsisWidth * font_scale;
3460
3461 // We can now claim the space between pos_max.x and ellipsis_max.x
3462 const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_width) - pos_min.x, 1.0f);
3463 float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
3464 if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
3465 {
3466 // Always display at least 1 character if there's no room for character + ellipsis
3467 text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
3468 text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
3469 }
3470 while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
3471 {
3472 // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
3473 text_end_ellipsis--;
3474 text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
3475 }
3476
3477 // Render text, render ellipsis
3478 RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
3479 ImVec2 ellipsis_pos = ImTrunc(ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
3480 if (ellipsis_pos.x + ellipsis_width <= ellipsis_max_x)
3481 for (int i = 0; i < font->EllipsisCharCount; i++, ellipsis_pos.x += font->EllipsisCharStep * font_scale)
3482 font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar);
3483 }
3484 else
3485 {
3486 RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
3487 }
3488
3489 if (g.LogEnabled)
3490 LogRenderedText(&pos_min, text, text_end_full);
3491}
3492
3493// Render a rectangle shaped with optional rounding and borders
3494void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
3495{
3496 ImGuiContext& g = *GImGui;
3497 ImGuiWindow* window = g.CurrentWindow;
3498 window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
3499 const float border_size = g.Style.FrameBorderSize;
3500 if (border && border_size > 0.0f)
3501 {
3502 window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3503 window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3504 }
3505}
3506
3507void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
3508{
3509 ImGuiContext& g = *GImGui;
3510 ImGuiWindow* window = g.CurrentWindow;
3511 const float border_size = g.Style.FrameBorderSize;
3512 if (border_size > 0.0f)
3513 {
3514 window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3515 window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3516 }
3517}
3518
3519void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
3520{
3521 ImGuiContext& g = *GImGui;
3522 if (id != g.NavId)
3523 return;
3524 if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
3525 return;
3526 ImGuiWindow* window = g.CurrentWindow;
3527 if (window->DC.NavHideHighlightOneFrame)
3528 return;
3529
3530 float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
3531 ImRect display_rect = bb;
3532 display_rect.ClipWith(window->ClipRect);
3533 const float thickness = 2.0f;
3534 if (flags & ImGuiNavHighlightFlags_Compact)
3535 {
3536 window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, thickness);
3537 }
3538 else
3539 {
3540 const float distance = 3.0f + thickness * 0.5f;
3541 display_rect.Expand(ImVec2(distance, distance));
3542 bool fully_visible = window->ClipRect.Contains(display_rect);
3543 if (!fully_visible)
3544 window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
3545 window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, thickness);
3546 if (!fully_visible)
3547 window->DrawList->PopClipRect();
3548 }
3549}
3550
3551void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
3552{
3553 ImGuiContext& g = *GImGui;
3554 IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT);
3555 ImFontAtlas* font_atlas = g.DrawListSharedData.Font->ContainerAtlas;
3556 for (ImGuiViewportP* viewport : g.Viewports)
3557 {
3558 // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
3559 ImVec2 offset, size, uv[4];
3560 if (!font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2]))
3561 continue;
3562 const ImVec2 pos = base_pos - offset;
3563 const float scale = base_scale * viewport->DpiScale;
3564 if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
3565 continue;
3566 ImDrawList* draw_list = GetForegroundDrawList(viewport);
3567 ImTextureID tex_id = font_atlas->TexID;
3568 draw_list->PushTextureID(tex_id);
3569 draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow);
3570 draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow);
3571 draw_list->AddImage(tex_id, pos, pos + size * scale, uv[2], uv[3], col_border);
3572 draw_list->AddImage(tex_id, pos, pos + size * scale, uv[0], uv[1], col_fill);
3573 draw_list->PopTextureID();
3574 }
3575}
3576
3577//-----------------------------------------------------------------------------
3578// [SECTION] INITIALIZATION, SHUTDOWN
3579//-----------------------------------------------------------------------------
3580
3581// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
3582// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
3583ImGuiContext* ImGui::GetCurrentContext()
3584{
3585 return GImGui;
3586}
3587
3588void ImGui::SetCurrentContext(ImGuiContext* ctx)
3589{
3590#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
3591 IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
3592#else
3593 GImGui = ctx;
3594#endif
3595}
3596
3597void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
3598{
3599 GImAllocatorAllocFunc = alloc_func;
3600 GImAllocatorFreeFunc = free_func;
3601 GImAllocatorUserData = user_data;
3602}
3603
3604// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
3605void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
3606{
3607 *p_alloc_func = GImAllocatorAllocFunc;
3608 *p_free_func = GImAllocatorFreeFunc;
3609 *p_user_data = GImAllocatorUserData;
3610}
3611
3612ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
3613{
3614 ImGuiContext* prev_ctx = GetCurrentContext();
3615 ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
3616 SetCurrentContext(ctx);
3617 Initialize();
3618 if (prev_ctx != NULL)
3619 SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
3620 return ctx;
3621}
3622
3623void ImGui::DestroyContext(ImGuiContext* ctx)
3624{
3625 ImGuiContext* prev_ctx = GetCurrentContext();
3626 if (ctx == NULL) //-V1051
3627 ctx = prev_ctx;
3628 SetCurrentContext(ctx);
3629 Shutdown();
3630 SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
3631 IM_DELETE(ctx);
3632}
3633
3634// IMPORTANT: ###xxx suffixes must be same in ALL languages
3635static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
3636{
3637 { ImGuiLocKey_VersionStr, "Dear ImGui " IMGUI_VERSION " (" IM_STRINGIFY(IMGUI_VERSION_NUM) ")" },
3638 { ImGuiLocKey_TableSizeOne, "Size column to fit###SizeOne" },
3639 { ImGuiLocKey_TableSizeAllFit, "Size all columns to fit###SizeAll" },
3640 { ImGuiLocKey_TableSizeAllDefault, "Size all columns to default###SizeAll" },
3641 { ImGuiLocKey_TableResetOrder, "Reset order###ResetOrder" },
3642 { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)" },
3643 { ImGuiLocKey_WindowingPopup, "(Popup)" },
3644 { ImGuiLocKey_WindowingUntitled, "(Untitled)" },
3645 { ImGuiLocKey_DockingHideTabBar, "Hide tab bar###HideTabBar" },
3646 { ImGuiLocKey_DockingHoldShiftToDock, "Hold SHIFT to enable Docking window." },
3647 { ImGuiLocKey_DockingDragToUndockOrMoveNode,"Click and drag to move or undock whole node." },
3648};
3649
3650void ImGui::Initialize()
3651{
3652 ImGuiContext& g = *GImGui;
3653 IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
3654
3655 // Add .ini handle for ImGuiWindow and ImGuiTable types
3656 {
3657 ImGuiSettingsHandler ini_handler;
3658 ini_handler.TypeName = "Window";
3659 ini_handler.TypeHash = ImHashStr("Window");
3660 ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
3661 ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
3662 ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
3663 ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
3664 ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
3665 AddSettingsHandler(&ini_handler);
3666 }
3667 TableSettingsAddSettingsHandler();
3668
3669 // Setup default localization table
3670 LocalizeRegisterEntries(GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS));
3671
3672 // Setup default platform clipboard/IME handlers.
3673 g.IO.GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
3674 g.IO.SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
3675 g.IO.ClipboardUserData = (void*)&g; // Default implementation use the ImGuiContext as user data (ideally those would be arguments to the function)
3676 g.IO.SetPlatformImeDataFn = SetPlatformImeDataFn_DefaultImpl;
3677
3678 // Create default viewport
3679 ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
3680 viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
3681 viewport->Idx = 0;
3682 viewport->PlatformWindowCreated = true;
3683 viewport->Flags = ImGuiViewportFlags_OwnedByApp;
3684 g.Viewports.push_back(viewport);
3685 g.TempBuffer.resize(1024 * 3 + 1, 0);
3686 g.ViewportCreatedCount++;
3687 g.PlatformIO.Viewports.push_back(g.Viewports[0]);
3688
3689 // Build KeysMayBeCharInput[] lookup table (1 bool per named key)
3690 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
3691 if ((key >= ImGuiKey_0 && key <= ImGuiKey_9) || (key >= ImGuiKey_A && key <= ImGuiKey_Z) || (key >= ImGuiKey_Keypad0 && key <= ImGuiKey_Keypad9)
3692 || key == ImGuiKey_Tab || key == ImGuiKey_Space || key == ImGuiKey_Apostrophe || key == ImGuiKey_Comma || key == ImGuiKey_Minus || key == ImGuiKey_Period
3693 || key == ImGuiKey_Slash || key == ImGuiKey_Semicolon || key == ImGuiKey_Equal || key == ImGuiKey_LeftBracket || key == ImGuiKey_RightBracket || key == ImGuiKey_GraveAccent
3694 || key == ImGuiKey_KeypadDecimal || key == ImGuiKey_KeypadDivide || key == ImGuiKey_KeypadMultiply || key == ImGuiKey_KeypadSubtract || key == ImGuiKey_KeypadAdd || key == ImGuiKey_KeypadEqual)
3695 g.KeysMayBeCharInput.SetBit(key);
3696
3697#ifdef IMGUI_HAS_DOCK
3698 // Initialize Docking
3699 DockContextInitialize(&g);
3700#endif
3701
3702 g.Initialized = true;
3703}
3704
3705// This function is merely here to free heap allocations.
3706void ImGui::Shutdown()
3707{
3708 ImGuiContext& g = *GImGui;
3709 IM_ASSERT_USER_ERROR(g.IO.BackendPlatformUserData == NULL, "Forgot to shutdown Platform backend?");
3710 IM_ASSERT_USER_ERROR(g.IO.BackendRendererUserData == NULL, "Forgot to shutdown Renderer backend?");
3711
3712 // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
3713 if (g.IO.Fonts && g.FontAtlasOwnedByContext)
3714 {
3715 g.IO.Fonts->Locked = false;
3716 IM_DELETE(g.IO.Fonts);
3717 }
3718 g.IO.Fonts = NULL;
3719 g.DrawListSharedData.TempBuffer.clear();
3720
3721 // Cleanup of other data are conditional on actually having initialized Dear ImGui.
3722 if (!g.Initialized)
3723 return;
3724
3725 // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
3726 if (g.SettingsLoaded && g.IO.IniFilename != NULL)
3727 SaveIniSettingsToDisk(g.IO.IniFilename);
3728
3729 // Destroy platform windows
3730 DestroyPlatformWindows();
3731
3732 // Shutdown extensions
3733 DockContextShutdown(&g);
3734
3735 CallContextHooks(&g, ImGuiContextHookType_Shutdown);
3736
3737 // Clear everything else
3738 g.Windows.clear_delete();
3739 g.WindowsFocusOrder.clear();
3740 g.WindowsTempSortBuffer.clear();
3741 g.CurrentWindow = NULL;
3742 g.CurrentWindowStack.clear();
3743 g.WindowsById.Clear();
3744 g.NavWindow = NULL;
3745 g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
3746 g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
3747 g.MovingWindow = NULL;
3748
3749 g.KeysRoutingTable.Clear();
3750
3751 g.ColorStack.clear();
3752 g.StyleVarStack.clear();
3753 g.FontStack.clear();
3754 g.OpenPopupStack.clear();
3755 g.BeginPopupStack.clear();
3756 g.NavTreeNodeStack.clear();
3757
3758 g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
3759 g.Viewports.clear_delete();
3760
3761 g.TabBars.Clear();
3762 g.CurrentTabBarStack.clear();
3763 g.ShrinkWidthBuffer.clear();
3764
3765 g.ClipperTempData.clear_destruct();
3766
3767 g.Tables.Clear();
3768 g.TablesTempData.clear_destruct();
3769 g.DrawChannelsTempMergeBuffer.clear();
3770
3771 g.ClipboardHandlerData.clear();
3772 g.MenusIdSubmittedThisFrame.clear();
3773 g.InputTextState.ClearFreeMemory();
3774 g.InputTextDeactivatedState.ClearFreeMemory();
3775
3776 g.SettingsWindows.clear();
3777 g.SettingsHandlers.clear();
3778
3779 if (g.LogFile)
3780 {
3781#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
3782 if (g.LogFile != stdout)
3783#endif
3784 ImFileClose(g.LogFile);
3785 g.LogFile = NULL;
3786 }
3787 g.LogBuffer.clear();
3788 g.DebugLogBuf.clear();
3789 g.DebugLogIndex.clear();
3790
3791 g.Initialized = false;
3792}
3793
3794// No specific ordering/dependency support, will see as needed
3795ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
3796{
3797 ImGuiContext& g = *ctx;
3798 IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
3799 g.Hooks.push_back(*hook);
3800 g.Hooks.back().HookId = ++g.HookIdNext;
3801 return g.HookIdNext;
3802}
3803
3804// Deferred removal, avoiding issue with changing vector while iterating it
3805void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
3806{
3807 ImGuiContext& g = *ctx;
3808 IM_ASSERT(hook_id != 0);
3809 for (ImGuiContextHook& hook : g.Hooks)
3810 if (hook.HookId == hook_id)
3811 hook.Type = ImGuiContextHookType_PendingRemoval_;
3812}
3813
3814// Call context hooks (used by e.g. test engine)
3815// We assume a small number of hooks so all stored in same array
3816void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
3817{
3818 ImGuiContext& g = *ctx;
3819 for (ImGuiContextHook& hook : g.Hooks)
3820 if (hook.Type == hook_type)
3821 hook.Callback(&g, &hook);
3822}
3823
3824
3825//-----------------------------------------------------------------------------
3826// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
3827//-----------------------------------------------------------------------------
3828
3829// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
3830ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NULL)
3831{
3832 memset(this, 0, sizeof(*this));
3833 Ctx = ctx;
3834 Name = ImStrdup(name);
3835 NameBufLen = (int)strlen(name) + 1;
3836 ID = ImHashStr(name);
3837 IDStack.push_back(ID);
3838 ViewportAllowPlatformMonitorExtend = -1;
3839 ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
3840 MoveId = GetID("#MOVE");
3841 TabId = GetID("#TAB");
3842 ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
3843 ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
3844 AutoFitFramesX = AutoFitFramesY = -1;
3845 AutoPosLastDirection = ImGuiDir_None;
3846 SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = 0;
3847 SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
3848 LastFrameActive = -1;
3849 LastFrameJustFocused = -1;
3850 LastTimeActive = -1.0f;
3851 FontWindowScale = FontDpiScale = 1.0f;
3852 SettingsOffset = -1;
3853 DockOrder = -1;
3854 DrawList = &DrawListInst;
3855 DrawList->_Data = &Ctx->DrawListSharedData;
3856 DrawList->_OwnerName = Name;
3857 NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX);
3858 IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass();
3859}
3860
3861ImGuiWindow::~ImGuiWindow()
3862{
3863 IM_ASSERT(DrawList == &DrawListInst);
3864 IM_DELETE(Name);
3865 ColumnsStorage.clear_destruct();
3866}
3867
3868ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
3869{
3870 ImGuiID seed = IDStack.back();
3871 ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
3872 ImGuiContext& g = *Ctx;
3873 if (g.DebugHookIdInfo == id)
3874 ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
3875 return id;
3876}
3877
3878ImGuiID ImGuiWindow::GetID(const void* ptr)
3879{
3880 ImGuiID seed = IDStack.back();
3881 ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
3882 ImGuiContext& g = *Ctx;
3883 if (g.DebugHookIdInfo == id)
3884 ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
3885 return id;
3886}
3887
3888ImGuiID ImGuiWindow::GetID(int n)
3889{
3890 ImGuiID seed = IDStack.back();
3891 ImGuiID id = ImHashData(&n, sizeof(n), seed);
3892 ImGuiContext& g = *Ctx;
3893 if (g.DebugHookIdInfo == id)
3894 ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
3895 return id;
3896}
3897
3898// This is only used in rare/specific situations to manufacture an ID out of nowhere.
3899ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
3900{
3901 ImGuiID seed = IDStack.back();
3902 ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs);
3903 ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
3904 return id;
3905}
3906
3907static void SetCurrentWindow(ImGuiWindow* window)
3908{
3909 ImGuiContext& g = *GImGui;
3910 g.CurrentWindow = window;
3911 g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
3912 if (window)
3913 {
3914 g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
3915 ImGui::NavUpdateCurrentWindowIsScrollPushableX();
3916 }
3917}
3918
3919void ImGui::GcCompactTransientMiscBuffers()
3920{
3921 ImGuiContext& g = *GImGui;
3922 g.ItemFlagsStack.clear();
3923 g.GroupStack.clear();
3924 TableGcCompactSettings();
3925}
3926
3927// Free up/compact internal window buffers, we can use this when a window becomes unused.
3928// Not freed:
3929// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
3930// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
3931void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
3932{
3933 window->MemoryCompacted = true;
3934 window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
3935 window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
3936 window->IDStack.clear();
3937 window->DrawList->_ClearFreeMemory();
3938 window->DC.ChildWindows.clear();
3939 window->DC.ItemWidthStack.clear();
3940 window->DC.TextWrapPosStack.clear();
3941}
3942
3943void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
3944{
3945 // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
3946 // The other buffers tends to amortize much faster.
3947 window->MemoryCompacted = false;
3948 window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
3949 window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
3950 window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
3951}
3952
3953void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
3954{
3955 ImGuiContext& g = *GImGui;
3956
3957 // Clear previous active id
3958 if (g.ActiveId != 0)
3959 {
3960 // While most behaved code would make an effort to not steal active id during window move/drag operations,
3961 // we at least need to be resilient to it. Canceling the move is rather aggressive and users of 'master' branch
3962 // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
3963 if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
3964 {
3965 IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
3966 g.MovingWindow = NULL;
3967 }
3968
3969 // This could be written in a more general way (e.g associate a hook to ActiveId),
3970 // but since this is currently quite an exception we'll leave it as is.
3971 // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveId()
3972 if (g.InputTextState.ID == g.ActiveId)
3973 InputTextDeactivateHook(g.ActiveId);
3974 }
3975
3976 // Set active id
3977 g.ActiveIdIsJustActivated = (g.ActiveId != id);
3978 if (g.ActiveIdIsJustActivated)
3979 {
3980 IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() old:0x%08X (window \"%s\") -> new:0x%08X (window \"%s\")\n", g.ActiveId, g.ActiveIdWindow ? g.ActiveIdWindow->Name : "", id, window ? window->Name : "");
3981 g.ActiveIdTimer = 0.0f;
3982 g.ActiveIdHasBeenPressedBefore = false;
3983 g.ActiveIdHasBeenEditedBefore = false;
3984 g.ActiveIdMouseButton = -1;
3985 if (id != 0)
3986 {
3987 g.LastActiveId = id;
3988 g.LastActiveIdTimer = 0.0f;
3989 }
3990 }
3991 g.ActiveId = id;
3992 g.ActiveIdAllowOverlap = false;
3993 g.ActiveIdNoClearOnFocusLoss = false;
3994 g.ActiveIdWindow = window;
3995 g.ActiveIdHasBeenEditedThisFrame = false;
3996 g.ActiveIdFromShortcut = false;
3997 if (id)
3998 {
3999 g.ActiveIdIsAlive = id;
4000 g.ActiveIdSource = (g.NavActivateId == id || g.NavJustMovedToId == id) ? g.NavInputSource : ImGuiInputSource_Mouse;
4001 IM_ASSERT(g.ActiveIdSource != ImGuiInputSource_None);
4002 }
4003
4004 // Clear declaration of inputs claimed by the widget
4005 // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
4006 g.ActiveIdUsingNavDirMask = 0x00;
4007 g.ActiveIdUsingAllKeyboardKeys = false;
4008#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4009 g.ActiveIdUsingNavInputMask = 0x00;
4010#endif
4011}
4012
4013void ImGui::ClearActiveID()
4014{
4015 SetActiveID(0, NULL); // g.ActiveId = 0;
4016}
4017
4018void ImGui::SetHoveredID(ImGuiID id)
4019{
4020 ImGuiContext& g = *GImGui;
4021 g.HoveredId = id;
4022 g.HoveredIdAllowOverlap = false;
4023 if (id != 0 && g.HoveredIdPreviousFrame != id)
4024 g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
4025}
4026
4027ImGuiID ImGui::GetHoveredID()
4028{
4029 ImGuiContext& g = *GImGui;
4030 return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
4031}
4032
4033void ImGui::MarkItemEdited(ImGuiID id)
4034{
4035 // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
4036 // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need to fill the data.
4037 ImGuiContext& g = *GImGui;
4038 if (g.LockMarkEdited > 0)
4039 return;
4040 if (g.ActiveId == id || g.ActiveId == 0)
4041 {
4042 g.ActiveIdHasBeenEditedThisFrame = true;
4043 g.ActiveIdHasBeenEditedBefore = true;
4044 }
4045
4046 // We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343)
4047 // We accept 'ActiveIdPreviousFrame == id' for InputText() returning an edit after it has been taken ActiveId away (#4714)
4048 IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.ActiveIdPreviousFrame == id);
4049
4050 //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
4051 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
4052}
4053
4054bool ImGui::IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
4055{
4056 // An active popup disable hovering on other windows (apart from its own children)
4057 // FIXME-OPT: This could be cached/stored within the window.
4058 ImGuiContext& g = *GImGui;
4059 if (g.NavWindow)
4060 if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindowDockTree)
4061 if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree)
4062 {
4063 // For the purpose of those flags we differentiate "standard popup" from "modal popup"
4064 // NB: The 'else' is important because Modal windows are also Popups.
4065 bool want_inhibit = false;
4066 if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
4067 want_inhibit = true;
4068 else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
4069 want_inhibit = true;
4070
4071 // Inhibit hover unless the window is within the stack of our modal/popup
4072 if (want_inhibit)
4073 if (!IsWindowWithinBeginStackOf(window->RootWindow, focused_root_window))
4074 return false;
4075 }
4076
4077 // Filter by viewport
4078 if (window->Viewport != g.MouseViewport)
4079 if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)
4080 return false;
4081
4082 return true;
4083}
4084
4085static inline float CalcDelayFromHoveredFlags(ImGuiHoveredFlags flags)
4086{
4087 ImGuiContext& g = *GImGui;
4088 if (flags & ImGuiHoveredFlags_DelayNormal)
4089 return g.Style.HoverDelayNormal;
4090 if (flags & ImGuiHoveredFlags_DelayShort)
4091 return g.Style.HoverDelayShort;
4092 return 0.0f;
4093}
4094
4095static ImGuiHoveredFlags ApplyHoverFlagsForTooltip(ImGuiHoveredFlags user_flags, ImGuiHoveredFlags shared_flags)
4096{
4097 // Allow instance flags to override shared flags
4098 if (user_flags & (ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal))
4099 shared_flags &= ~(ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal);
4100 return user_flags | shared_flags;
4101}
4102
4103// This is roughly matching the behavior of internal-facing ItemHoverable()
4104// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
4105// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
4106bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
4107{
4108 ImGuiContext& g = *GImGui;
4109 ImGuiWindow* window = g.CurrentWindow;
4110 IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsItemHovered) == 0 && "Invalid flags for IsItemHovered()!");
4111
4112 if (g.NavDisableMouseHover && !g.NavDisableHighlight && !(flags & ImGuiHoveredFlags_NoNavOverride))
4113 {
4114 if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4115 return false;
4116 if (!IsItemFocused())
4117 return false;
4118
4119 if (flags & ImGuiHoveredFlags_ForTooltip)
4120 flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipNav);
4121 }
4122 else
4123 {
4124 // Test for bounding box overlap, as updated as ItemAdd()
4125 ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
4126 if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
4127 return false;
4128
4129 if (flags & ImGuiHoveredFlags_ForTooltip)
4130 flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
4131
4132 IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_DockHierarchy)) == 0); // Flags not supported by this function
4133
4134 // Done with rectangle culling so we can perform heavier checks now
4135 // Test if we are hovering the right window (our window could be behind another window)
4136 // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
4137 // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable
4138 // to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was
4139 // the test that has been running for a long while.
4140 if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
4141 if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByWindow) == 0)
4142 return false;
4143
4144 // Test if another item is active (e.g. being dragged)
4145 const ImGuiID id = g.LastItemData.ID;
4146 if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
4147 if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4148 if (g.ActiveId != window->MoveId && g.ActiveId != window->TabId)
4149 return false;
4150
4151 // Test if interactions on this window are blocked by an active popup or modal.
4152 // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
4153 if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.InFlags & ImGuiItemFlags_NoWindowHoverableCheck))
4154 return false;
4155
4156 // Test if the item is disabled
4157 if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4158 return false;
4159
4160 // Special handling for calling after Begin() which represent the title bar or tab.
4161 // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin)
4162 // will never be overwritten so we need to detect the case.
4163 if (id == window->MoveId && window->WriteAccessed)
4164 return false;
4165
4166 // Test if using AllowOverlap and overlapped
4167 if ((g.LastItemData.InFlags & ImGuiItemFlags_AllowOverlap) && id != 0)
4168 if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByItem) == 0)
4169 if (g.HoveredIdPreviousFrame != g.LastItemData.ID)
4170 return false;
4171 }
4172
4173 // Handle hover delay
4174 // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
4175 const float delay = CalcDelayFromHoveredFlags(flags);
4176 if (delay > 0.0f || (flags & ImGuiHoveredFlags_Stationary))
4177 {
4178 ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromRectangle(g.LastItemData.Rect);
4179 if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverItemDelayIdPreviousFrame != hover_delay_id))
4180 g.HoverItemDelayTimer = 0.0f;
4181 g.HoverItemDelayId = hover_delay_id;
4182
4183 // When changing hovered item we requires a bit of stationary delay before activating hover timer,
4184 // but once unlocked on a given item we also moving.
4185 //if (g.HoverDelayTimer >= delay && (g.HoverDelayTimer - g.IO.DeltaTime < delay || g.MouseStationaryTimer - g.IO.DeltaTime < g.Style.HoverStationaryDelay)) { IMGUI_DEBUG_LOG("HoverDelayTimer = %f/%f, MouseStationaryTimer = %f\n", g.HoverDelayTimer, delay, g.MouseStationaryTimer); }
4186 if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverItemUnlockedStationaryId != hover_delay_id)
4187 return false;
4188
4189 if (g.HoverItemDelayTimer < delay)
4190 return false;
4191 }
4192
4193 return true;
4194}
4195
4196// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
4197// (this does not rely on LastItemData it can be called from a ButtonBehavior() call not following an ItemAdd() call)
4198// FIXME-LEGACY: the 'ImGuiItemFlags item_flags' parameter was added on 2023-06-28.
4199// If you used this in your legacy/custom widgets code:
4200// - Commonly: if your ItemHoverable() call comes after an ItemAdd() call: pass 'item_flags = g.LastItemData.InFlags'.
4201// - Rare: otherwise you may pass 'item_flags = 0' (ImGuiItemFlags_None) unless you want to benefit from special behavior handled by ItemHoverable.
4202bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flags)
4203{
4204 ImGuiContext& g = *GImGui;
4205 ImGuiWindow* window = g.CurrentWindow;
4206 if (g.HoveredWindow != window)
4207 return false;
4208 if (!IsMouseHoveringRect(bb.Min, bb.Max))
4209 return false;
4210
4211 if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
4212 return false;
4213 if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4214 if (!g.ActiveIdFromShortcut)
4215 return false;
4216
4217 // Done with rectangle culling so we can perform heavier checks now.
4218 if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
4219 {
4220 g.HoveredIdDisabled = true;
4221 return false;
4222 }
4223
4224 // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
4225 // hover test in widgets code. We could also decide to split this function is two.
4226 if (id != 0)
4227 {
4228 // Drag source doesn't report as hovered
4229 if (g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover))
4230 return false;
4231
4232 SetHoveredID(id);
4233
4234 // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match.
4235 // This allows using patterns where a later submitted widget overlaps a previous one. Generally perceived as a front-to-back hit-test.
4236 if (item_flags & ImGuiItemFlags_AllowOverlap)
4237 {
4238 g.HoveredIdAllowOverlap = true;
4239 if (g.HoveredIdPreviousFrame != id)
4240 return false;
4241 }
4242 }
4243
4244 // When disabled we'll return false but still set HoveredId
4245 if (item_flags & ImGuiItemFlags_Disabled)
4246 {
4247 // Release active id if turning disabled
4248 if (g.ActiveId == id && id != 0)
4249 ClearActiveID();
4250 g.HoveredIdDisabled = true;
4251 return false;
4252 }
4253
4254#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4255 if (id != 0)
4256 {
4257 // [DEBUG] Item Picker tool!
4258 // We perform the check here because reaching is path is rare (1~ time a frame),
4259 // making the cost of this tool near-zero! We could get better call-stack and support picking non-hovered
4260 // items if we performed the test in ItemAdd(), but that would incur a bigger runtime cost.
4261 if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
4262 GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
4263 if (g.DebugItemPickerBreakId == id)
4264 IM_DEBUG_BREAK();
4265 }
4266#endif
4267
4268 if (g.NavDisableMouseHover)
4269 return false;
4270
4271 return true;
4272}
4273
4274// FIXME: This is inlined/duplicated in ItemAdd()
4275// FIXME: The id != 0 path is not used by our codebase, may get rid of it?
4276bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
4277{
4278 ImGuiContext& g = *GImGui;
4279 ImGuiWindow* window = g.CurrentWindow;
4280 if (!bb.Overlaps(window->ClipRect))
4281 if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
4282 if (!g.LogEnabled)
4283 return true;
4284 return false;
4285}
4286
4287// This is also inlined in ItemAdd()
4288// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect.
4289void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
4290{
4291 ImGuiContext& g = *GImGui;
4292 g.LastItemData.ID = item_id;
4293 g.LastItemData.InFlags = in_flags;
4294 g.LastItemData.StatusFlags = item_flags;
4295 g.LastItemData.Rect = g.LastItemData.NavRect = item_rect;
4296}
4297
4298float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
4299{
4300 if (wrap_pos_x < 0.0f)
4301 return 0.0f;
4302
4303 ImGuiContext& g = *GImGui;
4304 ImGuiWindow* window = g.CurrentWindow;
4305 if (wrap_pos_x == 0.0f)
4306 {
4307 // We could decide to setup a default wrapping max point for auto-resizing windows,
4308 // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
4309 //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
4310 // wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
4311 //else
4312 wrap_pos_x = window->WorkRect.Max.x;
4313 }
4314 else if (wrap_pos_x > 0.0f)
4315 {
4316 wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
4317 }
4318
4319 return ImMax(wrap_pos_x - pos.x, 1.0f);
4320}
4321
4322// IM_ALLOC() == ImGui::MemAlloc()
4323void* ImGui::MemAlloc(size_t size)
4324{
4325 void* ptr = (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
4326#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4327 if (ImGuiContext* ctx = GImGui)
4328 DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, size);
4329#endif
4330 return ptr;
4331}
4332
4333// IM_FREE() == ImGui::MemFree()
4334void ImGui::MemFree(void* ptr)
4335{
4336#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4337 if (ptr != NULL)
4338 if (ImGuiContext* ctx = GImGui)
4339 DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, (size_t)-1);
4340#endif
4341 return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
4342}
4343
4344// We record the number of allocation in recent frames, as a way to audit/sanitize our guiding principles of "no allocations on idle/repeating frames"
4345void ImGui::DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size)
4346{
4347 ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4348 IM_UNUSED(ptr);
4349 if (entry->FrameCount != frame_count)
4350 {
4351 info->LastEntriesIdx = (info->LastEntriesIdx + 1) % IM_ARRAYSIZE(info->LastEntriesBuf);
4352 entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4353 entry->FrameCount = frame_count;
4354 entry->AllocCount = entry->FreeCount = 0;
4355 }
4356 if (size != (size_t)-1)
4357 {
4358 entry->AllocCount++;
4359 info->TotalAllocCount++;
4360 //printf("[%05d] MemAlloc(%d) -> 0x%p\n", frame_count, size, ptr);
4361 }
4362 else
4363 {
4364 entry->FreeCount++;
4365 info->TotalFreeCount++;
4366 //printf("[%05d] MemFree(0x%p)\n", frame_count, ptr);
4367 }
4368}
4369
4370const char* ImGui::GetClipboardText()
4371{
4372 ImGuiContext& g = *GImGui;
4373 return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
4374}
4375
4376void ImGui::SetClipboardText(const char* text)
4377{
4378 ImGuiContext& g = *GImGui;
4379 if (g.IO.SetClipboardTextFn)
4380 g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
4381}
4382
4383const char* ImGui::GetVersion()
4384{
4385 return IMGUI_VERSION;
4386}
4387
4388ImGuiIO& ImGui::GetIO()
4389{
4390 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4391 return GImGui->IO;
4392}
4393
4394ImGuiPlatformIO& ImGui::GetPlatformIO()
4395{
4396 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
4397 return GImGui->PlatformIO;
4398}
4399
4400// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
4401ImDrawData* ImGui::GetDrawData()
4402{
4403 ImGuiContext& g = *GImGui;
4404 ImGuiViewportP* viewport = g.Viewports[0];
4405 return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
4406}
4407
4408double ImGui::GetTime()
4409{
4410 return GImGui->Time;
4411}
4412
4413int ImGui::GetFrameCount()
4414{
4415 return GImGui->FrameCount;
4416}
4417
4418static ImDrawList* GetViewportBgFgDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
4419{
4420 // Create the draw list on demand, because they are not frequently used for all viewports
4421 ImGuiContext& g = *GImGui;
4422 IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->BgFgDrawLists));
4423 ImDrawList* draw_list = viewport->BgFgDrawLists[drawlist_no];
4424 if (draw_list == NULL)
4425 {
4426 draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
4427 draw_list->_OwnerName = drawlist_name;
4428 viewport->BgFgDrawLists[drawlist_no] = draw_list;
4429 }
4430
4431 // Our ImDrawList system requires that there is always a command
4432 if (viewport->BgFgDrawListsLastFrame[drawlist_no] != g.FrameCount)
4433 {
4434 draw_list->_ResetForNewFrame();
4435 draw_list->PushTextureID(g.IO.Fonts->TexID);
4436 draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
4437 viewport->BgFgDrawListsLastFrame[drawlist_no] = g.FrameCount;
4438 }
4439 return draw_list;
4440}
4441
4442ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
4443{
4444 return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 0, "##Background");
4445}
4446
4447ImDrawList* ImGui::GetBackgroundDrawList()
4448{
4449 ImGuiContext& g = *GImGui;
4450 return GetBackgroundDrawList(g.CurrentWindow->Viewport);
4451}
4452
4453ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
4454{
4455 return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
4456}
4457
4458ImDrawList* ImGui::GetForegroundDrawList()
4459{
4460 ImGuiContext& g = *GImGui;
4461 return GetForegroundDrawList(g.CurrentWindow->Viewport);
4462}
4463
4464ImDrawListSharedData* ImGui::GetDrawListSharedData()
4465{
4466 return &GImGui->DrawListSharedData;
4467}
4468
4469void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
4470{
4471 // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
4472 // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
4473 // This is because we want ActiveId to be set even when the window is not permitted to move.
4474 ImGuiContext& g = *GImGui;
4475 FocusWindow(window);
4476 SetActiveID(window->MoveId, window);
4477 g.NavDisableHighlight = true;
4478 g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos;
4479 g.ActiveIdNoClearOnFocusLoss = true;
4480 SetActiveIdUsingAllKeyboardKeys();
4481
4482 bool can_move_window = true;
4483 if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove))
4484 can_move_window = false;
4485 if (ImGuiDockNode* node = window->DockNodeAsHost)
4486 if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
4487 can_move_window = false;
4488 if (can_move_window)
4489 g.MovingWindow = window;
4490}
4491
4492// We use 'undock == false' when dragging from title bar to allow moving groups of floating nodes without undocking them.
4493void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock)
4494{
4495 ImGuiContext& g = *GImGui;
4496 bool can_undock_node = false;
4497 if (undock && node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0 && (node->MergedFlags & ImGuiDockNodeFlags_NoUndocking) == 0)
4498 {
4499 // Can undock if:
4500 // - part of a hierarchy with more than one visible node (if only one is visible, we'll just move the root window)
4501 // - part of a dockspace node hierarchy: so we can undock the last single visible node too (trivia: undocking from a fixed/central node will create a new node and copy windows)
4502 ImGuiDockNode* root_node = DockNodeGetRootNode(node);
4503 if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL) // -V1051 PVS-Studio thinks node should be root_node and is wrong about that.
4504 can_undock_node = true;
4505 }
4506
4507 const bool clicked = IsMouseClicked(0);
4508 const bool dragging = IsMouseDragging(0);
4509 if (can_undock_node && dragging)
4510 DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame
4511 else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window)
4512 StartMouseMovingWindow(window);
4513}
4514
4515// Handle mouse moving window
4516// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
4517// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
4518// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
4519// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
4520void ImGui::UpdateMouseMovingWindowNewFrame()
4521{
4522 ImGuiContext& g = *GImGui;
4523 if (g.MovingWindow != NULL)
4524 {
4525 // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
4526 // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
4527 KeepAliveID(g.ActiveId);
4528 IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree);
4529 ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree;
4530
4531 // When a window stop being submitted while being dragged, it may will its viewport until next Begin()
4532 const bool window_disappared = (!moving_window->WasActive && !moving_window->Active);
4533 if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos) && !window_disappared)
4534 {
4535 ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
4536 if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
4537 {
4538 SetWindowPos(moving_window, pos, ImGuiCond_Always);
4539 if (moving_window->Viewport && moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
4540 {
4541 moving_window->Viewport->Pos = pos;
4542 moving_window->Viewport->UpdateWorkRect();
4543 }
4544 }
4545 FocusWindow(g.MovingWindow);
4546 }
4547 else
4548 {
4549 if (!window_disappared)
4550 {
4551 // Try to merge the window back into the main viewport.
4552 // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
4553 if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
4554 UpdateTryMergeWindowIntoHostViewport(moving_window, g.MouseViewport);
4555
4556 // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
4557 if (moving_window->Viewport && !IsDragDropPayloadBeingAccepted())
4558 g.MouseViewport = moving_window->Viewport;
4559
4560 // Clear the NoInput window flag set by the Viewport system
4561 if (moving_window->Viewport)
4562 moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs;
4563 }
4564
4565 g.MovingWindow = NULL;
4566 ClearActiveID();
4567 }
4568 }
4569 else
4570 {
4571 // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
4572 if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
4573 {
4574 KeepAliveID(g.ActiveId);
4575 if (!g.IO.MouseDown[0])
4576 ClearActiveID();
4577 }
4578 }
4579}
4580
4581// Initiate moving window when clicking on empty space or title bar.
4582// Handle left-click and right-click focus.
4583void ImGui::UpdateMouseMovingWindowEndFrame()
4584{
4585 ImGuiContext& g = *GImGui;
4586 if (g.ActiveId != 0 || g.HoveredId != 0)
4587 return;
4588
4589 // Unless we just made a window/popup appear
4590 if (g.NavWindow && g.NavWindow->Appearing)
4591 return;
4592
4593 // Click on empty space to focus window and start moving
4594 // (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!)
4595 if (g.IO.MouseClicked[0])
4596 {
4597 // Handle the edge case of a popup being closed while clicking in its empty space.
4598 // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
4599 ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
4600 const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
4601
4602 if (root_window != NULL && !is_closed_popup)
4603 {
4604 StartMouseMovingWindow(g.HoveredWindow); //-V595
4605
4606 // Cancel moving if clicked outside of title bar
4607 if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
4608 if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
4609 if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
4610 g.MovingWindow = NULL;
4611
4612 // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
4613 if (g.HoveredIdDisabled)
4614 g.MovingWindow = NULL;
4615 }
4616 else if (root_window == NULL && g.NavWindow != NULL)
4617 {
4618 // Clicking on void disable focus
4619 FocusWindow(NULL, ImGuiFocusRequestFlags_UnlessBelowModal);
4620 }
4621 }
4622
4623 // With right mouse button we close popups without changing focus based on where the mouse is aimed
4624 // Instead, focus will be restored to the window under the bottom-most closed popup.
4625 // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
4626 if (g.IO.MouseClicked[1])
4627 {
4628 // Find the top-most window between HoveredWindow and the top-most Modal Window.
4629 // This is where we can trim the popup stack.
4630 ImGuiWindow* modal = GetTopMostPopupModal();
4631 bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(g.HoveredWindow, modal));
4632 ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
4633 }
4634}
4635
4636// This is called during NewFrame()->UpdateViewportsNewFrame() only.
4637// Need to keep in sync with SetWindowPos()
4638static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
4639{
4640 window->Pos += delta;
4641 window->ClipRect.Translate(delta);
4642 window->OuterRectClipped.Translate(delta);
4643 window->InnerRect.Translate(delta);
4644 window->DC.CursorPos += delta;
4645 window->DC.CursorStartPos += delta;
4646 window->DC.CursorMaxPos += delta;
4647 window->DC.IdealMaxPos += delta;
4648}
4649
4650static void ScaleWindow(ImGuiWindow* window, float scale)
4651{
4652 ImVec2 origin = window->Viewport->Pos;
4653 window->Pos = ImFloor((window->Pos - origin) * scale + origin);
4654 window->Size = ImTrunc(window->Size * scale);
4655 window->SizeFull = ImTrunc(window->SizeFull * scale);
4656 window->ContentSize = ImTrunc(window->ContentSize * scale);
4657}
4658
4659static bool IsWindowActiveAndVisible(ImGuiWindow* window)
4660{
4661 return (window->Active) && (!window->Hidden);
4662}
4663
4664// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
4665void ImGui::UpdateHoveredWindowAndCaptureFlags()
4666{
4667 ImGuiContext& g = *GImGui;
4668 ImGuiIO& io = g.IO;
4669 g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
4670
4671 // Find the window hovered by mouse:
4672 // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
4673 // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
4674 // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
4675 bool clear_hovered_windows = false;
4676 FindHoveredWindow();
4677 IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
4678
4679 // Modal windows prevents mouse from hovering behind them.
4680 ImGuiWindow* modal_window = GetTopMostPopupModal();
4681 if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window)) // FIXME-MERGE: RootWindowDockTree ?
4682 clear_hovered_windows = true;
4683
4684 // Disabled mouse?
4685 if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
4686 clear_hovered_windows = true;
4687
4688 // We track click ownership. When clicked outside of a window the click is owned by the application and
4689 // won't report hovering nor request capture even while dragging over our windows afterward.
4690 const bool has_open_popup = (g.OpenPopupStack.Size > 0);
4691 const bool has_open_modal = (modal_window != NULL);
4692 int mouse_earliest_down = -1;
4693 bool mouse_any_down = false;
4694 for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
4695 {
4696 if (io.MouseClicked[i])
4697 {
4698 io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
4699 io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
4700 }
4701 mouse_any_down |= io.MouseDown[i];
4702 if (io.MouseDown[i])
4703 if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
4704 mouse_earliest_down = i;
4705 }
4706 const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
4707 const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
4708
4709 // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
4710 // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
4711 const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
4712 if (!mouse_avail && !mouse_dragging_extern_payload)
4713 clear_hovered_windows = true;
4714
4715 if (clear_hovered_windows)
4716 g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4717
4718 // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
4719 // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
4720 if (g.WantCaptureMouseNextFrame != -1)
4721 {
4722 io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
4723 }
4724 else
4725 {
4726 io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
4727 io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
4728 }
4729
4730 // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
4731 io.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
4732 if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
4733 io.WantCaptureKeyboard = true;
4734 if (g.WantCaptureKeyboardNextFrame != -1) // Manual override
4735 io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
4736
4737 // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
4738 io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
4739}
4740
4741void ImGui::NewFrame()
4742{
4743 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4744 ImGuiContext& g = *GImGui;
4745
4746 // Remove pending delete hooks before frame start.
4747 // This deferred removal avoid issues of removal while iterating the hook vector
4748 for (int n = g.Hooks.Size - 1; n >= 0; n--)
4749 if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
4750 g.Hooks.erase(&g.Hooks[n]);
4751
4752 CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
4753
4754 // Check and assert for various common IO and Configuration mistakes
4755 g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame;
4756 ErrorCheckNewFrameSanityChecks();
4757 g.ConfigFlagsCurrFrame = g.IO.ConfigFlags;
4758
4759 // Load settings on first frame, save settings when modified (after a delay)
4760 UpdateSettings();
4761
4762 g.Time += g.IO.DeltaTime;
4763 g.WithinFrameScope = true;
4764 g.FrameCount += 1;
4765 g.TooltipOverrideCount = 0;
4766 g.WindowsActiveCount = 0;
4767 g.MenusIdSubmittedThisFrame.resize(0);
4768
4769 // Calculate frame-rate for the user, as a purely luxurious feature
4770 g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
4771 g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
4772 g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
4773 g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
4774 g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
4775
4776 // Process input queue (trickle as many events as possible), turn events into writes to IO structure
4777 g.InputEventsTrail.resize(0);
4778 UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue);
4779
4780 // Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
4781 UpdateViewportsNewFrame();
4782
4783 // Setup current font and draw list shared data
4784 // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
4785 g.IO.Fonts->Locked = true;
4786 SetCurrentFont(GetDefaultFont());
4787 IM_ASSERT(g.Font->IsLoaded());
4788 ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
4789 for (ImGuiViewportP* viewport : g.Viewports)
4790 virtual_space.Add(viewport->GetMainRect());
4791 g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
4792 g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
4793 g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
4794 g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
4795 if (g.Style.AntiAliasedLines)
4796 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
4797 if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines))
4798 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
4799 if (g.Style.AntiAliasedFill)
4800 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
4801 if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
4802 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
4803
4804 // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
4805 for (ImGuiViewportP* viewport : g.Viewports)
4806 {
4807 viewport->DrawData = NULL;
4808 viewport->DrawDataP.Valid = false;
4809 }
4810
4811 // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
4812 if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
4813 KeepAliveID(g.DragDropPayload.SourceId);
4814
4815 // Update HoveredId data
4816 if (!g.HoveredIdPreviousFrame)
4817 g.HoveredIdTimer = 0.0f;
4818 if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
4819 g.HoveredIdNotActiveTimer = 0.0f;
4820 if (g.HoveredId)
4821 g.HoveredIdTimer += g.IO.DeltaTime;
4822 if (g.HoveredId && g.ActiveId != g.HoveredId)
4823 g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
4824 g.HoveredIdPreviousFrame = g.HoveredId;
4825 g.HoveredId = 0;
4826 g.HoveredIdAllowOverlap = false;
4827 g.HoveredIdDisabled = false;
4828
4829 // Clear ActiveID if the item is not alive anymore.
4830 // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
4831 // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
4832 if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
4833 {
4834 IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n");
4835 ClearActiveID();
4836 }
4837
4838 // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
4839 if (g.ActiveId)
4840 g.ActiveIdTimer += g.IO.DeltaTime;
4841 g.LastActiveIdTimer += g.IO.DeltaTime;
4842 g.ActiveIdPreviousFrame = g.ActiveId;
4843 g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
4844 g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
4845 g.ActiveIdIsAlive = 0;
4846 g.ActiveIdHasBeenEditedThisFrame = false;
4847 g.ActiveIdPreviousFrameIsAlive = false;
4848 g.ActiveIdIsJustActivated = false;
4849 if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
4850 g.TempInputId = 0;
4851 if (g.ActiveId == 0)
4852 {
4853 g.ActiveIdUsingNavDirMask = 0x00;
4854 g.ActiveIdUsingAllKeyboardKeys = false;
4855#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4856 g.ActiveIdUsingNavInputMask = 0x00;
4857#endif
4858 }
4859
4860#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4861 if (g.ActiveId == 0)
4862 g.ActiveIdUsingNavInputMask = 0;
4863 else if (g.ActiveIdUsingNavInputMask != 0)
4864 {
4865 // If your custom widget code used: { g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel); }
4866 // Since IMGUI_VERSION_NUM >= 18804 it should be: { SetKeyOwner(ImGuiKey_Escape, g.ActiveId); SetKeyOwner(ImGuiKey_NavGamepadCancel, g.ActiveId); }
4867 if (g.ActiveIdUsingNavInputMask & (1 << ImGuiNavInput_Cancel))
4868 SetKeyOwner(ImGuiKey_Escape, g.ActiveId);
4869 if (g.ActiveIdUsingNavInputMask & ~(1 << ImGuiNavInput_Cancel))
4870 IM_ASSERT(0); // Other values unsupported
4871 }
4872#endif
4873
4874 // Record when we have been stationary as this state is preserved while over same item.
4875 // FIXME: The way this is expressed means user cannot alter HoverStationaryDelay during the frame to use varying values.
4876 // To allow this we should store HoverItemMaxStationaryTime+ID and perform the >= check in IsItemHovered() function.
4877 if (g.HoverItemDelayId != 0 && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
4878 g.HoverItemUnlockedStationaryId = g.HoverItemDelayId;
4879 else if (g.HoverItemDelayId == 0)
4880 g.HoverItemUnlockedStationaryId = 0;
4881 if (g.HoveredWindow != NULL && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
4882 g.HoverWindowUnlockedStationaryId = g.HoveredWindow->ID;
4883 else if (g.HoveredWindow == NULL)
4884 g.HoverWindowUnlockedStationaryId = 0;
4885
4886 // Update hover delay for IsItemHovered() with delays and tooltips
4887 g.HoverItemDelayIdPreviousFrame = g.HoverItemDelayId;
4888 if (g.HoverItemDelayId != 0)
4889 {
4890 g.HoverItemDelayTimer += g.IO.DeltaTime;
4891 g.HoverItemDelayClearTimer = 0.0f;
4892 g.HoverItemDelayId = 0;
4893 }
4894 else if (g.HoverItemDelayTimer > 0.0f)
4895 {
4896 // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
4897 // We could expose 0.25f as style.HoverClearDelay but I am not sure of the logic yet, this is particularly subtle.
4898 g.HoverItemDelayClearTimer += g.IO.DeltaTime;
4899 if (g.HoverItemDelayClearTimer >= ImMax(0.25f, g.IO.DeltaTime * 2.0f)) // ~7 frames at 30 Hz + allow for low framerate
4900 g.HoverItemDelayTimer = g.HoverItemDelayClearTimer = 0.0f; // May want a decaying timer, in which case need to clamp at max first, based on max of caller last requested timer.
4901 }
4902
4903 // Drag and drop
4904 g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
4905 g.DragDropAcceptIdCurr = 0;
4906 g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
4907 g.DragDropWithinSource = false;
4908 g.DragDropWithinTarget = false;
4909 g.DragDropHoldJustPressedId = 0;
4910
4911 // Close popups on focus lost (currently wip/opt-in)
4912 //if (g.IO.AppFocusLost)
4913 // ClosePopupsExceptModals();
4914
4915 // Update keyboard input state
4916 UpdateKeyboardInputs();
4917
4918 //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
4919 //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
4920 //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
4921 //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
4922
4923 // Update gamepad/keyboard navigation
4924 NavUpdate();
4925
4926 // Update mouse input state
4927 UpdateMouseInputs();
4928
4929 // Undocking
4930 // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
4931 DockContextNewFrameUpdateUndocking(&g);
4932
4933 // Find hovered window
4934 // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
4935 UpdateHoveredWindowAndCaptureFlags();
4936
4937 // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
4938 UpdateMouseMovingWindowNewFrame();
4939
4940 // Background darkening/whitening
4941 if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
4942 g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
4943 else
4944 g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
4945
4946 g.MouseCursor = ImGuiMouseCursor_Arrow;
4947 g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
4948
4949 // Platform IME data: reset for the frame
4950 g.PlatformImeDataPrev = g.PlatformImeData;
4951 g.PlatformImeData.WantVisible = false;
4952
4953 // Mouse wheel scrolling, scale
4954 UpdateMouseWheel();
4955
4956 // Mark all windows as not visible and compact unused memory.
4957 IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
4958 const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
4959 for (ImGuiWindow* window : g.Windows)
4960 {
4961 window->WasActive = window->Active;
4962 window->Active = false;
4963 window->WriteAccessed = false;
4964 window->BeginCountPreviousFrame = window->BeginCount;
4965 window->BeginCount = 0;
4966
4967 // Garbage collect transient buffers of recently unused windows
4968 if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
4969 GcCompactTransientWindowBuffers(window);
4970 }
4971
4972 // Garbage collect transient buffers of recently unused tables
4973 for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
4974 if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
4975 TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
4976 for (ImGuiTableTempData& table_temp_data : g.TablesTempData)
4977 if (table_temp_data.LastTimeActive >= 0.0f && table_temp_data.LastTimeActive < memory_compact_start_time)
4978 TableGcCompactTransientBuffers(&table_temp_data);
4979 if (g.GcCompactAll)
4980 GcCompactTransientMiscBuffers();
4981 g.GcCompactAll = false;
4982
4983 // Closing the focused window restore focus to the first active root window in descending z-order
4984 if (g.NavWindow && !g.NavWindow->WasActive)
4985 FocusTopMostWindowUnderOne(NULL, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild);
4986
4987 // No window should be open at the beginning of the frame.
4988 // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
4989 g.CurrentWindowStack.resize(0);
4990 g.BeginPopupStack.resize(0);
4991 g.ItemFlagsStack.resize(0);
4992 g.ItemFlagsStack.push_back(ImGuiItemFlags_None);
4993 g.GroupStack.resize(0);
4994
4995 // Docking
4996 DockContextNewFrameUpdateDocking(&g);
4997
4998 // [DEBUG] Update debug features
4999#ifndef IMGUI_DISABLE_DEBUG_TOOLS
5000 UpdateDebugToolItemPicker();
5001 UpdateDebugToolStackQueries();
5002 UpdateDebugToolFlashStyleColor();
5003 if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0)
5004 {
5005 g.DebugLocateId = 0;
5006 g.DebugBreakInLocateId = false;
5007 }
5008 if (g.DebugLogAutoDisableFrames > 0 && --g.DebugLogAutoDisableFrames == 0)
5009 {
5010 DebugLog("(Debug Log: Auto-disabled some ImGuiDebugLogFlags after 2 frames)\n");
5011 g.DebugLogFlags &= ~g.DebugLogAutoDisableFlags;
5012 g.DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None;
5013 }
5014#endif
5015
5016 // Create implicit/fallback window - which we will only render it if the user has added something to it.
5017 // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
5018 // This fallback is particularly important as it prevents ImGui:: calls from crashing.
5019 g.WithinFrameScopeWithImplicitWindow = true;
5020 SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
5021 Begin("Debug##Default");
5022 IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
5023
5024 // [DEBUG] When io.ConfigDebugBeginReturnValue is set, we make Begin()/BeginChild() return false at different level of the window-stack,
5025 // allowing to validate correct Begin/End behavior in user code.
5026#ifndef IMGUI_DISABLE_DEBUG_TOOLS
5027 if (g.IO.ConfigDebugBeginReturnValueLoop)
5028 g.DebugBeginReturnValueCullDepth = (g.DebugBeginReturnValueCullDepth == -1) ? 0 : ((g.DebugBeginReturnValueCullDepth + ((g.FrameCount % 4) == 0 ? 1 : 0)) % 10);
5029 else
5030 g.DebugBeginReturnValueCullDepth = -1;
5031#endif
5032
5033 CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
5034}
5035
5036// FIXME: Add a more explicit sort order in the window structure.
5037static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
5038{
5039 const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
5040 const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
5041 if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
5042 return d;
5043 if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
5044 return d;
5045 return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
5046}
5047
5048static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
5049{
5050 out_sorted_windows->push_back(window);
5051 if (window->Active)
5052 {
5053 int count = window->DC.ChildWindows.Size;
5054 ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
5055 for (int i = 0; i < count; i++)
5056 {
5057 ImGuiWindow* child = window->DC.ChildWindows[i];
5058 if (child->Active)
5059 AddWindowToSortBuffer(out_sorted_windows, child);
5060 }
5061 }
5062}
5063
5064static void AddWindowToDrawData(ImGuiWindow* window, int layer)
5065{
5066 ImGuiContext& g = *GImGui;
5067 ImGuiViewportP* viewport = window->Viewport;
5068 IM_ASSERT(viewport != NULL);
5069 g.IO.MetricsRenderWindows++;
5070 if (window->DrawList->_Splitter._Count > 1)
5071 window->DrawList->ChannelsMerge(); // Merge if user forgot to merge back. Also required in Docking branch for ImGuiWindowFlags_DockNodeHost windows.
5072 ImGui::AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[layer], window->DrawList);
5073 for (ImGuiWindow* child : window->DC.ChildWindows)
5074 if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
5075 AddWindowToDrawData(child, layer);
5076}
5077
5078static inline int GetWindowDisplayLayer(ImGuiWindow* window)
5079{
5080 return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
5081}
5082
5083// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
5084static inline void AddRootWindowToDrawData(ImGuiWindow* window)
5085{
5086 AddWindowToDrawData(window, GetWindowDisplayLayer(window));
5087}
5088
5089static void FlattenDrawDataIntoSingleLayer(ImDrawDataBuilder* builder)
5090{
5091 int n = builder->Layers[0]->Size;
5092 int full_size = n;
5093 for (int i = 1; i < IM_ARRAYSIZE(builder->Layers); i++)
5094 full_size += builder->Layers[i]->Size;
5095 builder->Layers[0]->resize(full_size);
5096 for (int layer_n = 1; layer_n < IM_ARRAYSIZE(builder->Layers); layer_n++)
5097 {
5098 ImVector<ImDrawList*>* layer = builder->Layers[layer_n];
5099 if (layer->empty())
5100 continue;
5101 memcpy(builder->Layers[0]->Data + n, layer->Data, layer->Size * sizeof(ImDrawList*));
5102 n += layer->Size;
5103 layer->resize(0);
5104 }
5105}
5106
5107static void InitViewportDrawData(ImGuiViewportP* viewport)
5108{
5109 ImGuiIO& io = ImGui::GetIO();
5110 ImDrawData* draw_data = &viewport->DrawDataP;
5111
5112 viewport->DrawData = draw_data; // Make publicly accessible
5113 viewport->DrawDataBuilder.Layers[0] = &draw_data->CmdLists;
5114 viewport->DrawDataBuilder.Layers[1] = &viewport->DrawDataBuilder.LayerData1;
5115 viewport->DrawDataBuilder.Layers[0]->resize(0);
5116 viewport->DrawDataBuilder.Layers[1]->resize(0);
5117
5118 // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode,
5119 // and to allow applications/backends to easily skip rendering.
5120 // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure.
5121 // This is because the work has been done already, and its wasted! We should fix that and add optimizations for
5122 // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline.
5123 const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0;
5124
5125 draw_data->Valid = true;
5126 draw_data->CmdListsCount = 0;
5127 draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
5128 draw_data->DisplayPos = viewport->Pos;
5129 draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size;
5130 draw_data->FramebufferScale = io.DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis?
5131 draw_data->OwnerViewport = viewport;
5132}
5133
5134// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
5135// - When using this function it is sane to ensure that float are perfectly rounded to integer values,
5136// so that e.g. (int)(max.x-min.x) in user's render produce correct result.
5137// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
5138// some frequently called functions which to modify both channels and clipping simultaneously tend to use the
5139// more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
5140void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
5141{
5142 ImGuiWindow* window = GetCurrentWindow();
5143 window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
5144 window->ClipRect = window->DrawList->_ClipRectStack.back();
5145}
5146
5147void ImGui::PopClipRect()
5148{
5149 ImGuiWindow* window = GetCurrentWindow();
5150 window->DrawList->PopClipRect();
5151 window->ClipRect = window->DrawList->_ClipRectStack.back();
5152}
5153
5154static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
5155{
5156 for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
5157 if (IsWindowActiveAndVisible(window->DC.ChildWindows[n]))
5158 return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]);
5159 return window;
5160}
5161
5162static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
5163{
5164 if ((col & IM_COL32_A_MASK) == 0)
5165 return;
5166
5167 ImGuiViewportP* viewport = window->Viewport;
5168 ImRect viewport_rect = viewport->GetMainRect();
5169
5170 // Draw behind window by moving the draw command at the FRONT of the draw list
5171 {
5172 // Draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
5173 // FIXME: This is creating complication, might be simpler if we could inject a drawlist in drawdata at a given position and not attempt to manipulate ImDrawCmd order.
5174 ImDrawList* draw_list = window->RootWindowDockTree->DrawList;
5175 draw_list->ChannelsMerge();
5176 if (draw_list->CmdBuffer.Size == 0)
5177 draw_list->AddDrawCmd();
5178 draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // FIXME: Need to stricty ensure ImDrawCmd are not merged (ElemCount==6 checks below will verify that)
5179 draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col);
5180 ImDrawCmd cmd = draw_list->CmdBuffer.back();
5181 IM_ASSERT(cmd.ElemCount == 6);
5182 draw_list->CmdBuffer.pop_back();
5183 draw_list->CmdBuffer.push_front(cmd);
5184 draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
5185 draw_list->PopClipRect();
5186 }
5187
5188 // Draw over sibling docking nodes in a same docking tree
5189 if (window->RootWindow->DockIsActive)
5190 {
5191 ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindowDockTree)->DrawList;
5192 draw_list->ChannelsMerge();
5193 if (draw_list->CmdBuffer.Size == 0)
5194 draw_list->AddDrawCmd();
5195 draw_list->PushClipRect(viewport_rect.Min, viewport_rect.Max, false);
5196 RenderRectFilledWithHole(draw_list, window->RootWindowDockTree->Rect(), window->RootWindow->Rect(), col, 0.0f);// window->RootWindowDockTree->WindowRounding);
5197 draw_list->PopClipRect();
5198 }
5199}
5200
5201ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
5202{
5203 ImGuiContext& g = *GImGui;
5204 ImGuiWindow* bottom_most_visible_window = parent_window;
5205 for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--)
5206 {
5207 ImGuiWindow* window = g.Windows[i];
5208 if (window->Flags & ImGuiWindowFlags_ChildWindow)
5209 continue;
5210 if (!IsWindowWithinBeginStackOf(window, parent_window))
5211 break;
5212 if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window))
5213 bottom_most_visible_window = window;
5214 }
5215 return bottom_most_visible_window;
5216}
5217
5218// Important: AddWindowToDrawData() has not been called yet, meaning DockNodeHost windows needs a DrawList->ChannelsMerge() before usage.
5219// We call ChannelsMerge() lazily here at it is faster that doing a full iteration of g.Windows[] prior to calling RenderDimmedBackgrounds().
5220static void ImGui::RenderDimmedBackgrounds()
5221{
5222 ImGuiContext& g = *GImGui;
5223 ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
5224 if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
5225 return;
5226 const bool dim_bg_for_modal = (modal_window != NULL);
5227 const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
5228 if (!dim_bg_for_modal && !dim_bg_for_window_list)
5229 return;
5230
5231 ImGuiViewport* viewports_already_dimmed[2] = { NULL, NULL };
5232 if (dim_bg_for_modal)
5233 {
5234 // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
5235 ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window);
5236 RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(modal_window->DC.ModalDimBgColor, g.DimBgRatio));
5237 viewports_already_dimmed[0] = modal_window->Viewport;
5238 }
5239 else if (dim_bg_for_window_list)
5240 {
5241 // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window
5242 RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5243 if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->Viewport && g.NavWindowingListWindow->Viewport != g.NavWindowingTargetAnim->Viewport)
5244 RenderDimmedBackgroundBehindWindow(g.NavWindowingListWindow, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5245 viewports_already_dimmed[0] = g.NavWindowingTargetAnim->Viewport;
5246 viewports_already_dimmed[1] = g.NavWindowingListWindow ? g.NavWindowingListWindow->Viewport : NULL;
5247
5248 // Draw border around CTRL+Tab target window
5249 ImGuiWindow* window = g.NavWindowingTargetAnim;
5250 ImGuiViewport* viewport = window->Viewport;
5251 float distance = g.FontSize;
5252 ImRect bb = window->Rect();
5253 bb.Expand(distance);
5254 if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
5255 bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
5256 window->DrawList->ChannelsMerge();
5257 if (window->DrawList->CmdBuffer.Size == 0)
5258 window->DrawList->AddDrawCmd();
5259 window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size);
5260 window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f);
5261 window->DrawList->PopClipRect();
5262 }
5263
5264 // Draw dimming background on _other_ viewports than the ones our windows are in
5265 for (ImGuiViewportP* viewport : g.Viewports)
5266 {
5267 if (viewport == viewports_already_dimmed[0] || viewport == viewports_already_dimmed[1])
5268 continue;
5269 if (modal_window && viewport->Window && IsWindowAbove(viewport->Window, modal_window))
5270 continue;
5271 ImDrawList* draw_list = GetForegroundDrawList(viewport);
5272 const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
5273 draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col);
5274 }
5275}
5276
5277// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
5278void ImGui::EndFrame()
5279{
5280 ImGuiContext& g = *GImGui;
5281 IM_ASSERT(g.Initialized);
5282
5283 // Don't process EndFrame() multiple times.
5284 if (g.FrameCountEnded == g.FrameCount)
5285 return;
5286 IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
5287
5288 CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
5289
5290 ErrorCheckEndFrameSanityChecks();
5291
5292 // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
5293 ImGuiPlatformImeData* ime_data = &g.PlatformImeData;
5294 if (g.IO.SetPlatformImeDataFn && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0)
5295 {
5296 ImGuiViewport* viewport = FindViewportByID(g.PlatformImeViewport);
5297 IMGUI_DEBUG_LOG_IO("[io] Calling io.SetPlatformImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y);
5298 if (viewport == NULL)
5299 viewport = GetMainViewport();
5300 g.IO.SetPlatformImeDataFn(viewport, ime_data);
5301 }
5302
5303 // Hide implicit/fallback "Debug" window if it hasn't been used
5304 g.WithinFrameScopeWithImplicitWindow = false;
5305 if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
5306 g.CurrentWindow->Active = false;
5307 End();
5308
5309 // Update navigation: CTRL+Tab, wrap-around requests
5310 NavEndFrame();
5311
5312 // Update docking
5313 DockContextEndFrame(&g);
5314
5315 SetCurrentViewport(NULL, NULL);
5316
5317 // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
5318 if (g.DragDropActive)
5319 {
5320 bool is_delivered = g.DragDropPayload.Delivery;
5321 bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));
5322 if (is_delivered || is_elapsed)
5323 ClearDragDrop();
5324 }
5325
5326 // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
5327 if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
5328 {
5329 g.DragDropWithinSource = true;
5330 SetTooltip("...");
5331 g.DragDropWithinSource = false;
5332 }
5333
5334 // End frame
5335 g.WithinFrameScope = false;
5336 g.FrameCountEnded = g.FrameCount;
5337
5338 // Initiate moving window + handle left-click and right-click focus
5339 UpdateMouseMovingWindowEndFrame();
5340
5341 // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
5342 UpdateViewportsEndFrame();
5343
5344 // Sort the window list so that all child windows are after their parent
5345 // We cannot do that on FocusWindow() because children may not exist yet
5346 g.WindowsTempSortBuffer.resize(0);
5347 g.WindowsTempSortBuffer.reserve(g.Windows.Size);
5348 for (ImGuiWindow* window : g.Windows)
5349 {
5350 if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
5351 continue;
5352 AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
5353 }
5354
5355 // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
5356 IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
5357 g.Windows.swap(g.WindowsTempSortBuffer);
5358 g.IO.MetricsActiveWindows = g.WindowsActiveCount;
5359
5360 // Unlock font atlas
5361 g.IO.Fonts->Locked = false;
5362
5363 // Clear Input data for next frame
5364 g.IO.MousePosPrev = g.IO.MousePos;
5365 g.IO.AppFocusLost = false;
5366 g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
5367 g.IO.InputQueueCharacters.resize(0);
5368
5369 CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
5370}
5371
5372// Prepare the data for rendering so you can call GetDrawData()
5373// (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all:
5374// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
5375void ImGui::Render()
5376{
5377 ImGuiContext& g = *GImGui;
5378 IM_ASSERT(g.Initialized);
5379
5380 if (g.FrameCountEnded != g.FrameCount)
5381 EndFrame();
5382 if (g.FrameCountRendered == g.FrameCount)
5383 return;
5384 g.FrameCountRendered = g.FrameCount;
5385
5386 g.IO.MetricsRenderWindows = 0;
5387 CallContextHooks(&g, ImGuiContextHookType_RenderPre);
5388
5389 // Add background ImDrawList (for each active viewport)
5390 for (ImGuiViewportP* viewport : g.Viewports)
5391 {
5392 InitViewportDrawData(viewport);
5393 if (viewport->BgFgDrawLists[0] != NULL)
5394 AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
5395 }
5396
5397 // Draw modal/window whitening backgrounds
5398 RenderDimmedBackgrounds();
5399
5400 // Add ImDrawList to render
5401 ImGuiWindow* windows_to_render_top_most[2];
5402 windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL;
5403 windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
5404 for (ImGuiWindow* window : g.Windows)
5405 {
5406 IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
5407 if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
5408 AddRootWindowToDrawData(window);
5409 }
5410 for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
5411 if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
5412 AddRootWindowToDrawData(windows_to_render_top_most[n]);
5413
5414 // Draw software mouse cursor if requested by io.MouseDrawCursor flag
5415 if (g.IO.MouseDrawCursor && g.MouseCursor != ImGuiMouseCursor_None)
5416 RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
5417
5418 // Setup ImDrawData structures for end-user
5419 g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
5420 for (ImGuiViewportP* viewport : g.Viewports)
5421 {
5422 FlattenDrawDataIntoSingleLayer(&viewport->DrawDataBuilder);
5423
5424 // Add foreground ImDrawList (for each active viewport)
5425 if (viewport->BgFgDrawLists[1] != NULL)
5426 AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
5427
5428 // We call _PopUnusedDrawCmd() last thing, as RenderDimmedBackgrounds() rely on a valid command being there (especially in docking branch).
5429 ImDrawData* draw_data = &viewport->DrawDataP;
5430 IM_ASSERT(draw_data->CmdLists.Size == draw_data->CmdListsCount);
5431 for (ImDrawList* draw_list : draw_data->CmdLists)
5432 draw_list->_PopUnusedDrawCmd();
5433
5434 g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
5435 g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
5436 }
5437
5438 CallContextHooks(&g, ImGuiContextHookType_RenderPost);
5439}
5440
5441// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
5442// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
5443ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
5444{
5445 ImGuiContext& g = *GImGui;
5446
5447 const char* text_display_end;
5448 if (hide_text_after_double_hash)
5449 text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string
5450