Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/prusa3d/PrusaSlicer.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
Diffstat (limited to 'src/imgui/imgui.cpp')
-rw-r--r--src/imgui/imgui.cpp5885
1 files changed, 3558 insertions, 2327 deletions
diff --git a/src/imgui/imgui.cpp b/src/imgui/imgui.cpp
index 2822e3e23..1b78dd83c 100644
--- a/src/imgui/imgui.cpp
+++ b/src/imgui/imgui.cpp
@@ -1,15 +1,25 @@
-// dear imgui, v1.66 WIP
+// dear imgui, v1.75
// (main code and documentation)
-// Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code.
-// Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.
-// Get latest version at https://github.com/ocornut/imgui
-// Releases change-log at https://github.com/ocornut/imgui/releases
-// Technical Support for Getting Started https://discourse.dearimgui.org/c/getting-started
-// Gallery (please post your screenshots/video there!): https://github.com/ocornut/imgui/issues/1269
+// Help:
+// - Read FAQ at http://dearimgui.org/faq
+// - Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.
+// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code. All applications in examples/ are doing that.
+
+// Resources:
+// - FAQ http://dearimgui.org/faq
+// - Homepage & latest https://github.com/ocornut/imgui
+// - Releases & changelog https://github.com/ocornut/imgui/releases
+// - Gallery https://github.com/ocornut/imgui/issues/2847 (please post your screenshots/video there!)
+// - Glossary https://github.com/ocornut/imgui/wiki/Glossary
+// - Wiki https://github.com/ocornut/imgui/wiki
+// - Issues & support https://github.com/ocornut/imgui/issues
+
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
+// See LICENSE.txt for copyright and licensing details (standard MIT License).
// This library is free but I need your support to sustain development and maintenance.
-// If you work for a company, please consider financial support, see README. For individuals: https://www.patreon.com/imgui
+// Businesses: you can support continued development via invoiced technical support, maintenance and sponsoring contracts. Please reach out to "contact AT dearimgui.org".
+// Individuals: you can support continued development via donations. See docs/README or web page.
// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
@@ -25,47 +35,39 @@ DOCUMENTATION
- MISSION STATEMENT
- END-USER GUIDE
-- PROGRAMMER GUIDE (read me!)
- - Read first
- - How to update to a newer version of Dear ImGui
- - Getting started with integrating Dear ImGui in your code/engine
- - This is how a simple application may look like (2 variations)
- - This is how a simple rendering function may look like
- - Using gamepad/keyboard navigation controls
+- PROGRAMMER GUIDE
+ - READ FIRST
+ - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
+ - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
+ - HOW A SIMPLE APPLICATION MAY LOOK LIKE (2 variations)
+ - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
+ - USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
- API BREAKING CHANGES (read me when you update!)
-- FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
- - How can I tell whether to dispatch mouse/keyboard to imgui or to my application?
- - How can I display an image? What is ImTextureID, how does it works?
- - How can I have multiple widgets with the same label or without a label? A primer on labels and the ID Stack.
- - How can I use my own math types instead of ImVec2/ImVec4?
- - How can I load a different font than the default?
- - How can I easily use icons in my application?
- - How can I load multiple fonts?
- - How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic?
- - How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
- - I integrated Dear ImGui in my engine and the text or lines are blurry..
- - I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
- - How can I help?
-
-CODE
+- FREQUENTLY ASKED QUESTIONS (FAQ)
+ - Read all answers online: https://www.dearimgui.org/faq, or in docs/FAQ.md (with a Markdown viewer)
+
+CODE
(search for "[SECTION]" in the code to find them)
// [SECTION] FORWARD DECLARATIONS
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
// [SECTION] MAIN USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
-// [SECTION] MISC HELPER/UTILITIES (Maths, String, Format, Hash, File functions)
-// [SECTION] MISC HELPER/UTILITIES (ImText* functions)
-// [SECTION] MISC HELPER/UTILITIES (Color functions)
+// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
+// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
+// [SECTION] MISC HELPERS/UTILITIES (File functions)
+// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
+// [SECTION] MISC HELPERS/UTILITIES (Color functions)
// [SECTION] ImGuiStorage
// [SECTION] ImGuiTextFilter
// [SECTION] ImGuiTextBuffer
// [SECTION] ImGuiListClipper
// [SECTION] RENDER HELPERS
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
+// [SECTION] ERROR CHECKING
+// [SECTION] SCROLLING
// [SECTION] TOOLTIPS
// [SECTION] POPUPS
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
-// [SECTION] COLUMNS
// [SECTION] DRAG AND DROP
// [SECTION] LOGGING/CAPTURING
// [SECTION] SETTINGS
@@ -83,19 +85,19 @@ CODE
MISSION STATEMENT
=================
- - Easy to use to create code-driven and data-driven tools
- - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools
- - Easy to hack and improve
- - Minimize screen real-estate usage
- - Minimize setup and maintenance
- - Minimize state storage on user side
- - Portable, minimize dependencies, run on target (consoles, phones, etc.)
- - Efficient runtime and memory consumption (NB- we do allocate when "growing" content e.g. creating a window,
- opening a tree node for the first time, etc. but a typical frame should not allocate anything)
+ - Easy to use to create code-driven and data-driven tools.
+ - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
+ - Easy to hack and improve.
+ - Minimize screen real-estate usage.
+ - Minimize setup and maintenance.
+ - Minimize state storage on user side.
+ - Portable, minimize dependencies, run on target (consoles, phones, etc.).
+ - Efficient runtime and memory consumption (NB- we do allocate when "growing" content e.g. creating a window,.
+ opening a tree node for the first time, etc. but a typical frame should not allocate anything).
Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes:
- - Doesn't look fancy, doesn't animate
- - Limited layout features, intricate layouts are typically crafted in code
+ - Doesn't look fancy, doesn't animate.
+ - Limited layout features, intricate layouts are typically crafted in code.
END-USER GUIDE
@@ -126,16 +128,29 @@ CODE
================
READ FIRST
-
- - Read the FAQ below this section!
+ ----------
+ - Remember to read the FAQ (https://www.dearimgui.org/faq)
- Your code creates the UI, if your code doesn't run the UI is gone! The UI can be highly dynamic, there are no construction
or destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, less bugs.
- Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
- - You can learn about immediate-mode GUI principles at http://www.johno.se/book/imgui.html or watch http://mollyrocket.com/861
- See README.md for more links describing the IMGUI paradigm. Dear ImGui is an implementation of the IMGUI paradigm.
+ - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
+ - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
+ You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links docs/README.md.
+ - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
+ For every application frame your UI code will be called only once. This is in contrast to e.g. Unity's own implementation of an IMGUI,
+ where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
+ - Our origin are on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
+ - This codebase is also optimized to yield decent performances with typical "Debug" builds settings.
+ - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
+ If you get an assert, read the messages and comments around the assert.
+ - C++: this is a very C-ish codebase: we don't rely on C++11, we don't include any C++ headers, and ImGui:: is a namespace.
+ - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
+ See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
+ However, imgui_internal.h can optionally export math operators for ImVec2/ImVec4, which we use in this codebase.
+ - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (avoid using it in your code!).
HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
-
+ ----------------------------------------------
- Overwrite all the sources files except for imconfig.h (if you have made modification to your copy of imconfig.h)
- Or maintain your own branch where you have imconfig.h modified.
- Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
@@ -145,20 +160,22 @@ CODE
- Try to keep your copy of dear imgui reasonably up to date.
GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
-
+ ---------------------------------------------------------------
- Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
+ - In the majority of cases you should be able to use unmodified back-ends files available in the examples/ folder.
- Add the Dear ImGui source files to your projects or using your preferred build system.
- It is recommended you build and statically link the .cpp files as part of your project and not as shared library (DLL).
- - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating imgui types with your own maths types.
+ It is recommended you build and statically link the .cpp files as part of your project and NOT as shared library (DLL).
+ - 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.
- When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
- Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
- phases of your own application. All rendering informatioe are stored into command-lists that you will retrieve after calling ImGui::Render().
+ phases of your own application. All rendering information are stored into command-lists that you will retrieve after calling ImGui::Render().
- Refer to the bindings and demo applications in the examples/ folder for instruction on how to setup your code.
- 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.
HOW A SIMPLE APPLICATION MAY LOOK LIKE
- EXHIBIT 1: USING THE EXAMPLE BINDINGS (imgui_impl_XXX.cpp files from the examples/ folder)
+ --------------------------------------
+ EXHIBIT 1: USING THE EXAMPLE BINDINGS (imgui_impl_XXX.cpp files from the examples/ folder).
// Application init: create a dear imgui context, setup some options, load fonts
ImGui::CreateContext();
@@ -167,7 +184,7 @@ CODE
// TODO: Fill optional fields of the io structure later.
// TODO: Load TTF/OTF fonts if you don't want to use the default font.
- // Initialize helper Platform and Renderer bindings (here we are using imgui_impl_win32 and imgui_impl_dx11)
+ // Initialize helper Platform and Renderer bindings (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
ImGui_ImplWin32_Init(hwnd);
ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
@@ -187,13 +204,12 @@ CODE
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
g_pSwapChain->Present(1, 0);
}
-
+
// Shutdown
ImGui_ImplDX11_Shutdown();
ImGui_ImplWin32_Shutdown();
ImGui::DestroyContext();
- HOW A SIMPLE APPLICATION MAY LOOK LIKE
EXHIBIT 2: IMPLEMENTING CUSTOM BINDING / CUSTOM ENGINE
// Application init: create a dear imgui context, setup some options, load fonts
@@ -211,7 +227,7 @@ CODE
// At this point you've got the texture data and you need to upload that your your graphic system:
// After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
- // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ below for details about ImTextureID.
+ // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
io.Fonts->TexID = (void*)texture;
@@ -228,16 +244,16 @@ CODE
io.MouseDown[1] = my_mouse_buttons[1];
// Call NewFrame(), after this point you can use ImGui::* functions anytime
- // (So you want to try calling NewFrame() as early as you can in your mainloop to be able to use imgui everywhere)
+ // (So you want to try calling NewFrame() as early as you can in your mainloop to be able to use Dear ImGui everywhere)
ImGui::NewFrame();
// Most of your application code here
ImGui::Text("Hello, world!");
- MyGameUpdate(); // may use any ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
- MyGameRender(); // may use any ImGui functions as well!
+ MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
+ MyGameRender(); // may use any Dear ImGui functions as well!
- // Render imgui, swap buffers
- // (You want to try calling EndFrame/Render as late as you can, to be able to use imgui in your own game rendering code)
+ // Render dear imgui, swap buffers
+ // (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)
ImGui::EndFrame();
ImGui::Render();
ImDrawData* draw_data = ImGui::GetDrawData();
@@ -249,17 +265,18 @@ CODE
ImGui::DestroyContext();
HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
-
+ ---------------------------------------------
void void MyImGuiRenderFunction(ImDrawData* draw_data)
{
// TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
- // TODO: Setup viewport using draw_data->DisplaySize
+ // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
// TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
// TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
- const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by ImGui
- const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by ImGui
+ const ImDrawList* cmd_list = draw_data->CmdLists[n];
+ const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by Dear ImGui
+ const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by Dear ImGui
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
@@ -270,7 +287,7 @@ CODE
else
{
// The texture for the draw call is specified by pcmd->TextureId.
- // The vast majority of draw calls will use the imgui texture atlas, which value you have set yourself during initialization.
+ // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
MyEngineBindTexture((MyTexture*)pcmd->TextureId);
// We are using scissoring to clip some objects. All low-level graphics API should supports it.
@@ -278,14 +295,14 @@ CODE
// (some elements visible outside their bounds) but you can fix that once everything else works!
// - Clipping coordinates are provided in imgui coordinates space (from draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize)
// In a single viewport application, draw_data->DisplayPos will always be (0,0) and draw_data->DisplaySize will always be == io.DisplaySize.
- // However, in the interest of supporting multi-viewport applications in the future (see 'viewport' branch on github),
+ // However, in the interest of supporting multi-viewport applications in the future (see 'viewport' branch on github),
// always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
// - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
ImVec2 pos = draw_data->DisplayPos;
MyEngineScissor((int)(pcmd->ClipRect.x - pos.x), (int)(pcmd->ClipRect.y - pos.y), (int)(pcmd->ClipRect.z - pos.x), (int)(pcmd->ClipRect.w - pos.y));
// Render 'pcmd->ElemCount/3' indexed triangles.
- // By default the indices ImDrawIdx are 16-bits, you can change them to 32-bits in imconfig.h if your engine doesn't support 16-bits indices.
+ // 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.
MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer, vtx_buffer);
}
idx_buffer += pcmd->ElemCount;
@@ -295,16 +312,25 @@ CODE
- The examples/ folders contains many actual implementation of the pseudo-codes above.
- When calling NewFrame(), the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags are updated.
- They tell you if Dear ImGui intends to use your inputs. When a flag is set you want to hide the corresponding inputs
- from the rest of your application. In every cases you need to pass on the inputs to imgui. Refer to the FAQ for more information.
- - Please read the FAQ below!. Amusingly, it is called a FAQ because people frequently run into the same issues!
+ They tell you if Dear ImGui intends to use your inputs. When a flag is set you want to hide the corresponding inputs from the
+ rest of your application. In every cases you need to pass on the inputs to Dear ImGui.
+ - Refer to the FAQ for more information. Amusingly, it is called a FAQ because people frequently run into the same issues!
USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
-
- - The gamepad/keyboard navigation is fairly functional and keeps being improved.
- - Gamepad support is particularly useful to use dear imgui on a console system (e.g. PS4, Switch, XB1) without a mouse!
+ ------------------------------------------
+ - The gamepad/keyboard navigation is fairly functional and keeps being improved.
+ - Gamepad support is particularly useful to use Dear ImGui on a console system (e.g. PS4, Switch, XB1) without a mouse!
- You can ask questions and report issues at https://github.com/ocornut/imgui/issues/787
- The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable.
+ - Keyboard:
+ - Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable.
+ NewFrame() will automatically fill io.NavInputs[] based on your io.KeysDown[] + io.KeyMap[] arrays.
+ - When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard), the io.WantCaptureKeyboard flag
+ will be set. For more advanced uses, you may want to read from:
+ - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
+ - io.NavVisible: true when the navigation cursor is visible (and usually goes false when mouse is used).
+ - or query focus information with e.g. IsWindowFocused(ImGuiFocusedFlags_AnyWindow), IsItemFocused() etc. functions.
+ Please reach out if you think the game vs navigation input sharing could be improved.
- Gamepad:
- Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable.
- Backend: Set io.BackendFlags |= ImGuiBackendFlags_HasGamepad + fill the io.NavInputs[] fields before calling NewFrame().
@@ -316,15 +342,6 @@ CODE
- You can download PNG/PSD files depicting the gamepad controls for common controllers at: http://goo.gl/9LgVZW.
- If you need to share inputs between your game and the imgui parts, the easiest approach is to go all-or-nothing, with a buttons combo
to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
- - Keyboard:
- - Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable.
- NewFrame() will automatically fill io.NavInputs[] based on your io.KeysDown[] + io.KeyMap[] arrays.
- - When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard), the io.WantCaptureKeyboard flag
- will be set. For more advanced uses, you may want to read from:
- - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
- - io.NavVisible: true when the navigation cursor is visible (and usually goes false when mouse is used).
- - or query focus information with e.g. IsWindowFocused(ImGuiFocusedFlags_AnyWindow), IsItemFocused() etc. functions.
- Please reach out if you think the game vs navigation input sharing could be improved.
- Mouse:
- PS4 users: Consider emulating a mouse cursor with DualShock4 touch pad or a spare analog stick as a mouse-emulation fallback.
- Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + uSynergy.c (on your console/tablet/phone app) to share your PC mouse/keyboard.
@@ -345,9 +362,56 @@ CODE
When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
You can read releases logs https://github.com/ocornut/imgui/releases for more details.
- - 2018/10/12 (1.66) - Renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
+ - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
+ - 2019/12/17 (1.75) - 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.
+ - 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.
+ - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
+ - ShowTestWindow() -> use ShowDemoWindow()
+ - IsRootWindowFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
+ - IsRootWindowOrAnyChildFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
+ - SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
+ - GetItemsLineHeightWithSpacing() -> use GetFrameHeightWithSpacing()
+ - ImGuiCol_ChildWindowBg -> use ImGuiCol_ChildBg
+ - ImGuiStyleVar_ChildWindowRounding -> use ImGuiStyleVar_ChildRounding
+ - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
+ - IMGUI_DISABLE_TEST_WINDOWS -> use IMGUI_DISABLE_DEMO_WINDOWS
+ - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was the vaguely documented and rarely if ever used). Instead we added an explicit PrimUnreserve() API.
+ - 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).
+ - 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.
+ - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
+ - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
+ - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
+ - Begin() [old 5 args version] -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
+ - IsRootWindowOrAnyChildHovered() -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
+ - AlignFirstTextHeightToWidgets() -> use AlignTextToFramePadding()
+ - SetNextWindowPosCenter() -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
+ - ImFont::Glyph -> use ImFontGlyph
+ - 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.
+ 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.
+ 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).
+ If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
+ - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
+ - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
+ - 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.
+ - 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
+ 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.
+ 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.
+ Please reach out if you are affected.
+ - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
+ - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
+ - 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.
+ - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
+ - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
+ - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
+ - 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 a dummy small value!
+ - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
+ - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
+ - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
+ - 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.
+ - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
+ - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
- 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
- - 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.
+ - 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.
If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
- 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
- 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.
@@ -356,12 +420,16 @@ CODE
- 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).
- 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
- 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
- - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges to enable the feature.
+ - 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.
- 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
- 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
- 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
+ - 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.).
+ old bindings will still work as is, however prefer using the separated bindings as they will be updated to support multi-viewports.
+ when adopting new bindings follow the main.cpp code of your preferred examples/ folder to know which functions to call.
+ in particular, note that old bindings called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
- 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
- - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
+ - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
- 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.
If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
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.
@@ -406,8 +474,12 @@ CODE
- 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.
- 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.
removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
+ IsItemHoveredRect() --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
+ IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
+ IsMouseHoveringWindow() --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
- 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
- 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
+ - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
- 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).
- 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 binding if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
- 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
@@ -415,10 +487,10 @@ CODE
- renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
- 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
- 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.
- - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame.
+ - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
- 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.
- - 2017/08/13 (1.51) - renamed ImGuiCol_Columns*** to ImGuiCol_Separator***. Kept redirection enums (will obsolete).
- - 2017/08/11 (1.51) - renamed ImGuiSetCond_*** types and flags to ImGuiCond_***. Kept redirection enums (will obsolete).
+ - 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).
+ - 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).
- 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
- 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.
- 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.
@@ -431,14 +503,9 @@ CODE
- 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.
- 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.
- 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
- If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you.
- If your TitleBg/TitleBgActive alpha was <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.
- 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.
- 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);
- }
+ 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 tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
+ 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:
+ 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); }
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.
- 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
- 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
@@ -465,7 +532,7 @@ CODE
- the signature of the io.RenderDrawListsFn handler has changed!
old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
- argument: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
+ parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
- 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.
@@ -497,14 +564,13 @@ CODE
- 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
- 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
- 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
- (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
- font init: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); <..Upload texture to GPU..>
- became: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); <..Upload texture to GPU>; io.Fonts->TexId = YourTextureIdentifier;
- you now 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.
- (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID.
- (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
- (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
+ - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
+ - old: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
+ - new: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->TexId = YourTexIdentifier;
+ 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.
+ - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID.
+ - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
+ - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
- 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
- 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
- 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
@@ -518,117 +584,56 @@ CODE
- 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
- FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
- ======================================
-
- Q: How can I tell whether to dispatch mouse/keyboard to imgui or to my application?
- A: You can read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags from the ImGuiIO structure (e.g. if (ImGui::GetIO().WantCaptureMouse) { ... } )
- - When 'io.WantCaptureMouse' is set, imgui wants to use your mouse state, and you may want to discard/hide the inputs from the rest of your application.
- - When 'io.WantCaptureKeyboard' is set, imgui wants to use your keyboard state, and you may want to discard/hide the inputs from the rest of your application.
- - When 'io.WantTextInput' is set to may want to notify your OS to popup an on-screen keyboard, if available (e.g. on a mobile phone, or console OS).
- Note: you should always pass your mouse/keyboard inputs to imgui, even when the io.WantCaptureXXX flag are set false.
- This is because imgui needs to detect that you clicked in the void to unfocus its own windows.
- Note: The 'io.WantCaptureMouse' is more accurate that any attempt to "check if the mouse is hovering a window" (don't do that!).
- It handle mouse dragging correctly (both dragging that started over your application or over an imgui window) and handle e.g. modal windows blocking inputs.
- Those flags are updated by ImGui::NewFrame(). Preferably read the flags after calling NewFrame() if you can afford it, but reading them before is also
- perfectly fine, as the bool toggle fairly rarely. If you have on a touch device, you might find use for an early call to UpdateHoveredWindowAndCaptureFlags().
- Note: Text input widget releases focus on "Return KeyDown", so the subsequent "Return KeyUp" event that your application receive will typically
- have 'io.WantCaptureKeyboard=false'. Depending on your application logic it may or not be inconvenient. You might want to track which key-downs
- were targeted for Dear ImGui, e.g. with an array of bool, and filter out the corresponding key-ups.)
+ FREQUENTLY ASKED QUESTIONS (FAQ)
+ ================================
- Q: How can I display an image? What is ImTextureID, how does it works?
- A: Short explanation:
- - You may use functions such as ImGui::Image(), ImGui::ImageButton() or lower-level ImDrawList::AddImage() to emit draw calls that will use your own textures.
- - Actual textures are identified in a way that is up to the user/engine. Those identifiers are stored and passed as ImTextureID (void*) value.
- - Loading image files from the disk and turning them into a texture is not within the scope of Dear ImGui (for a good reason).
- Please read documentations or tutorials on your graphics API to understand how to display textures on the screen before moving onward.
-
- Long explanation:
- - Dear ImGui's job is to create "meshes", defined in a renderer-agnostic format made of draw commands and vertices.
- At the end of the frame those meshes (ImDrawList) will be displayed by your rendering function. They are made up of textured polygons and the code
- to render them is generally fairly short (a few dozen lines). In the examples/ folder we provide functions for popular graphics API (OpenGL, DirectX, etc.).
- - Each rendering function decides on a data type to represent "textures". The concept of what is a "texture" is entirely tied to your underlying engine/graphics API.
- We carry the information to identify a "texture" in the ImTextureID type.
- ImTextureID is nothing more that a void*, aka 4/8 bytes worth of data: just enough to store 1 pointer or 1 integer of your choice.
- Dear ImGui doesn't know or understand what you are storing in ImTextureID, it merely pass ImTextureID values until they reach your rendering function.
- - In the examples/ bindings, for each graphics API binding we decided on a type that is likely to be a good representation for specifying
- an image from the end-user perspective. This is what the _examples_ rendering functions are using:
-
- OpenGL: ImTextureID = GLuint (see ImGui_ImplGlfwGL3_RenderDrawData() function in imgui_impl_glfw_gl3.cpp)
- DirectX9: ImTextureID = LPDIRECT3DTEXTURE9 (see ImGui_ImplDX9_RenderDrawData() function in imgui_impl_dx9.cpp)
- DirectX11: ImTextureID = ID3D11ShaderResourceView* (see ImGui_ImplDX11_RenderDrawData() function in imgui_impl_dx11.cpp)
- DirectX12: ImTextureID = D3D12_GPU_DESCRIPTOR_HANDLE (see ImGui_ImplDX12_RenderDrawData() function in imgui_impl_dx12.cpp)
-
- For example, in the OpenGL example binding we store raw OpenGL texture identifier (GLuint) inside ImTextureID.
- Whereas in the DirectX11 example binding we store a pointer to ID3D11ShaderResourceView inside ImTextureID, which is a higher-level structure
- tying together both the texture and information about its format and how to read it.
- - If you have a custom engine built over e.g. OpenGL, instead of passing GLuint around you may decide to use a high-level data type to carry information about
- the texture as well as how to display it (shaders, etc.). The decision of what to use as ImTextureID can always be made better knowing how your codebase
- is designed. If your engine has high-level data types for "textures" and "material" then you may want to use them.
- If you are starting with OpenGL or DirectX or Vulkan and haven't built much of a rendering engine over them, keeping the default ImTextureID
- representation suggested by the example bindings is probably the best choice.
- (Advanced users may also decide to keep a low-level type in ImTextureID, and use ImDrawList callback and pass information to their renderer)
-
- User code may do:
-
- // Cast our texture type to ImTextureID / void*
- MyTexture* texture = g_CoffeeTableTexture;
- ImGui::Image((void*)texture, ImVec2(texture->Width, texture->Height));
-
- The renderer function called after ImGui::Render() will receive that same value that the user code passed:
-
- // Cast ImTextureID / void* stored in the draw command as our texture type
- MyTexture* texture = (MyTexture*)pcmd->TextureId;
- MyEngineBindTexture2D(texture);
-
- Once you understand this design you will understand that loading image files and turning them into displayable textures is not within the scope of Dear ImGui.
- This is by design and is actually a good thing, because it means your code has full control over your data types and how you display them.
- If you want to display an image file (e.g. PNG file) into the screen, please refer to documentation and tutorials for the graphics API you are using.
-
- Here's a simplified OpenGL example using stb_image.h:
-
- // Use stb_image.h to load a PNG from disk and turn it into raw RGBA pixel data:
- #define STB_IMAGE_IMPLEMENTATION
- #include <stb_image.h>
- [...]
- int my_image_width, my_image_height;
- unsigned char* my_image_data = stbi_load("my_image.png", &my_image_width, &my_image_height, NULL, 4);
-
- // Turn the RGBA pixel data into an OpenGL texture:
- GLuint my_opengl_texture;
- glGenTextures(1, &my_opengl_texture);
- glBindTexture(GL_TEXTURE_2D, my_opengl_texture);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image_width, image_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data);
-
- // Now that we have an OpenGL texture, assuming our imgui rendering function (imgui_impl_xxx.cpp file) takes GLuint as ImTextureID, we can display it:
- ImGui::Image((void*)(intptr_t)my_opengl_texture, ImVec2(my_image_width, my_image_height));
-
- C/C++ tip: a void* is pointer-sized storage. You may safely store any pointer or integer into it by casting your value to ImTexture / void*, and vice-versa.
- Because both end-points (user code and rendering function) are under your control, you know exactly what is stored inside the ImTexture / void*.
- Examples:
-
- GLuint my_tex = XXX;
- void* my_void_ptr;
- my_void_ptr = (void*)(intptr_t)my_tex; // cast a GLuint into a void* (we don't take its address! we literally store the value inside the pointer)
- my_tex = (GLuint)(intptr_t)my_void_ptr; // cast a void* into a GLuint
-
- ID3D11ShaderResourceView* my_dx11_srv = XXX;
- void* my_void_ptr;
- my_void_ptr = (void*)my_dx11_srv; // cast a ID3D11ShaderResourceView* into an opaque void*
- my_dx11_srv = (ID3D11ShaderResourceView*)my_void_ptr; // cast a void* into a ID3D11ShaderResourceView*
-
- Finally, you may call ImGui::ShowMetricsWindow() to explore/visualize/understand how the ImDrawList are generated.
-
- Q: How can I have multiple widgets with the same label or without a label?
- Q: I have multiple widgets with the same label, and only the first one works. Why is that?
+ Read all answers online: https://www.dearimgui.org/faq, or in docs/FAQ.md (with a Markdown viewer)
+ Some answers are copied down here to facilitate searching in code.
+
+ Q&A: Basics
+ ===========
+
+ Q: Where is the documentation?
+ A: This library is poorly documented at the moment and expects of the user to be acquainted with C/C++.
+ - Run the examples/ and explore them.
+ - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
+ - The demo covers most features of Dear ImGui, so you can read the code and see its output.
+ - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
+ - Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the
+ examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
+ - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
+ - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
+ - Your programming IDE is your friend, find the type or function declaration to find comments
+ associated to it.
+
+ Q: What is this library called?
+ Q: Which version should I get?
+ >> This library is called "Dear ImGui", please don't call it "ImGui" :)
+ >> See https://www.dearimgui.org/faq
+
+ Q&A: Integration
+ ================
+
+ Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or to my application?
+ A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
+ >> See https://www.dearimgui.org/faq for fully detailed answer. You really want to read this.
+
+ Q. How can I enable keyboard controls?
+ Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display)
+ Q: I integrated Dear ImGui in my engine and the text or lines are blurry..
+ Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
+ >> See https://www.dearimgui.org/faq
+
+ Q&A: Usage
+ ----------
+
+ Q: Why are multiple widgets reacting when I interact with a single one?
+ Q: How can I have multiple widgets with the same label or with an empty label?
A: A primer on labels and the ID Stack...
Dear ImGui internally need to uniquely identify UI elements.
Elements that are typically not clickable (such as calls to the Text functions) don't need an ID.
- Interactive widgets (such as calls to Button buttons) need a unique ID.
+ Interactive widgets (such as calls to Button buttons) need a unique ID.
Unique ID are used internally to track active widgets and occasionally associate state to widgets.
Unique ID are implicitly built from the hash of multiple elements that identify the "path" to the UI element.
@@ -644,6 +649,9 @@ CODE
Begin("MyWindow");
Button("OK"); // Label = "OK", ID = hash of ("MyWindow", "OK")
End();
+ Begin("MyOtherWindow");
+ Button("OK"); // Label = "OK", ID = hash of ("MyOtherWindow", "OK")
+ End();
- If you have a same ID twice in the same location, you'll have a conflict:
@@ -672,8 +680,8 @@ CODE
you to animate labels. For example you may want to include varying information in a window title bar,
but windows are uniquely identified by their ID. Use "###" to pass a label that isn't part of ID:
- Button("Hello###ID"; // Label = "Hello", ID = hash of (..., "ID")
- Button("World###ID"; // Label = "World", ID = hash of (..., "ID") // Same as above, even though the label looks different
+ Button("Hello###ID"); // Label = "Hello", ID = hash of (..., "###ID")
+ Button("World###ID"); // Label = "World", ID = hash of (..., "###ID") // Same as above, even though the label looks different
sprintf(buf, "My game (%f FPS)###MyGame", fps);
Begin(buf); // Variable title, ID = hash of "MyGame"
@@ -683,47 +691,48 @@ CODE
within the same window. This is the most convenient way of distinguishing ID when iterating and
creating many UI elements programmatically.
You can push a pointer, a string or an integer value into the ID stack.
- Remember that ID are formed from the concatenation of _everything_ in the ID stack!
+ Remember that ID are formed from the concatenation of _everything_ pushed into the ID stack.
+ At each level of the stack we store the seed used for items at this level of the ID stack.
- Begin("Window");
+ Begin("Window");
for (int i = 0; i < 100; i++)
{
- PushID(i); // Push i to the id tack
- Button("Click"); // Label = "Click", ID = Hash of ("Window", i, "Click")
+ PushID(i); // Push i to the id tack
+ Button("Click"); // Label = "Click", ID = hash of ("Window", i, "Click")
PopID();
}
for (int i = 0; i < 100; i++)
{
MyObject* obj = Objects[i];
PushID(obj);
- Button("Click"); // Label = "Click", ID = Hash of ("Window", obj pointer, "Click")
+ Button("Click"); // Label = "Click", ID = hash of ("Window", obj pointer, "Click")
PopID();
}
for (int i = 0; i < 100; i++)
{
MyObject* obj = Objects[i];
PushID(obj->Name);
- Button("Click"); // Label = "Click", ID = Hash of ("Window", obj->Name, "Click")
+ Button("Click"); // Label = "Click", ID = hash of ("Window", obj->Name, "Click")
PopID();
}
End();
- - More example showing that you can stack multiple prefixes into the ID stack:
+ - You can stack multiple prefixes into the ID stack:
- Button("Click"); // Label = "Click", ID = hash of (..., "Click")
+ Button("Click"); // Label = "Click", ID = hash of (..., "Click")
PushID("node");
- Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click")
+ Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click")
PushID(my_ptr);
- Button("Click"); // Label = "Click", ID = hash of (..., "node", my_ptr, "Click")
+ Button("Click"); // Label = "Click", ID = hash of (..., "node", my_ptr, "Click")
PopID();
PopID();
- Tree nodes implicitly creates a scope for you by calling PushID().
- Button("Click"); // Label = "Click", ID = hash of (..., "Click")
- if (TreeNode("node"))
+ Button("Click"); // Label = "Click", ID = hash of (..., "Click")
+ if (TreeNode("node")) // <-- this function call will do a PushID() for you (unless instructed not to, with a special flag)
{
- Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click")
+ Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click")
TreePop();
}
@@ -734,116 +743,47 @@ CODE
e.g. when displaying a list of objects, using indices or pointers as ID will preserve the
node open/closed state differently. See what makes more sense in your situation!
- Q: How can I use my own math types instead of ImVec2/ImVec4?
- A: You can edit imconfig.h and setup the IM_VEC2_CLASS_EXTRA/IM_VEC4_CLASS_EXTRA macros to add implicit type conversions.
- This way you'll be able to use your own types everywhere, e.g. passsing glm::vec2 to ImGui functions instead of ImVec2.
+ Q: How can I display an image? What is ImTextureID, how does it works?
+ >> See https://www.dearimgui.org/faq and https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples
- Q: How can I load a different font than the default?
- A: Use the font atlas to load the TTF/OTF file you want:
- ImGuiIO& io = ImGui::GetIO();
- io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels);
- io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
- Default is ProggyClean.ttf, rendered at size 13, embedded in dear imgui's source code.
- (Read the 'misc/fonts/README.txt' file for more details about font loading.)
-
- New programmers: remember that in C/C++ and most programming languages if you want to use a
- backslash \ within a string literal, you need to write it double backslash "\\":
- io.Fonts->AddFontFromFileTTF("MyDataFolder\MyFontFile.ttf", size_in_pixels); // WRONG (you are escape the M here!)
- io.Fonts->AddFontFromFileTTF("MyDataFolder\\MyFontFile.ttf", size_in_pixels); // CORRECT
- io.Fonts->AddFontFromFileTTF("MyDataFolder/MyFontFile.ttf", size_in_pixels); // ALSO CORRECT
+ Q: How can I use my own math types instead of ImVec2/ImVec4?
+ Q: How can I interact with standard C++ types (such as std::string and std::vector)?
+ Q: How can I display custom shapes? (using low-level ImDrawList API)
+ >> See https://www.dearimgui.org/faq
- Q: How can I easily use icons in my application?
- A: The most convenient and practical way is to merge an icon font such as FontAwesome inside you
- main font. Then you can refer to icons within your strings.
- (Read the 'misc/fonts/README.txt' file for more details about icons font loading.)
+ Q&A: Fonts, Text
+ ================
+ Q: How can I load a different font than the default?
+ Q: How can I easily use icons in my application?
Q: How can I load multiple fonts?
- A: Use the font atlas to pack them into a single texture:
- (Read the 'misc/fonts/README.txt' file and the code in ImFontAtlas for more details.)
-
- ImGuiIO& io = ImGui::GetIO();
- ImFont* font0 = io.Fonts->AddFontDefault();
- ImFont* font1 = io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels);
- ImFont* font2 = io.Fonts->AddFontFromFileTTF("myfontfile2.ttf", size_in_pixels);
- io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
- // the first loaded font gets used by default
- // use ImGui::PushFont()/ImGui::PopFont() to change the font at runtime
-
- // Options
- ImFontConfig config;
- config.OversampleH = 3;
- config.OversampleV = 1;
- config.GlyphOffset.y -= 2.0f; // Move everything by 2 pixels up
- config.GlyphExtraSpacing.x = 1.0f; // Increase spacing between characters
- io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, &config);
-
- // Combine multiple fonts into one (e.g. for icon fonts)
- static ImWchar ranges[] = { 0xf000, 0xf3ff, 0 };
- ImFontConfig config;
- config.MergeMode = true;
- io.Fonts->AddFontDefault();
- io.Fonts->LoadFromFileTTF("fontawesome-webfont.ttf", 16.0f, &config, ranges); // Merge icon font
- io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, NULL, &config, io.Fonts->GetGlyphRangesJapanese()); // Merge japanese glyphs
-
Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
- A: When loading a font, pass custom Unicode ranges to specify the glyphs to load.
-
- // Add default Japanese ranges
- io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, io.Fonts->GetGlyphRangesJapanese());
-
- // Or create your own custom ranges (e.g. for a game you can feed your entire game script and only build the characters the game need)
- ImVector<ImWchar> ranges;
- ImFontAtlas::GlyphRangesBuilder builder;
- builder.AddText("Hello world"); // Add a string (here "Hello world" contains 7 unique characters)
- builder.AddChar(0x7262); // Add a specific character
- builder.AddRanges(io.Fonts->GetGlyphRangesJapanese()); // Add one of the default ranges
- builder.BuildRanges(&ranges); // Build the final result (ordered ranges with all the unique characters submitted)
- io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, ranges.Data);
-
- All your strings needs to use UTF-8 encoding. In C++11 you can encode a string literal in UTF-8
- by using the u8"hello" syntax. Specifying literal in your source code using a local code page
- (such as CP-923 for Japanese or CP-1251 for Cyrillic) will NOT work!
- Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8.
-
- Text input: it is up to your application to pass the right character code by calling io.AddInputCharacter().
- The applications in examples/ are doing that.
- Windows: you can use the WM_CHAR or WM_UNICHAR or WM_IME_CHAR message (depending if your app is built using Unicode or MultiByte mode).
- You may also use MultiByteToWideChar() or ToUnicode() to retrieve Unicode codepoints from MultiByte characters or keyboard state.
- Windows: if your language is relying on an Input Method Editor (IME), you copy the HWND of your window to io.ImeWindowHandle in order for
- the default implementation of io.ImeSetInputScreenPosFn() to set your Microsoft IME position correctly.
-
- Q: How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
- A: - You can create a dummy window. Call Begin() with the NoBackground | NoDecoration | NoSavedSettings | NoInputs flags.
- (The ImGuiWindowFlags_NoDecoration flag itself is a shortcut for NoTitleBar | NoResize | NoScrollbar | NoCollapse)
- Then you can retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like.
- - You can call ImGui::GetOverlayDrawList() and use this draw list to display contents over every other imgui windows.
- - You can create your own ImDrawList instance. You'll need to initialize them ImGui::GetDrawListSharedData(), or create your own ImDrawListSharedData,
- and then call your rendered code with your own ImDrawList or ImDrawData data.
+ >> See https://www.dearimgui.org/faq and docs/FONTS.txt
- Q: I integrated Dear ImGui in my engine and the text or lines are blurry..
- A: In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f).
- Also make sure your orthographic projection matrix and io.DisplaySize matches your actual framebuffer dimension.
+ Q&A: Concerns
+ =============
- Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
- A: You are probably mishandling the clipping rectangles in your render function.
- Rectangles provided by ImGui are defined as (x1=left,y1=top,x2=right,y2=bottom) and NOT as (x1,y1,width,height).
+ Q: Who uses Dear ImGui?
+ Q: Can you create elaborate/serious tools with Dear ImGui?
+ Q: Can you reskin the look of Dear ImGui?
+ Q: Why using C++ (as opposed to C)?
+ >> See https://www.dearimgui.org/faq
+
+ Q&A: Community
+ ==============
Q: How can I help?
- A: - If you are experienced with Dear ImGui and C++, look at the github issues, or docs/TODO.txt and see how you want/can help!
- - Convince your company to sponsor/fund development! Individual users: you can also become a Patron (patreon.com/imgui) or donate on PayPal! See README.
- - Disclose your usage of dear imgui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
- You may post screenshot or links in the gallery threads (github.com/ocornut/imgui/issues/1269). Visuals are ideal as they inspire other programmers.
+ A: - Businesses: please reach out to "contact AT dearimgui.org" if you work in a place using Dear ImGui!
+ We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
+ This is among the most useful thing you can do for Dear ImGui. With increased funding we can hire more people working on this project.
+ - Individuals: you can support continued development via PayPal donations. See README.
+ - If you are experienced with Dear ImGui and C++, look at the github issues, look at the Wiki, read docs/TODO.txt
+ and see how you want to help and can help!
+ - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
+ You may post screenshot or links in the gallery threads (github.com/ocornut/imgui/issues/2847). Visuals are ideal as they inspire other programmers.
But even without visuals, disclosing your use of dear imgui help the library grow credibility, and help other teams and programmers with taking decisions.
- 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).
- - tip: you can call Begin() multiple times with the same name during the same frame, it will keep appending to the same window.
- this is also useful to set yourself in the context of another window (to get/set other settings)
- - tip: you can create widgets without a Begin()/End() block, they will go in an implicit window called "Debug".
- - tip: the ImGuiOnceUponAFrame helper will allow run the block of code only once a frame. You can use it to quickly add custom UI in the middle
- of a deep nested inner loop in your code.
- - tip: you can call Render() multiple times (e.g for VR renders).
- - tip: call and read the ShowDemoWindow() code in imgui_demo.cpp for more example of how to use ImGui!
-
*/
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
@@ -851,12 +791,14 @@ CODE
#endif
#include "imgui.h"
+#ifndef IMGUI_DISABLE
+
#ifndef IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_MATH_OPERATORS
#endif
#include "imgui_internal.h"
-#include <ctype.h> // toupper, isprint
+#include <ctype.h> // toupper
#include <stdio.h> // vsnprintf, sscanf, printf
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
#include <stddef.h> // intptr_t
@@ -865,27 +807,39 @@ CODE
#endif
// Debug options
-#define IMGUI_DEBUG_NAV_SCORING 0
-#define IMGUI_DEBUG_NAV_RECTS 0
+#define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
+#define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window
+#define IMGUI_DEBUG_INI_SETTINGS 0 // Save additional comments in .ini file (particularly helps for Docking, but makes saving slower)
// Visual Studio warnings
#ifdef _MSC_VER
#pragma warning (disable: 4127) // condition expression is constant
#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
+#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later
+#pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types
+#endif
#endif
// Clang/GCC warnings with -Weverything
-#ifdef __clang__
+#if defined(__clang__)
#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning : unknown warning group '-Wformat-pedantic *' // not all warnings are known by all clang versions.. so ignoring warnings triggers new warnings on some configuration. great!
#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse.
#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.
#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.
#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.
-#pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference it.
+#pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference is.
#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness //
#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.
-#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int'
+#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int'
+#if __has_warning("-Wzero-as-null-pointer-constant")
+#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning : zero as null pointer constant // some standard header variations use #define NULL 0
+#endif
+#if __has_warning("-Wdouble-promotion")
+#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.
+#endif
#elif defined(__GNUC__)
+// We disable -Wpragmas because GCC doesn't provide an has_warning equivalent and some forks/patches may not following the warning/version association.
+#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
@@ -893,42 +847,36 @@ CODE
#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
#pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
-#if __GNUC__ >= 8
-#pragma GCC diagnostic ignored "-Wclass-memaccess" // warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
-#endif
+#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
#endif
// 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.
static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in
static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear
-// Window resizing from edges (when io.ConfigResizeWindowsFromEdges = true)
-static const float RESIZE_WINDOWS_FROM_EDGES_HALF_THICKNESS = 4.0f; // Extend outside and inside windows. Affect FindHoveredWindow().
-static const float RESIZE_WINDOWS_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time.
+// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by back-end)
+static const float WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS = 4.0f; // Extend outside and inside windows. Affect FindHoveredWindow().
+static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time.
+static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 2.00f; // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certaint time, unless mouse moved.
//-------------------------------------------------------------------------
// [SECTION] FORWARD DECLARATIONS
//-------------------------------------------------------------------------
static void SetCurrentWindow(ImGuiWindow* window);
-static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond);
-static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond);
-static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond);
static void FindHoveredWindow();
static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags);
-static void CheckStacksSize(ImGuiWindow* window, bool write);
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges);
static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list);
-static void AddWindowToDrawData(ImVector<ImDrawList*>* out_list, ImGuiWindow* window);
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
static ImRect GetViewportRect();
// Settings
-static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
-static void SettingsHandlerWindow_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
-static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
+static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
+static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
+static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
// Platform Dependents default implementation for IO functions
static const char* GetClipboardTextFn_DefaultImpl(void* user_data);
@@ -937,44 +885,53 @@ static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y);
namespace ImGui
{
-static bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags);
-
// Navigation
static void NavUpdate();
static void NavUpdateWindowing();
-static void NavUpdateWindowingList();
+static void NavUpdateWindowingOverlay();
static void NavUpdateMoveResult();
-static float NavUpdatePageUpPageDown(int allowed_dir_flags);
+static float NavUpdatePageUpPageDown();
static inline void NavUpdateAnyRequestFlag();
-static void NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, const ImGuiID id);
+static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand);
+static void NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, ImGuiID id);
static ImVec2 NavCalcPreferredRefPos();
-static void NavSaveLastChildNavWindow(ImGuiWindow* nav_window);
+static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window);
+static int FindWindowFocusIndex(ImGuiWindow* window);
+
+// Error Checking
+static void ErrorCheckEndFrame();
+static void ErrorCheckBeginEndCompareStacksSize(ImGuiWindow* window, bool write);
// Misc
static void UpdateMouseInputs();
static void UpdateMouseWheel();
-static void UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]);
-}
+static bool UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]);
+static void UpdateDebugToolItemPicker();
+static void RenderWindowOuterBorders(ImGuiWindow* window);
+static void RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
+static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
-// Test engine hooks (imgui-test)
-//#define IMGUI_ENABLE_TEST_ENGINE_HOOKS
-#ifdef IMGUI_ENABLE_TEST_ENGINE_HOOKS
-extern void ImGuiTestEngineHook_PreNewFrame();
-extern void ImGuiTestEngineHook_PostNewFrame();
-extern void ImGuiTestEngineHook_ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg);
-#endif
+}
//-----------------------------------------------------------------------------
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
//-----------------------------------------------------------------------------
// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
-// CreateContext() will automatically set this pointer if it is NULL. Change to a different context by calling ImGui::SetCurrentContext().
-// If you use DLL hotreloading you might need to call SetCurrentContext() after reloading code from this file.
-// ImGui functions are not thread-safe because of this pointer. If you want thread-safety to allow N threads to access N different contexts, you can:
-// - Change this variable to use thread local storage. You may #define GImGui in imconfig.h for that purpose. Future development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
-// - Having multiple instances of the ImGui code compiled inside different namespace (easiest/safest, if you have a finite number of contexts)
+// ImGui::CreateContext() will automatically set this pointer if it is NULL. Change to a different context by calling ImGui::SetCurrentContext().
+// 1) Important: globals are not shared across DLL boundaries! If you use DLLs or any form of hot-reloading: you will need to call
+// SetCurrentContext() (with the pointer you got from CreateContext) from each unique static/DLL boundary, and after each hot-reloading.
+// In your debugger, add GImGui to your watch window and notice how its value changes depending on which location you are currently stepping into.
+// 2) Important: Dear ImGui functions are not thread-safe because of this pointer.
+// If you want thread-safety to allow N threads to access N different contexts, you can:
+// - Change this variable to use thread local storage so each thread can refer to a different context, in imconfig.h:
+// struct ImGuiContext;
+// extern thread_local ImGuiContext* MyImGuiTLS;
+// #define GImGui MyImGuiTLS
+// And then define MyImGuiTLS in one of your cpp file. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
+// - Future development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
+// - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from different namespace.
#ifndef GImGui
ImGuiContext* GImGui = NULL;
#endif
@@ -983,11 +940,11 @@ ImGuiContext* GImGui = NULL;
// If you use DLL hotreloading you might need to call SetAllocatorFunctions() after reloading code from this file.
// Otherwise, you probably don't want to modify them mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
-static void* MallocWrapper(size_t size, void* user_data) { (void)user_data; return malloc(size); }
-static void FreeWrapper(void* ptr, void* user_data) { (void)user_data; free(ptr); }
+static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); return malloc(size); }
+static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); free(ptr); }
#else
-static void* MallocWrapper(size_t size, void* user_data) { (void)user_data; (void)size; IM_ASSERT(0); return NULL; }
-static void FreeWrapper(void* ptr, void* user_data) { (void)user_data; (void)ptr; IM_ASSERT(0); }
+static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
+static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
#endif
static void* (*GImAllocatorAllocFunc)(size_t size, void* user_data) = MallocWrapper;
@@ -1006,6 +963,7 @@ ImGuiStyle::ImGuiStyle()
WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
WindowMinSize = ImVec2(32,32); // Minimum window size
WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
+ WindowMenuButtonPosition= ImGuiDir_Left; // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
@@ -1017,18 +975,23 @@ ImGuiStyle::ImGuiStyle()
ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
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!
IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
- ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns
- ScrollbarSize = 16.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
+ ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
+ ScrollbarSize = 14.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar
GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
+ TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
+ TabBorderSize = 0.0f; // Thickness of border around tabs.
+ ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
- DisplayWindowPadding = ImVec2(20,20); // Window position are clamped to be visible within the display area by at least this amount. Only applies to regular windows.
+ SelectableTextAlign = ImVec2(0.0f,0.0f);// Alignment of selectable text when button is larger than text.
+ 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.
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.
MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU.
AntiAliasedFill = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.)
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.
+ CircleSegmentMaxError = 1.60f; // 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.
// Default theme
ImGui::StyleColorsDark(this);
@@ -1054,6 +1017,7 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor)
ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor);
GrabMinSize = ImFloor(GrabMinSize * scale_factor);
GrabRounding = ImFloor(GrabRounding * scale_factor);
+ TabRounding = ImFloor(TabRounding * scale_factor);
DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);
DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);
MouseCursorScale = ImFloor(MouseCursorScale * scale_factor);
@@ -1063,10 +1027,11 @@ ImGuiIO::ImGuiIO()
{
// Most fields are initialized with zero
memset(this, 0, sizeof(*this));
+ IM_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT); // Our pre-C++11 IM_STATIC_ASSERT() macros triggers warning on modern compilers so we don't use it here.
// Settings
- ConfigFlags = 0x00;
- BackendFlags = 0x00;
+ ConfigFlags = ImGuiConfigFlags_None;
+ BackendFlags = ImGuiBackendFlags_None;
DisplaySize = ImVec2(-1.0f, -1.0f);
DeltaTime = 1.0f/60.0f;
IniSavingRate = 5.0f;
@@ -1076,7 +1041,7 @@ ImGuiIO::ImGuiIO()
MouseDoubleClickMaxDist = 6.0f;
for (int i = 0; i < ImGuiKey_COUNT; i++)
KeyMap[i] = -1;
- KeyRepeatDelay = 0.250f;
+ KeyRepeatDelay = 0.275f;
KeyRepeatRate = 0.050f;
UserData = NULL;
@@ -1085,18 +1050,22 @@ ImGuiIO::ImGuiIO()
FontDefault = NULL;
FontAllowUserScaling = false;
DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
- DisplayVisibleMin = DisplayVisibleMax = ImVec2(0.0f, 0.0f);
- // Miscellaneous configuration options
+ // Miscellaneous options
+ MouseDrawCursor = false;
#ifdef __APPLE__
ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag
#else
ConfigMacOSXBehaviors = false;
#endif
ConfigInputTextCursorBlink = true;
- ConfigResizeWindowsFromEdges = false;
+ ConfigWindowsResizeFromEdges = true;
+ ConfigWindowsMoveFromTitleBarOnly = false;
+ ConfigWindowsMemoryCompactTimer = 60.0f;
- // Settings (User Functions)
+ // Platform Functions
+ BackendPlatformName = BackendRendererName = NULL;
+ BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
ClipboardUserData = NULL;
@@ -1107,7 +1076,7 @@ ImGuiIO::ImGuiIO()
RenderDrawListsFn = NULL;
#endif
- // Input (NB: we already have memset zero the entire structure)
+ // Input (NB: we already have memset zero the entire structure!)
MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
MouseDragThreshold = 6.0f;
@@ -1119,30 +1088,100 @@ ImGuiIO::ImGuiIO()
// Pass in translated ASCII characters for text input.
// - with glfw you can get those from the callback set in glfwSetCharCallback()
// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
-void ImGuiIO::AddInputCharacter(ImWchar c)
+void ImGuiIO::AddInputCharacter(unsigned int c)
+{
+ if (c > 0 && c <= IM_UNICODE_CODEPOINT_MAX)
+ InputQueueCharacters.push_back((ImWchar)c);
+}
+
+void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
{
- const int n = ImStrlenW(InputCharacters);
- if (n + 1 < IM_ARRAYSIZE(InputCharacters))
+ while (*utf8_chars != 0)
{
- InputCharacters[n] = c;
- InputCharacters[n+1] = '\0';
+ unsigned int c = 0;
+ utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
+ if (c > 0 && c <= IM_UNICODE_CODEPOINT_MAX)
+ InputQueueCharacters.push_back((ImWchar)c);
}
}
-void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
+void ImGuiIO::ClearInputCharacters()
{
- // We can't pass more wchars than ImGuiIO::InputCharacters[] can hold so don't convert more
- const int wchars_buf_len = sizeof(ImGuiIO::InputCharacters) / sizeof(ImWchar);
- ImWchar wchars[wchars_buf_len];
- ImTextStrFromUtf8(wchars, wchars_buf_len, utf8_chars, NULL);
- for (int i = 0; i < wchars_buf_len && wchars[i] != 0; i++)
- AddInputCharacter(wchars[i]);
+ InputQueueCharacters.resize(0);
}
//-----------------------------------------------------------------------------
-// [SECTION] MISC HELPER/UTILITIES (Maths, String, Format, Hash, File functions)
+// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
//-----------------------------------------------------------------------------
+ImVec2 ImBezierClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
+{
+ IM_ASSERT(num_segments > 0); // Use ImBezierClosestPointCasteljau()
+ ImVec2 p_last = p1;
+ ImVec2 p_closest;
+ float p_closest_dist2 = FLT_MAX;
+ float t_step = 1.0f / (float)num_segments;
+ for (int i_step = 1; i_step <= num_segments; i_step++)
+ {
+ ImVec2 p_current = ImBezierCalc(p1, p2, p3, p4, t_step * i_step);
+ ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
+ float dist2 = ImLengthSqr(p - p_line);
+ if (dist2 < p_closest_dist2)
+ {
+ p_closest = p_line;
+ p_closest_dist2 = dist2;
+ }
+ p_last = p_current;
+ }
+ return p_closest;
+}
+
+// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
+static void BezierClosestPointCasteljauStep(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)
+{
+ float dx = x4 - x1;
+ float dy = y4 - y1;
+ float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
+ float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
+ d2 = (d2 >= 0) ? d2 : -d2;
+ d3 = (d3 >= 0) ? d3 : -d3;
+ if ((d2+d3) * (d2+d3) < tess_tol * (dx*dx + dy*dy))
+ {
+ ImVec2 p_current(x4, y4);
+ ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
+ float dist2 = ImLengthSqr(p - p_line);
+ if (dist2 < p_closest_dist2)
+ {
+ p_closest = p_line;
+ p_closest_dist2 = dist2;
+ }
+ p_last = p_current;
+ }
+ else if (level < 10)
+ {
+ float x12 = (x1+x2)*0.5f, y12 = (y1+y2)*0.5f;
+ float x23 = (x2+x3)*0.5f, y23 = (y2+y3)*0.5f;
+ float x34 = (x3+x4)*0.5f, y34 = (y3+y4)*0.5f;
+ float x123 = (x12+x23)*0.5f, y123 = (y12+y23)*0.5f;
+ float x234 = (x23+x34)*0.5f, y234 = (y23+y34)*0.5f;
+ float x1234 = (x123+x234)*0.5f, y1234 = (y123+y234)*0.5f;
+ BezierClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
+ BezierClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
+ }
+}
+
+// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
+// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
+ImVec2 ImBezierClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
+{
+ IM_ASSERT(tess_tol > 0.0f);
+ ImVec2 p_last = p1;
+ ImVec2 p_closest;
+ float p_closest_dist2 = FLT_MAX;
+ BezierClosestPointCasteljauStep(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);
+ return p_closest;
+}
+
ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
{
ImVec2 ap = p - a;
@@ -1191,6 +1230,11 @@ ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c,
return proj_ca;
}
+//-----------------------------------------------------------------------------
+// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
+//-----------------------------------------------------------------------------
+
+// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
int ImStricmp(const char* str1, const char* str2)
{
int d;
@@ -1207,16 +1251,32 @@ int ImStrnicmp(const char* str1, const char* str2, size_t count)
void ImStrncpy(char* dst, const char* src, size_t count)
{
- if (count < 1) return;
- strncpy(dst, src, count);
- dst[count-1] = 0;
+ if (count < 1)
+ return;
+ if (count > 1)
+ strncpy(dst, src, count - 1);
+ dst[count - 1] = 0;
+}
+
+char* ImStrdup(const char* str)
+{
+ size_t len = strlen(str);
+ void* buf = IM_ALLOC(len + 1);
+ return (char*)memcpy(buf, (const void*)str, len + 1);
}
-char* ImStrdup(const char *str)
+char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
{
- size_t len = strlen(str) + 1;
- void* buf = ImGui::MemAlloc(len);
- return (char*)memcpy(buf, (const void*)str, len);
+ size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
+ size_t src_size = strlen(src) + 1;
+ if (dst_buf_size < src_size)
+ {
+ IM_FREE(dst);
+ dst = (char*)IM_ALLOC(src_size);
+ if (p_dst_size)
+ *p_dst_size = src_size;
+ }
+ return (char*)memcpy(dst, (const void*)src, src_size);
}
const char* ImStrchrRange(const char* str, const char* str_end, char c)
@@ -1227,7 +1287,7 @@ const char* ImStrchrRange(const char* str, const char* str_end, char c)
int ImStrlenW(const ImWchar* str)
{
- //return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bits
+ //return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bit
int n = 0;
while (*str++) n++;
return n;
@@ -1285,10 +1345,26 @@ void ImStrTrimBlanks(char* buf)
buf[p - p_start] = 0; // Zero terminate
}
+const char* ImStrSkipBlank(const char* str)
+{
+ while (str[0] == ' ' || str[0] == '\t')
+ str++;
+ return str;
+}
+
// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
// 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.
// B) When buf==NULL vsnprintf() will return the output size.
-#ifndef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS
+#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
+
+// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
+// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
+// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
+// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
+#ifdef IMGUI_USE_STB_SPRINTF
+#define STB_SPRINTF_IMPLEMENTATION
+#include "stb_sprintf.h"
+#endif
#if defined(_MSC_VER) && !defined(vsnprintf)
#define vsnprintf _vsnprintf
@@ -1298,7 +1374,11 @@ int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
+#ifdef IMGUI_USE_STB_SPRINTF
+ int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
+#else
int w = vsnprintf(buf, buf_size, fmt, args);
+#endif
va_end(args);
if (buf == NULL)
return w;
@@ -1310,7 +1390,11 @@ int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
{
+#ifdef IMGUI_USE_STB_SPRINTF
+ int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
+#else
int w = vsnprintf(buf, buf_size, fmt, args);
+#endif
if (buf == NULL)
return w;
if (w == -1 || w >= (int)buf_size)
@@ -1318,45 +1402,71 @@ int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
buf[w] = 0;
return w;
}
-#endif // #ifdef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS
+#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
+
+// CRC32 needs a 1KB lookup table (not cache friendly)
+// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
+// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
+static const ImU32 GCrc32LookupTable[256] =
+{
+ 0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
+ 0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
+ 0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
+ 0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
+ 0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
+ 0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
+ 0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
+ 0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
+ 0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
+ 0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
+ 0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
+ 0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
+ 0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
+ 0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
+ 0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
+ 0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
+};
-// Pass data_size==0 for zero-terminated strings
+// Known size hash
+// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
-ImU32 ImHash(const void* data, int data_size, ImU32 seed)
+ImU32 ImHashData(const void* data_p, size_t data_size, ImU32 seed)
{
- static ImU32 crc32_lut[256] = { 0 };
- if (!crc32_lut[1])
- {
- const ImU32 polynomial = 0xEDB88320;
- for (ImU32 i = 0; i < 256; i++)
- {
- ImU32 crc = i;
- for (ImU32 j = 0; j < 8; j++)
- crc = (crc >> 1) ^ (ImU32(-int(crc & 1)) & polynomial);
- crc32_lut[i] = crc;
- }
- }
+ ImU32 crc = ~seed;
+ const unsigned char* data = (const unsigned char*)data_p;
+ const ImU32* crc32_lut = GCrc32LookupTable;
+ while (data_size-- != 0)
+ crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
+ return ~crc;
+}
+// Zero-terminated string hash, with support for ### to reset back to seed value
+// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
+// Because this syntax is rarely used we are optimizing for the common case.
+// - If we reach ### in the string we discard the hash so far and reset to the seed.
+// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
+// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
+ImU32 ImHashStr(const char* data_p, size_t data_size, ImU32 seed)
+{
seed = ~seed;
ImU32 crc = seed;
- const unsigned char* current = (const unsigned char*)data;
-
- if (data_size > 0)
+ const unsigned char* data = (const unsigned char*)data_p;
+ const ImU32* crc32_lut = GCrc32LookupTable;
+ if (data_size != 0)
{
- // Known size
- while (data_size--)
- crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *current++];
+ while (data_size-- != 0)
+ {
+ unsigned char c = *data++;
+ if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
+ crc = seed;
+ crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
+ }
}
else
{
- // Zero-terminated string
- while (unsigned char c = *current++)
+ while (unsigned char c = *data++)
{
- // We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
- // Because this syntax is rarely used we are optimizing for the common case.
- // - If we reach ### in the string we discard the hash so far and reset to the seed.
- // - We don't do 'current += 2; continue;' after handling ### to keep the code smaller.
- if (c == '#' && current[0] == '#' && current[1] == '#')
+ if (c == '#' && data[0] == '#' && data[1] == '#')
crc = seed;
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
}
@@ -1364,10 +1474,16 @@ ImU32 ImHash(const void* data, int data_size, ImU32 seed)
return ~crc;
}
-FILE* ImFileOpen(const char* filename, const char* mode)
+//-----------------------------------------------------------------------------
+// [SECTION] MISC HELPERS/UTILITIES (File functions)
+//-----------------------------------------------------------------------------
+
+// Default file functions
+#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
+ImFileHandle ImFileOpen(const char* filename, const char* mode)
{
-#if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__GNUC__)
- // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames. Converting both strings from UTF-8 to wchar format (using a single allocation, because we can)
+#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
+ // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
const int filename_wsize = ImTextCountCharsFromUtf8(filename, NULL) + 1;
const int mode_wsize = ImTextCountCharsFromUtf8(mode, NULL) + 1;
ImVector<ImWchar> buf;
@@ -1380,42 +1496,48 @@ FILE* ImFileOpen(const char* filename, const char* mode)
#endif
}
-// Load file content into memory
-// Memory allocated with ImGui::MemAlloc(), must be freed by user using ImGui::MemFree()
-void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, size_t* out_file_size, int padding_bytes)
+// 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.
+bool ImFileClose(ImFileHandle f) { return fclose(f) == 0; }
+ImU64 ImFileGetSize(ImFileHandle f) { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
+ImU64 ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fread(data, (size_t)sz, (size_t)count, f); }
+ImU64 ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fwrite(data, (size_t)sz, (size_t)count, f); }
+#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
+
+// Helper: Load file content into memory
+// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
+void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
{
- IM_ASSERT(filename && file_open_mode);
+ IM_ASSERT(filename && mode);
if (out_file_size)
*out_file_size = 0;
- FILE* f;
- if ((f = ImFileOpen(filename, file_open_mode)) == NULL)
+ ImFileHandle f;
+ if ((f = ImFileOpen(filename, mode)) == NULL)
return NULL;
- long file_size_signed;
- if (fseek(f, 0, SEEK_END) || (file_size_signed = ftell(f)) == -1 || fseek(f, 0, SEEK_SET))
+ size_t file_size = (size_t)ImFileGetSize(f);
+ if (file_size == (size_t)-1)
{
- fclose(f);
+ ImFileClose(f);
return NULL;
}
- size_t file_size = (size_t)file_size_signed;
- void* file_data = ImGui::MemAlloc(file_size + padding_bytes);
+ void* file_data = IM_ALLOC(file_size + padding_bytes);
if (file_data == NULL)
{
- fclose(f);
+ ImFileClose(f);
return NULL;
}
- if (fread(file_data, 1, file_size, f) != file_size)
+ if (ImFileRead(file_data, 1, file_size, f) != file_size)
{
- fclose(f);
- ImGui::MemFree(file_data);
+ ImFileClose(f);
+ IM_FREE(file_data);
return NULL;
}
if (padding_bytes > 0)
memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
- fclose(f);
+ ImFileClose(f);
if (out_file_size)
*out_file_size = file_size;
@@ -1426,7 +1548,7 @@ void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, size_
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
//-----------------------------------------------------------------------------
-// Convert UTF-8 to 32-bits character, process single character input.
+// Convert UTF-8 to 32-bit character, process single character input.
// Based on stb_from_utf8() from github.com/nothings/stb/
// We handle UTF-8 decoding error by skipping forward.
int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
@@ -1441,7 +1563,7 @@ int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char*
}
if ((*str & 0xe0) == 0xc0)
{
- *out_char = 0xFFFD; // will be invalid but not end of string
+ *out_char = IM_UNICODE_CODEPOINT_INVALID; // will be invalid but not end of string
if (in_text_end && in_text_end - (const char*)str < 2) return 1;
if (*str < 0xc2) return 2;
c = (unsigned int)((*str++ & 0x1f) << 6);
@@ -1452,7 +1574,7 @@ int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char*
}
if ((*str & 0xf0) == 0xe0)
{
- *out_char = 0xFFFD; // will be invalid but not end of string
+ *out_char = IM_UNICODE_CODEPOINT_INVALID; // will be invalid but not end of string
if (in_text_end && in_text_end - (const char*)str < 3) return 1;
if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 3;
if (*str == 0xed && str[1] > 0x9f) return 3; // str[1] < 0x80 is checked below
@@ -1466,7 +1588,7 @@ int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char*
}
if ((*str & 0xf8) == 0xf0)
{
- *out_char = 0xFFFD; // will be invalid but not end of string
+ *out_char = IM_UNICODE_CODEPOINT_INVALID; // will be invalid but not end of string
if (in_text_end && in_text_end - (const char*)str < 4) return 1;
if (*str > 0xf4) return 4;
if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 4;
@@ -1497,7 +1619,7 @@ int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const cha
in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
if (c == 0)
break;
- if (c < 0x10000) // FIXME: Losing characters that don't fit in 2 bytes
+ if (c <= IM_UNICODE_CODEPOINT_MAX) // FIXME: Losing characters that don't fit in 2 bytes
*buf_out++ = (ImWchar)c;
}
*buf_out = 0;
@@ -1515,7 +1637,7 @@ int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
if (c == 0)
break;
- if (c < 0x10000)
+ if (c <= IM_UNICODE_CODEPOINT_MAX)
char_count++;
}
return char_count;
@@ -1606,7 +1728,7 @@ int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_e
}
//-----------------------------------------------------------------------------
-// [SECTION] MISC HELPER/UTILTIES (Color functions)
+// [SECTION] MISC HELPERS/UTILTIES (Color functions)
// Note: The Convert functions are early design which are not consistent with other API.
//-----------------------------------------------------------------------------
@@ -1681,53 +1803,21 @@ void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float&
}
}
-ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
-{
- ImGuiStyle& style = GImGui->Style;
- ImVec4 c = style.Colors[idx];
- c.w *= style.Alpha * alpha_mul;
- return ColorConvertFloat4ToU32(c);
-}
-
-ImU32 ImGui::GetColorU32(const ImVec4& col)
-{
- ImGuiStyle& style = GImGui->Style;
- ImVec4 c = col;
- c.w *= style.Alpha;
- return ColorConvertFloat4ToU32(c);
-}
-
-const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
-{
- ImGuiStyle& style = GImGui->Style;
- return style.Colors[idx];
-}
-
-ImU32 ImGui::GetColorU32(ImU32 col)
-{
- float style_alpha = GImGui->Style.Alpha;
- if (style_alpha >= 1.0f)
- return col;
- ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
- a = (ImU32)(a * style_alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
- return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
-}
-
//-----------------------------------------------------------------------------
// [SECTION] ImGuiStorage
// Helper: Key->value storage
//-----------------------------------------------------------------------------
// std::lower_bound but without the bullshit
-static ImVector<ImGuiStorage::Pair>::iterator LowerBound(ImVector<ImGuiStorage::Pair>& data, ImGuiID key)
+static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)
{
- ImVector<ImGuiStorage::Pair>::iterator first = data.begin();
- ImVector<ImGuiStorage::Pair>::iterator last = data.end();
+ ImGuiStorage::ImGuiStoragePair* first = data.Data;
+ ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;
size_t count = (size_t)(last - first);
while (count > 0)
{
size_t count2 = count >> 1;
- ImVector<ImGuiStorage::Pair>::iterator mid = first + count2;
+ ImGuiStorage::ImGuiStoragePair* mid = first + count2;
if (mid->key < key)
{
first = ++mid;
@@ -1749,18 +1839,18 @@ void ImGuiStorage::BuildSortByKey()
static int IMGUI_CDECL PairCompareByID(const void* lhs, const void* rhs)
{
// We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
- if (((const Pair*)lhs)->key > ((const Pair*)rhs)->key) return +1;
- if (((const Pair*)lhs)->key < ((const Pair*)rhs)->key) return -1;
+ if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;
+ if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;
return 0;
}
};
if (Data.Size > 1)
- ImQsort(Data.Data, (size_t)Data.Size, sizeof(Pair), StaticFunc::PairCompareByID);
+ ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairCompareByID);
}
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
{
- ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
+ ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
if (it == Data.end() || it->key != key)
return default_val;
return it->val_i;
@@ -1773,7 +1863,7 @@ bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
{
- ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
+ ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
if (it == Data.end() || it->key != key)
return default_val;
return it->val_f;
@@ -1781,7 +1871,7 @@ float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
{
- ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
+ ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
if (it == Data.end() || it->key != key)
return NULL;
return it->val_p;
@@ -1790,9 +1880,9 @@ void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
// 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.
int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
{
- ImVector<Pair>::iterator it = LowerBound(Data, key);
+ ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
- it = Data.insert(it, Pair(key, default_val));
+ it = Data.insert(it, ImGuiStoragePair(key, default_val));
return &it->val_i;
}
@@ -1803,27 +1893,27 @@ bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
{
- ImVector<Pair>::iterator it = LowerBound(Data, key);
+ ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
- it = Data.insert(it, Pair(key, default_val));
+ it = Data.insert(it, ImGuiStoragePair(key, default_val));
return &it->val_f;
}
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
{
- ImVector<Pair>::iterator it = LowerBound(Data, key);
+ ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
- it = Data.insert(it, Pair(key, default_val));
+ it = Data.insert(it, ImGuiStoragePair(key, default_val));
return &it->val_p;
}
// 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)
void ImGuiStorage::SetInt(ImGuiID key, int val)
{
- ImVector<Pair>::iterator it = LowerBound(Data, key);
+ ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
- Data.insert(it, Pair(key, val));
+ Data.insert(it, ImGuiStoragePair(key, val));
return;
}
it->val_i = val;
@@ -1836,10 +1926,10 @@ void ImGuiStorage::SetBool(ImGuiID key, bool val)
void ImGuiStorage::SetFloat(ImGuiID key, float val)
{
- ImVector<Pair>::iterator it = LowerBound(Data, key);
+ ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
- Data.insert(it, Pair(key, val));
+ Data.insert(it, ImGuiStoragePair(key, val));
return;
}
it->val_f = val;
@@ -1847,10 +1937,10 @@ void ImGuiStorage::SetFloat(ImGuiID key, float val)
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
{
- ImVector<Pair>::iterator it = LowerBound(Data, key);
+ ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
- Data.insert(it, Pair(key, val));
+ Data.insert(it, ImGuiStoragePair(key, val));
return;
}
it->val_p = val;
@@ -1884,16 +1974,14 @@ ImGuiTextFilter::ImGuiTextFilter(const char* default_filter)
bool ImGuiTextFilter::Draw(const char* label, float width)
{
if (width != 0.0f)
- ImGui::PushItemWidth(width);
+ ImGui::SetNextItemWidth(width);
bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
- if (width != 0.0f)
- ImGui::PopItemWidth();
if (value_changed)
Build();
return value_changed;
}
-void ImGuiTextFilter::TextRange::split(char separator, ImVector<TextRange>* out) const
+void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
{
out->resize(0);
const char* wb = b;
@@ -1902,25 +1990,25 @@ void ImGuiTextFilter::TextRange::split(char separator, ImVector<TextRange>* out)
{
if (*we == separator)
{
- out->push_back(TextRange(wb, we));
+ out->push_back(ImGuiTextRange(wb, we));
wb = we + 1;
}
we++;
}
if (wb != we)
- out->push_back(TextRange(wb, we));
+ out->push_back(ImGuiTextRange(wb, we));
}
void ImGuiTextFilter::Build()
{
Filters.resize(0);
- TextRange input_range(InputBuf, InputBuf+strlen(InputBuf));
+ ImGuiTextRange input_range(InputBuf, InputBuf+strlen(InputBuf));
input_range.split(',', &Filters);
CountGrep = 0;
for (int i = 0; i != Filters.Size; i++)
{
- TextRange& f = Filters[i];
+ ImGuiTextRange& f = Filters[i];
while (f.b < f.e && ImCharIsBlankA(f.b[0]))
f.b++;
while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
@@ -1942,19 +2030,19 @@ bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
for (int i = 0; i != Filters.Size; i++)
{
- const TextRange& f = Filters[i];
+ const ImGuiTextRange& f = Filters[i];
if (f.empty())
continue;
if (f.b[0] == '-')
{
// Subtract
- if (ImStristr(text, text_end, f.begin()+1, f.end()) != NULL)
+ if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
return false;
}
else
{
// Grep
- if (ImStristr(text, text_end, f.begin(), f.end()) != NULL)
+ if (ImStristr(text, text_end, f.b, f.e) != NULL)
return true;
}
}
@@ -1982,6 +2070,32 @@ bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
char ImGuiTextBuffer::EmptyString[1] = { 0 };
+void ImGuiTextBuffer::append(const char* str, const char* str_end)
+{
+ int len = str_end ? (int)(str_end - str) : (int)strlen(str);
+
+ // Add zero-terminator the first time
+ const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
+ const int needed_sz = write_off + len;
+ if (write_off + len >= Buf.Capacity)
+ {
+ int new_capacity = Buf.Capacity * 2;
+ Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
+ }
+
+ Buf.resize(needed_sz);
+ memcpy(&Buf[write_off - 1], str, (size_t)len);
+ Buf[write_off - 1 + len] = 0;
+}
+
+void ImGuiTextBuffer::appendf(const char* fmt, ...)
+{
+ va_list args;
+ va_start(args, fmt);
+ appendfv(fmt, args);
+ va_end(args);
+}
+
// Helper: Text buffer for logging/accumulating text
void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
{
@@ -2000,8 +2114,8 @@ void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
const int needed_sz = write_off + len;
if (write_off + len >= Buf.Capacity)
{
- int double_capacity = Buf.Capacity * 2;
- Buf.reserve(needed_sz > double_capacity ? needed_sz : double_capacity);
+ int new_capacity = Buf.Capacity * 2;
+ Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
}
Buf.resize(needed_sz);
@@ -2009,30 +2123,66 @@ void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
va_end(args_copy);
}
-void ImGuiTextBuffer::appendf(const char* fmt, ...)
-{
- va_list args;
- va_start(args, fmt);
- appendfv(fmt, args);
- va_end(args);
-}
-
//-----------------------------------------------------------------------------
// [SECTION] ImGuiListClipper
-// This is currently not as flexible/powerful as it should be, needs some rework (see TODO)
+// This is currently not as flexible/powerful as it should be and really confusing/spaghetti, mostly because we changed
+// the API mid-way through development and support two ways to using the clipper, needs some rework (see TODO)
//-----------------------------------------------------------------------------
+// Helper to calculate coarse clipping of large list of evenly sized items.
+// NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern.
+// NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX
+void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ if (g.LogEnabled)
+ {
+ // If logging is active, do not perform any clipping
+ *out_items_display_start = 0;
+ *out_items_display_end = items_count;
+ return;
+ }
+ if (window->SkipItems)
+ {
+ *out_items_display_start = *out_items_display_end = 0;
+ return;
+ }
+
+ // We create the union of the ClipRect and the NavScoringRect which at worst should be 1 page away from ClipRect
+ ImRect unclipped_rect = window->ClipRect;
+ if (g.NavMoveRequest)
+ unclipped_rect.Add(g.NavScoringRectScreen);
+
+ const ImVec2 pos = window->DC.CursorPos;
+ int start = (int)((unclipped_rect.Min.y - pos.y) / items_height);
+ int end = (int)((unclipped_rect.Max.y - pos.y) / items_height);
+
+ // When performing a navigation request, ensure we have one item extra in the direction we are moving to
+ if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Up)
+ start--;
+ if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Down)
+ end++;
+
+ start = ImClamp(start, 0, items_count);
+ end = ImClamp(end + 1, start, items_count);
+ *out_items_display_start = start;
+ *out_items_display_end = end;
+}
+
static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height)
{
// Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
// FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
// The clipper should probably have a 4th step to display the last item in a regular manner.
- ImGui::SetCursorPosY(pos_y);
- ImGuiWindow* window = ImGui::GetCurrentWindow();
- 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.
- window->DC.PrevLineSize.y = (line_height - GImGui->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.
- if (window->DC.ColumnsSet)
- window->DC.ColumnsSet->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ window->DC.CursorPos.y = pos_y;
+ window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y);
+ 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.
+ 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.
+ if (ImGuiColumns* columns = window->DC.CurrentColumns)
+ columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
}
// Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1
@@ -2040,7 +2190,10 @@ static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height)
// FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style.
void ImGuiListClipper::Begin(int count, float items_height)
{
- StartPosY = ImGui::GetCursorPosY();
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+
+ StartPosY = window->DC.CursorPos.y;
ItemsHeight = items_height;
ItemsCount = count;
StepNo = 0;
@@ -2067,7 +2220,10 @@ void ImGuiListClipper::End()
bool ImGuiListClipper::Step()
{
- if (ItemsCount == 0 || ImGui::GetCurrentWindowRead()->SkipItems)
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+
+ if (ItemsCount == 0 || window->SkipItems)
{
ItemsCount = -1;
return false;
@@ -2076,16 +2232,16 @@ bool ImGuiListClipper::Step()
{
DisplayStart = 0;
DisplayEnd = 1;
- StartPosY = ImGui::GetCursorPosY();
+ StartPosY = window->DC.CursorPos.y;
StepNo = 1;
return true;
}
if (StepNo == 1) // Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element.
{
if (ItemsCount == 1) { ItemsCount = -1; return false; }
- float items_height = ImGui::GetCursorPosY() - StartPosY;
+ float items_height = window->DC.CursorPos.y - StartPosY;
IM_ASSERT(items_height > 0.0f); // If this triggers, it means Item 0 hasn't moved the cursor vertically
- Begin(ItemsCount-1, items_height);
+ Begin(ItemsCount - 1, items_height);
DisplayStart++;
DisplayEnd++;
StepNo = 3;
@@ -2104,10 +2260,42 @@ bool ImGuiListClipper::Step()
//-----------------------------------------------------------------------------
// [SECTION] RENDER HELPERS
-// Those (internal) functions are currently quite a legacy mess - their signature and behavior will change.
+// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change.
// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: state.
//-----------------------------------------------------------------------------
+ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
+{
+ ImGuiStyle& style = GImGui->Style;
+ ImVec4 c = style.Colors[idx];
+ c.w *= style.Alpha * alpha_mul;
+ return ColorConvertFloat4ToU32(c);
+}
+
+ImU32 ImGui::GetColorU32(const ImVec4& col)
+{
+ ImGuiStyle& style = GImGui->Style;
+ ImVec4 c = col;
+ c.w *= style.Alpha;
+ return ColorConvertFloat4ToU32(c);
+}
+
+const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
+{
+ ImGuiStyle& style = GImGui->Style;
+ return style.Colors[idx];
+}
+
+ImU32 ImGui::GetColorU32(ImU32 col)
+{
+ ImGuiStyle& style = GImGui->Style;
+ if (style.Alpha >= 1.0f)
+ return col;
+ ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
+ a = (ImU32)(a * style.Alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
+ return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
+}
+
const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
{
const char* text_display_end = text;
@@ -2165,17 +2353,8 @@ void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end
// Default clip_rect uses (pos_min,pos_max)
// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
-void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
+void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
{
- // Hide anything after a '##' string
- const char* text_display_end = FindRenderedTextEnd(text, text_end);
- const int text_len = (int)(text_display_end - text);
- if (text_len == 0)
- return;
-
- ImGuiContext& g = *GImGui;
- ImGuiWindow* window = g.CurrentWindow;
-
// Perform CPU side clipping for single clipped element to avoid using scissor state
ImVec2 pos = pos_min;
const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
@@ -2194,14 +2373,108 @@ void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, cons
if (need_clipping)
{
ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
- window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
+ draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
+ }
+ else
+ {
+ draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
+ }
+}
+
+void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
+{
+ // Hide anything after a '##' string
+ const char* text_display_end = FindRenderedTextEnd(text, text_end);
+ const int text_len = (int)(text_display_end - text);
+ if (text_len == 0)
+ return;
+
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
+ if (g.LogEnabled)
+ LogRenderedText(&pos_min, text, text_display_end);
+}
+
+
+// Another overly complex function until we reorganize everything into a nice all-in-one helper.
+// 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.
+// 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.
+void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
+{
+ ImGuiContext& g = *GImGui;
+ if (text_end_full == NULL)
+ text_end_full = FindRenderedTextEnd(text);
+ const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
+
+ //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));
+ //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));
+ //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
+ // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
+ if (text_size.x > pos_max.x - pos_min.x)
+ {
+ // Hello wo...
+ // | | |
+ // min max ellipsis_max
+ // <-> this is generally some padding value
+
+ const ImFont* font = draw_list->_Data->Font;
+ const float font_size = draw_list->_Data->FontSize;
+ const char* text_end_ellipsis = NULL;
+
+ ImWchar ellipsis_char = font->EllipsisChar;
+ int ellipsis_char_count = 1;
+ if (ellipsis_char == (ImWchar)-1)
+ {
+ ellipsis_char = (ImWchar)'.';
+ ellipsis_char_count = 3;
+ }
+ const ImFontGlyph* glyph = font->FindGlyph(ellipsis_char);
+
+ float ellipsis_glyph_width = glyph->X1; // Width of the glyph with no padding on either side
+ float ellipsis_total_width = ellipsis_glyph_width; // Full width of entire ellipsis
+
+ if (ellipsis_char_count > 1)
+ {
+ // Full ellipsis size without free spacing after it.
+ const float spacing_between_dots = 1.0f * (draw_list->_Data->FontSize / font->FontSize);
+ ellipsis_glyph_width = glyph->X1 - glyph->X0 + spacing_between_dots;
+ ellipsis_total_width = ellipsis_glyph_width * (float)ellipsis_char_count - spacing_between_dots;
+ }
+
+ // We can now claim the space between pos_max.x and ellipsis_max.x
+ const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_total_width) - pos_min.x, 1.0f);
+ float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
+ if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
+ {
+ // Always display at least 1 character if there's no room for character + ellipsis
+ text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
+ text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
+ }
+ while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
+ {
+ // 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)
+ text_end_ellipsis--;
+ 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
+ }
+
+ // Render text, render ellipsis
+ RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
+ float ellipsis_x = pos_min.x + text_size_clipped_x;
+ if (ellipsis_x + ellipsis_total_width <= ellipsis_max_x)
+ for (int i = 0; i < ellipsis_char_count; i++)
+ {
+ font->RenderChar(draw_list, font_size, ImVec2(ellipsis_x, pos_min.y), GetColorU32(ImGuiCol_Text), ellipsis_char);
+ ellipsis_x += ellipsis_glyph_width;
+ }
}
else
{
- window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
+ RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
}
+
if (g.LogEnabled)
- LogRenderedText(&pos, text, text_display_end);
+ LogRenderedText(&pos_min, text, text_end_full);
}
// Render a rectangle shaped with optional rounding and borders
@@ -2231,13 +2504,11 @@ void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
}
// Render an arrow aimed to be aligned with text (p_min is a position in the same space text would be positioned). To e.g. denote expanded/collapsed state
-void ImGui::RenderArrow(ImVec2 p_min, ImGuiDir dir, float scale)
+void ImGui::RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImU32 col, ImGuiDir dir, float scale)
{
- ImGuiContext& g = *GImGui;
-
- const float h = g.FontSize * 1.00f;
+ const float h = draw_list->_Data->FontSize * 1.00f;
float r = h * 0.40f * scale;
- ImVec2 center = p_min + ImVec2(h * 0.50f, h * 0.50f * scale);
+ ImVec2 center = pos + ImVec2(h * 0.50f, h * 0.50f * scale);
ImVec2 a, b, c;
switch (dir)
@@ -2261,15 +2532,12 @@ void ImGui::RenderArrow(ImVec2 p_min, ImGuiDir dir, float scale)
IM_ASSERT(0);
break;
}
-
- g.CurrentWindow->DrawList->AddTriangleFilled(center + a, center + b, center + c, GetColorU32(ImGuiCol_Text));
+ draw_list->AddTriangleFilled(center + a, center + b, center + c, col);
}
-void ImGui::RenderBullet(ImVec2 pos)
+void ImGui::RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col)
{
- ImGuiContext& g = *GImGui;
- ImGuiWindow* window = g.CurrentWindow;
- window->DrawList->AddCircleFilled(pos, g.FontSize*0.20f, GetColorU32(ImGuiCol_Text), 8);
+ draw_list->AddCircleFilled(pos, draw_list->_Data->FontSize * 0.20f, col, 8);
}
void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col, float sz)
@@ -2297,7 +2565,7 @@ void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFl
return;
if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
return;
- ImGuiWindow* window = ImGui::GetCurrentWindow();
+ ImGuiWindow* window = g.CurrentWindow;
if (window->DC.NavHideHighlightOneFrame)
return;
@@ -2331,15 +2599,16 @@ ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name)
: DrawListInst(&context->DrawListSharedData)
{
Name = ImStrdup(name);
- ID = ImHash(name, 0);
+ ID = ImHashStr(name);
IDStack.push_back(ID);
- Flags = 0;
+ Flags = ImGuiWindowFlags_None;
Pos = ImVec2(0.0f, 0.0f);
Size = SizeFull = ImVec2(0.0f, 0.0f);
- SizeContents = SizeContentsExplicit = ImVec2(0.0f, 0.0f);
+ ContentSize = ContentSizeExplicit = ImVec2(0.0f, 0.0f);
WindowPadding = ImVec2(0.0f, 0.0f);
WindowRounding = 0.0f;
WindowBorderSize = 0.0f;
+ NameBufLen = (int)strlen(name) + 1;
MoveId = GetID("#MOVE");
ChildId = 0;
Scroll = ImVec2(0.0f, 0.0f);
@@ -2354,23 +2623,28 @@ ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name)
SkipItems = false;
Appearing = false;
Hidden = false;
+ IsFallbackWindow = false;
HasCloseButton = false;
+ ResizeBorderHeld = -1;
BeginCount = 0;
BeginOrderWithinParent = -1;
BeginOrderWithinContext = -1;
PopupId = 0;
AutoFitFramesX = AutoFitFramesY = -1;
- AutoFitOnlyGrows = false;
AutoFitChildAxises = 0x00;
+ AutoFitOnlyGrows = false;
AutoPosLastDirection = ImGuiDir_None;
- HiddenFramesRegular = HiddenFramesForResize = 0;
+ HiddenFramesCanSkipItems = HiddenFramesCannotSkipItems = 0;
SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
+ InnerRect = ImRect(0.0f, 0.0f, 0.0f, 0.0f); // Clear so the InnerRect.GetSize() code in Begin() doesn't lead to overflow even if the result isn't used.
+
LastFrameActive = -1;
+ LastTimeActive = -1.0f;
ItemWidthDefault = 0.0f;
FontWindowScale = 1.0f;
- SettingsIdx = -1;
+ SettingsOffset = -1;
DrawList = &DrawListInst;
DrawList->_OwnerName = Name;
@@ -2383,9 +2657,8 @@ ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name)
NavRectRel[0] = NavRectRel[1] = ImRect();
NavLastChildNavWindow = NULL;
- FocusIdxAllCounter = FocusIdxTabCounter = -1;
- FocusIdxAllRequestCurrent = FocusIdxTabRequestCurrent = INT_MAX;
- FocusIdxAllRequestNext = FocusIdxTabRequestNext = INT_MAX;
+ MemoryCompacted = false;
+ MemoryDrawListIdxCapacity = MemoryDrawListVtxCapacity = 0;
}
ImGuiWindow::~ImGuiWindow()
@@ -2393,13 +2666,13 @@ ImGuiWindow::~ImGuiWindow()
IM_ASSERT(DrawList == &DrawListInst);
IM_DELETE(Name);
for (int i = 0; i != ColumnsStorage.Size; i++)
- ColumnsStorage[i].~ImGuiColumnsSet();
+ ColumnsStorage[i].~ImGuiColumns();
}
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
{
ImGuiID seed = IDStack.back();
- ImGuiID id = ImHash(str, str_end ? (int)(str_end - str) : 0, seed);
+ ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
ImGui::KeepAliveID(id);
return id;
}
@@ -2407,7 +2680,15 @@ ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
ImGuiID ImGuiWindow::GetID(const void* ptr)
{
ImGuiID seed = IDStack.back();
- ImGuiID id = ImHash(&ptr, sizeof(void*), seed);
+ ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
+ ImGui::KeepAliveID(id);
+ return id;
+}
+
+ImGuiID ImGuiWindow::GetID(int n)
+{
+ ImGuiID seed = IDStack.back();
+ ImGuiID id = ImHashData(&n, sizeof(n), seed);
ImGui::KeepAliveID(id);
return id;
}
@@ -2415,13 +2696,19 @@ ImGuiID ImGuiWindow::GetID(const void* ptr)
ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end)
{
ImGuiID seed = IDStack.back();
- return ImHash(str, str_end ? (int)(str_end - str) : 0, seed);
+ return ImHashStr(str, str_end ? (str_end - str) : 0, seed);
}
ImGuiID ImGuiWindow::GetIDNoKeepAlive(const void* ptr)
{
ImGuiID seed = IDStack.back();
- return ImHash(&ptr, sizeof(void*), seed);
+ return ImHashData(&ptr, sizeof(void*), seed);
+}
+
+ImGuiID ImGuiWindow::GetIDNoKeepAlive(int n)
+{
+ ImGuiID seed = IDStack.back();
+ return ImHashData(&n, sizeof(n), seed);
}
// This is only used in rare/specific situations to manufacture an ID out of nowhere.
@@ -2429,7 +2716,7 @@ ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
{
ImGuiID seed = IDStack.back();
const int r_rel[4] = { (int)(r_abs.Min.x - Pos.x), (int)(r_abs.Min.y - Pos.y), (int)(r_abs.Max.x - Pos.x), (int)(r_abs.Max.y - Pos.y) };
- ImGuiID id = ImHash(&r_rel, sizeof(r_rel), seed);
+ ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
ImGui::KeepAliveID(id);
return id;
}
@@ -2442,23 +2729,34 @@ static void SetCurrentWindow(ImGuiWindow* window)
g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
}
-void ImGui::SetNavID(ImGuiID id, int nav_layer)
+// Free up/compact internal window buffers, we can use this when a window becomes unused.
+// This is currently unused by the library, but you may call this yourself for easy GC.
+// Not freed:
+// - ImGuiWindow, ImGuiWindowSettings, Name
+// - StateStorage, ColumnsStorage (may hold useful data)
+// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
+void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
{
- ImGuiContext& g = *GImGui;
- IM_ASSERT(g.NavWindow);
- IM_ASSERT(nav_layer == 0 || nav_layer == 1);
- g.NavId = id;
- g.NavWindow->NavLastIds[nav_layer] = id;
+ window->MemoryCompacted = true;
+ window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
+ window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
+ window->IDStack.clear();
+ window->DrawList->ClearFreeMemory();
+ window->DC.ChildWindows.clear();
+ window->DC.ItemFlagsStack.clear();
+ window->DC.ItemWidthStack.clear();
+ window->DC.TextWrapPosStack.clear();
+ window->DC.GroupStack.clear();
}
-void ImGui::SetNavIDWithRectRel(ImGuiID id, int nav_layer, const ImRect& rect_rel)
+void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
{
- ImGuiContext& g = *GImGui;
- SetNavID(id, nav_layer);
- g.NavWindow->NavRectRel[nav_layer] = rect_rel;
- g.NavMousePosDirty = true;
- g.NavDisableHighlight = false;
- g.NavDisableMouseHover = true;
+ // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
+ // The other buffers tends to amortize much faster.
+ window->MemoryCompacted = false;
+ window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
+ window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
+ window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
}
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
@@ -2468,7 +2766,8 @@ void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
if (g.ActiveIdIsJustActivated)
{
g.ActiveIdTimer = 0.0f;
- g.ActiveIdHasBeenEdited = false;
+ g.ActiveIdHasBeenPressedBefore = false;
+ g.ActiveIdHasBeenEditedBefore = false;
if (id != 0)
{
g.LastActiveId = id;
@@ -2476,36 +2775,20 @@ void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
}
}
g.ActiveId = id;
- g.ActiveIdAllowNavDirFlags = 0;
g.ActiveIdAllowOverlap = false;
g.ActiveIdWindow = window;
+ g.ActiveIdHasBeenEditedThisFrame = false;
if (id)
{
g.ActiveIdIsAlive = id;
g.ActiveIdSource = (g.NavActivateId == id || g.NavInputId == id || g.NavJustTabbedId == id || g.NavJustMovedToId == id) ? ImGuiInputSource_Nav : ImGuiInputSource_Mouse;
}
-}
-void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
-{
- ImGuiContext& g = *GImGui;
- IM_ASSERT(id != 0);
-
- // Assume that SetFocusID() is called in the context where its NavLayer is the current layer, which is the case everywhere we call it.
- const int nav_layer = window->DC.NavLayerCurrent;
- if (g.NavWindow != window)
- g.NavInitRequest = false;
- g.NavId = id;
- g.NavWindow = window;
- g.NavLayer = nav_layer;
- window->NavLastIds[nav_layer] = id;
- if (window->DC.LastItemId == id)
- window->NavRectRel[nav_layer] = ImRect(window->DC.LastItemRect.Min - window->Pos, window->DC.LastItemRect.Max - window->Pos);
-
- if (g.ActiveIdSource == ImGuiInputSource_Nav)
- g.NavDisableMouseHover = true;
- else
- g.NavDisableHighlight = true;
+ // Clear declaration of inputs claimed by the widget
+ // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
+ g.ActiveIdUsingNavDirMask = 0x00;
+ g.ActiveIdUsingNavInputMask = 0x00;
+ g.ActiveIdUsingKeyInputMask = 0x00;
}
void ImGui::ClearActiveID()
@@ -2541,11 +2824,12 @@ void ImGui::MarkItemEdited(ImGuiID id)
{
// This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
// ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need need to fill the data.
- (void)id; // Avoid unused variable warnings when asserts are compiled out.
ImGuiContext& g = *GImGui;
IM_ASSERT(g.ActiveId == id || g.ActiveId == 0 || g.DragDropActive);
+ IM_UNUSED(id); // Avoid unused variable warnings when asserts are compiled out.
//IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
- g.ActiveIdHasBeenEdited = true;
+ g.ActiveIdHasBeenEditedThisFrame = true;
+ g.ActiveIdHasBeenEditedBefore = true;
g.CurrentWindow->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Edited;
}
@@ -2565,40 +2849,46 @@ static inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFla
if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
return false;
}
-
return true;
}
// Advance cursor given item size for layout.
-void ImGui::ItemSize(const ImVec2& size, float text_offset_y)
+void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return;
+ // We increase the height in this function to accommodate for baseline offset.
+ // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
+ // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
+ const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
+ const float line_height = ImMax(window->DC.CurrLineSize.y, size.y + offset_to_match_baseline_y);
+
// Always align ourselves on pixel boundaries
- const float line_height = ImMax(window->DC.CurrentLineSize.y, size.y);
- const float text_base_offset = ImMax(window->DC.CurrentLineTextBaseOffset, text_offset_y);
//if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
- window->DC.CursorPosPrevLine = ImVec2(window->DC.CursorPos.x + size.x, window->DC.CursorPos.y);
- window->DC.CursorPos = ImVec2((float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x), (float)(int)(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y));
+ window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
+ window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y;
+ window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); // Next line
+ window->DC.CursorPos.y = IM_FLOOR(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y); // Next line
window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
//if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
window->DC.PrevLineSize.y = line_height;
- window->DC.PrevLineTextBaseOffset = text_base_offset;
- window->DC.CurrentLineSize.y = window->DC.CurrentLineTextBaseOffset = 0.0f;
+ window->DC.CurrLineSize.y = 0.0f;
+ window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
+ window->DC.CurrLineTextBaseOffset = 0.0f;
// Horizontal layout mode
if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
SameLine();
}
-void ImGui::ItemSize(const ImRect& bb, float text_offset_y)
+void ImGui::ItemSize(const ImRect& bb, float text_baseline_y)
{
- ItemSize(bb.GetSize(), text_offset_y);
+ ItemSize(bb.GetSize(), text_baseline_y);
}
// Declare item bounding box for clipping and interaction.
@@ -2606,10 +2896,6 @@ void ImGui::ItemSize(const ImRect& bb, float text_offset_y)
// declare their minimum size requirement to ItemSize() and then use a larger region for drawing/interaction, which is passed to ItemAdd().
bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg)
{
-#ifdef IMGUI_ENABLE_TEST_ENGINE_HOOKS
- ImGuiTestEngineHook_ItemAdd(bb, id, nav_bb_arg);
-#endif
-
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
@@ -2617,19 +2903,38 @@ bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg)
{
// Navigation processing runs prior to clipping early-out
// (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
- // (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests unfortunately, but it is still limited to one window.
- // it may not scale very well for windows with ten of thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
- // We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick)
+ // (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
+ // unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
+ // thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
+ // We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
+ // to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
+ // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
+ // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
window->DC.NavLayerActiveMaskNext |= window->DC.NavLayerCurrentMask;
if (g.NavId == id || g.NavAnyRequest)
if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
NavProcessItem(window, nav_bb_arg ? *nav_bb_arg : bb, id);
+
+ // [DEBUG] Item Picker tool, when enabling the "extended" version we perform the check in ItemAdd()
+#ifdef IMGUI_DEBUG_TOOL_ITEM_PICKER_EX
+ if (id == g.DebugItemPickerBreakId)
+ {
+ IM_DEBUG_BREAK();
+ g.DebugItemPickerBreakId = 0;
+ }
+#endif
}
window->DC.LastItemId = id;
window->DC.LastItemRect = bb;
- window->DC.LastItemStatusFlags = 0;
+ window->DC.LastItemStatusFlags = ImGuiItemStatusFlags_None;
+ g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
+
+#ifdef IMGUI_ENABLE_TEST_ENGINE
+ if (id != 0)
+ IMGUI_TEST_ENGINE_ITEM_ADD(nav_bb_arg ? *nav_bb_arg : bb, id);
+#endif
// Clipping test
const bool is_clipped = IsClippedEx(bb, id, false);
@@ -2671,7 +2976,8 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
if (g.ActiveId != 0 && g.ActiveId != window->DC.LastItemId && !g.ActiveIdAllowOverlap && g.ActiveId != window->MoveId)
return false;
- // Test if interactions on this window are blocked by an active popup or modal
+ // Test if interactions on this window are blocked by an active popup or modal.
+ // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
if (!IsWindowContentHoverable(window, flags))
return false;
@@ -2679,7 +2985,8 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
if ((window->DC.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
return false;
- // Special handling for the 1st item after Begin() which represent the title bar. When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect tht case.
+ // Special handling for the dummy item after Begin() which represent the title bar or tab.
+ // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
if (window->DC.LastItemId == window->MoveId && window->WriteAccessed)
return false;
return true;
@@ -2705,6 +3012,17 @@ bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id)
return false;
SetHoveredID(id);
+
+ // [DEBUG] Item Picker tool!
+ // We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making
+ // the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered
+ // items if we perform the test in ItemAdd(), but that would incur a small runtime cost.
+ // #define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX in imconfig.h if you want this check to also be performed in ItemAdd().
+ if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
+ GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
+ if (g.DebugItemPickerBreakId == id)
+ IM_DEBUG_BREAK();
+
return true;
}
@@ -2719,26 +3037,39 @@ bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged
return false;
}
-bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id, bool tab_stop)
+// Process TAB/Shift+TAB. Be mindful that this function may _clear_ the ActiveID when tabbing out.
+bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id)
{
ImGuiContext& g = *GImGui;
+ // Increment counters
const bool is_tab_stop = (window->DC.ItemFlags & (ImGuiItemFlags_NoTabStop | ImGuiItemFlags_Disabled)) == 0;
- window->FocusIdxAllCounter++;
+ window->DC.FocusCounterRegular++;
if (is_tab_stop)
- window->FocusIdxTabCounter++;
+ window->DC.FocusCounterTabStop++;
- // Process keyboard input at this point: TAB/Shift-TAB to tab out of the currently focused item.
- // Note that we can always TAB out of a widget that doesn't allow tabbing in.
- if (tab_stop && (g.ActiveId == id) && window->FocusIdxAllRequestNext == INT_MAX && window->FocusIdxTabRequestNext == INT_MAX && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab))
- window->FocusIdxTabRequestNext = window->FocusIdxTabCounter + (g.IO.KeyShift ? (is_tab_stop ? -1 : 0) : +1); // Modulo on index will be applied at the end of frame once we've got the total counter of items.
+ // Process TAB/Shift-TAB to tab *OUT* of the currently focused item.
+ // (Note that we can always TAB out of a widget that doesn't allow tabbing in)
+ if (g.ActiveId == id && g.FocusTabPressed && !IsActiveIdUsingKey(ImGuiKey_Tab) && g.FocusRequestNextWindow == NULL)
+ {
+ g.FocusRequestNextWindow = window;
+ g.FocusRequestNextCounterTabStop = window->DC.FocusCounterTabStop + (g.IO.KeyShift ? (is_tab_stop ? -1 : 0) : +1); // Modulo on index will be applied at the end of frame once we've got the total counter of items.
+ }
- if (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent)
- return true;
- if (is_tab_stop && window->FocusIdxTabCounter == window->FocusIdxTabRequestCurrent)
+ // Handle focus requests
+ if (g.FocusRequestCurrWindow == window)
{
- g.NavJustTabbedId = id;
- return true;
+ if (window->DC.FocusCounterRegular == g.FocusRequestCurrCounterRegular)
+ return true;
+ if (is_tab_stop && window->DC.FocusCounterTabStop == g.FocusRequestCurrCounterTabStop)
+ {
+ g.NavJustTabbedId = id;
+ return true;
+ }
+
+ // If another item is about to be focused, we clear our own active id
+ if (g.ActiveId == id)
+ ClearActiveID();
}
return false;
@@ -2746,21 +3077,8 @@ bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id, bool tab_stop
void ImGui::FocusableItemUnregister(ImGuiWindow* window)
{
- window->FocusIdxAllCounter--;
- window->FocusIdxTabCounter--;
-}
-
-ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_x, float default_y)
-{
- ImGuiContext& g = *GImGui;
- ImVec2 content_max;
- if (size.x < 0.0f || size.y < 0.0f)
- content_max = g.CurrentWindow->Pos + GetContentRegionMax();
- if (size.x <= 0.0f)
- size.x = (size.x == 0.0f) ? default_x : ImMax(content_max.x - g.CurrentWindow->DC.CursorPos.x, 4.0f) + size.x;
- if (size.y <= 0.0f)
- size.y = (size.y == 0.0f) ? default_y : ImMax(content_max.y - g.CurrentWindow->DC.CursorPos.y, 4.0f) + size.y;
- return size;
+ window->DC.FocusCounterRegular--;
+ window->DC.FocusCounterTabStop--;
}
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
@@ -2768,15 +3086,16 @@ float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
if (wrap_pos_x < 0.0f)
return 0.0f;
- ImGuiWindow* window = GetCurrentWindowRead();
+ ImGuiWindow* window = GImGui->CurrentWindow;
if (wrap_pos_x == 0.0f)
- wrap_pos_x = GetContentRegionMax().x + window->Pos.x;
+ wrap_pos_x = window->WorkRect.Max.x;
else if (wrap_pos_x > 0.0f)
wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
return ImMax(wrap_pos_x - pos.x, 1.0f);
}
+// IM_ALLOC() == ImGui::MemAlloc()
void* ImGui::MemAlloc(size_t size)
{
if (ImGuiContext* ctx = GImGui)
@@ -2784,9 +3103,10 @@ void* ImGui::MemAlloc(size_t size)
return GImAllocatorAllocFunc(size, GImAllocatorUserData);
}
+// IM_FREE() == ImGui::MemFree()
void ImGui::MemFree(void* ptr)
{
- if (ptr)
+ if (ptr)
if (ImGuiContext* ctx = GImGui)
ctx->IO.MetricsActiveAllocations--;
return GImAllocatorFreeFunc(ptr, GImAllocatorUserData);
@@ -2794,13 +3114,15 @@ void ImGui::MemFree(void* ptr)
const char* ImGui::GetClipboardText()
{
- return GImGui->IO.GetClipboardTextFn ? GImGui->IO.GetClipboardTextFn(GImGui->IO.ClipboardUserData) : "";
+ ImGuiContext& g = *GImGui;
+ return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
}
void ImGui::SetClipboardText(const char* text)
{
- if (GImGui->IO.SetClipboardTextFn)
- GImGui->IO.SetClipboardTextFn(GImGui->IO.ClipboardUserData, text);
+ ImGuiContext& g = *GImGui;
+ if (g.IO.SetClipboardTextFn)
+ g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
}
const char* ImGui::GetVersion()
@@ -2808,7 +3130,7 @@ const char* ImGui::GetVersion()
return IMGUI_VERSION;
}
-// Internal state access - if you want to share ImGui state between modules (e.g. DLL) or allocate it yourself
+// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
// 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
ImGuiContext* ImGui::GetCurrentContext()
{
@@ -2824,9 +3146,12 @@ void ImGui::SetCurrentContext(ImGuiContext* ctx)
#endif
}
-// Helper function to verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
-// If the user has inconsistent compilation settings, imgui configuration #define, packing pragma, etc. you may see different structures from what imgui.cpp sees which is highly problematic.
-bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert)
+// Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
+// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
+// If the user has inconsistent compilation settings, imgui configuration #define, packing pragma, etc. your user code
+// may see different structures than what imgui.cpp sees, which is problematic.
+// We usually require settings to be in imconfig.h to make sure that they are accessible to all compilation units involved with Dear ImGui.
+bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
{
bool error = false;
if (strcmp(version, IMGUI_VERSION)!=0) { error = true; IM_ASSERT(strcmp(version,IMGUI_VERSION)==0 && "Mismatched version string!"); }
@@ -2835,10 +3160,11 @@ bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, si
if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
+ if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
return !error;
}
-void ImGui::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void(*free_func)(void* ptr, void* user_data), void* user_data)
+void ImGui::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data)
{
GImAllocatorAllocFunc = alloc_func;
GImAllocatorFreeFunc = free_func;
@@ -2866,13 +3192,13 @@ void ImGui::DestroyContext(ImGuiContext* ctx)
ImGuiIO& ImGui::GetIO()
{
- IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
+ IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
return GImGui->IO;
}
ImGuiStyle& ImGui::GetStyle()
{
- IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
+ IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
return GImGui->Style;
}
@@ -2893,9 +3219,14 @@ int ImGui::GetFrameCount()
return GImGui->FrameCount;
}
-ImDrawList* ImGui::GetOverlayDrawList()
+ImDrawList* ImGui::GetBackgroundDrawList()
+{
+ return &GImGui->BackgroundDrawList;
+}
+
+ImDrawList* ImGui::GetForegroundDrawList()
{
- return &GImGui->OverlayDrawList;
+ return &GImGui->ForegroundDrawList;
}
ImDrawListSharedData* ImGui::GetDrawListSharedData()
@@ -2906,18 +3237,24 @@ ImDrawListSharedData* ImGui::GetDrawListSharedData()
void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
{
// Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
+ // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
+ // This is because we want ActiveId to be set even when the window is not permitted to move.
ImGuiContext& g = *GImGui;
FocusWindow(window);
SetActiveID(window->MoveId, window);
g.NavDisableHighlight = true;
g.ActiveIdClickOffset = g.IO.MousePos - window->RootWindow->Pos;
- if (!(window->Flags & ImGuiWindowFlags_NoMove) && !(window->RootWindow->Flags & ImGuiWindowFlags_NoMove))
+
+ bool can_move_window = true;
+ if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindow->Flags & ImGuiWindowFlags_NoMove))
+ can_move_window = false;
+ if (can_move_window)
g.MovingWindow = window;
}
// Handle mouse moving window
// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
-void ImGui::UpdateMouseMovingWindow()
+void ImGui::UpdateMouseMovingWindowNewFrame()
{
ImGuiContext& g = *GImGui;
if (g.MovingWindow != NULL)
@@ -2955,6 +3292,58 @@ void ImGui::UpdateMouseMovingWindow()
}
}
+// Initiate moving window when clicking on empty space or title bar.
+// Handle left-click and right-click focus.
+void ImGui::UpdateMouseMovingWindowEndFrame()
+{
+ ImGuiContext& g = *GImGui;
+ if (g.ActiveId != 0 || g.HoveredId != 0)
+ return;
+
+ // Unless we just made a window/popup appear
+ if (g.NavWindow && g.NavWindow->Appearing)
+ return;
+
+ // Click to focus window and start moving (after we're done with all our widgets)
+ if (g.IO.MouseClicked[0])
+ {
+ if (g.HoveredRootWindow != NULL)
+ {
+ StartMouseMovingWindow(g.HoveredWindow);
+ if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(g.HoveredRootWindow->Flags & ImGuiWindowFlags_NoTitleBar))
+ if (!g.HoveredRootWindow->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
+ g.MovingWindow = NULL;
+ }
+ else if (g.NavWindow != NULL && GetTopMostPopupModal() == NULL)
+ {
+ // Clicking on void disable focus
+ FocusWindow(NULL);
+ }
+ }
+
+ // With right mouse button we close popups without changing focus based on where the mouse is aimed
+ // Instead, focus will be restored to the window under the bottom-most closed popup.
+ // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
+ if (g.IO.MouseClicked[1])
+ {
+ // Find the top-most window between HoveredWindow and the top-most Modal Window.
+ // This is where we can trim the popup stack.
+ ImGuiWindow* modal = GetTopMostPopupModal();
+ bool hovered_window_above_modal = false;
+ if (modal == NULL)
+ hovered_window_above_modal = true;
+ for (int i = g.Windows.Size - 1; i >= 0 && hovered_window_above_modal == false; i--)
+ {
+ ImGuiWindow* window = g.Windows[i];
+ if (window == modal)
+ break;
+ if (window == g.HoveredWindow)
+ hovered_window_above_modal = true;
+ }
+ ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
+ }
+}
+
static bool IsWindowActiveAndVisible(ImGuiWindow* window)
{
return (window->Active) && (!window->Hidden);
@@ -2966,7 +3355,7 @@ static void ImGui::UpdateMouseInputs()
// Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
if (IsMousePosValid(&g.IO.MousePos))
- g.IO.MousePos = ImFloor(g.IO.MousePos);
+ g.IO.MousePos = g.LastValidMousePos = ImFloor(g.IO.MousePos);
// If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MousePosPrev))
@@ -2998,6 +3387,7 @@ static void ImGui::UpdateMouseInputs()
g.IO.MouseClickedTime[i] = g.Time;
}
g.IO.MouseClickedPos[i] = g.IO.MousePos;
+ g.IO.MouseDownWasDoubleClick[i] = g.IO.MouseDoubleClicked[i];
g.IO.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
g.IO.MouseDragMaxDistanceSqr[i] = 0.0f;
}
@@ -3009,53 +3399,96 @@ static void ImGui::UpdateMouseInputs()
g.IO.MouseDragMaxDistanceAbs[i].x = ImMax(g.IO.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
g.IO.MouseDragMaxDistanceAbs[i].y = ImMax(g.IO.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
}
+ if (!g.IO.MouseDown[i] && !g.IO.MouseReleased[i])
+ g.IO.MouseDownWasDoubleClick[i] = false;
if (g.IO.MouseClicked[i]) // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
g.NavDisableMouseHover = false;
}
}
-void ImGui::UpdateMouseWheel()
+static void StartLockWheelingWindow(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
- if (!g.HoveredWindow || g.HoveredWindow->Collapsed)
+ if (g.WheelingWindow == window)
return;
+ g.WheelingWindow = window;
+ g.WheelingWindowRefMousePos = g.IO.MousePos;
+ g.WheelingWindowTimer = WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER;
+}
+
+void ImGui::UpdateMouseWheel()
+{
+ ImGuiContext& g = *GImGui;
+
+ // Reset the locked window if we move the mouse or after the timer elapses
+ if (g.WheelingWindow != NULL)
+ {
+ g.WheelingWindowTimer -= g.IO.DeltaTime;
+ if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
+ g.WheelingWindowTimer = 0.0f;
+ if (g.WheelingWindowTimer <= 0.0f)
+ {
+ g.WheelingWindow = NULL;
+ g.WheelingWindowTimer = 0.0f;
+ }
+ }
+
if (g.IO.MouseWheel == 0.0f && g.IO.MouseWheelH == 0.0f)
return;
- // If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent (unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set).
- ImGuiWindow* window = g.HoveredWindow;
- ImGuiWindow* scroll_window = window;
- while ((scroll_window->Flags & ImGuiWindowFlags_ChildWindow) && (scroll_window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(scroll_window->Flags & ImGuiWindowFlags_NoScrollbar) && !(scroll_window->Flags & ImGuiWindowFlags_NoMouseInputs) && scroll_window->ParentWindow)
- scroll_window = scroll_window->ParentWindow;
- const bool scroll_allowed = !(scroll_window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(scroll_window->Flags & ImGuiWindowFlags_NoMouseInputs);
+ ImGuiWindow* window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
+ if (!window || window->Collapsed)
+ return;
- if (g.IO.MouseWheel != 0.0f)
+ // Zoom / Scale window
+ // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
+ if (g.IO.MouseWheel != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
{
- if (g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
+ StartLockWheelingWindow(window);
+ const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
+ const float scale = new_font_scale / window->FontWindowScale;
+ window->FontWindowScale = new_font_scale;
+ if (!(window->Flags & ImGuiWindowFlags_ChildWindow))
{
- // Zoom / Scale window
- const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
- const float scale = new_font_scale / window->FontWindowScale;
- window->FontWindowScale = new_font_scale;
-
const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
- window->Pos += offset;
- window->Size *= scale;
- window->SizeFull *= scale;
+ SetWindowPos(window, window->Pos + offset, 0);
+ window->Size = ImFloor(window->Size * scale);
+ window->SizeFull = ImFloor(window->SizeFull * scale);
}
- else if (!g.IO.KeyCtrl && scroll_allowed)
+ return;
+ }
+
+ // Mouse wheel scrolling
+ // If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent
+
+ // Vertical Mouse Wheel scrolling
+ const float wheel_y = (g.IO.MouseWheel != 0.0f && !g.IO.KeyShift) ? g.IO.MouseWheel : 0.0f;
+ if (wheel_y != 0.0f && !g.IO.KeyCtrl)
+ {
+ StartLockWheelingWindow(window);
+ while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.y == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))))
+ window = window->ParentWindow;
+ if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
{
- // Mouse wheel vertical scrolling
- float scroll_amount = 5 * scroll_window->CalcFontSize();
- scroll_amount = (float)(int)ImMin(scroll_amount, (scroll_window->ContentsRegionRect.GetHeight() + scroll_window->WindowPadding.y * 2.0f) * 0.67f);
- SetWindowScrollY(scroll_window, scroll_window->Scroll.y - g.IO.MouseWheel * scroll_amount);
+ float max_step = window->InnerRect.GetHeight() * 0.67f;
+ float scroll_step = ImFloor(ImMin(5 * window->CalcFontSize(), max_step));
+ SetScrollY(window, window->Scroll.y - wheel_y * scroll_step);
}
}
- if (g.IO.MouseWheelH != 0.0f && scroll_allowed && !g.IO.KeyCtrl)
+
+ // Horizontal Mouse Wheel scrolling, or Vertical Mouse Wheel w/ Shift held
+ const float wheel_x = (g.IO.MouseWheelH != 0.0f && !g.IO.KeyShift) ? g.IO.MouseWheelH : (g.IO.MouseWheel != 0.0f && g.IO.KeyShift) ? g.IO.MouseWheel : 0.0f;
+ if (wheel_x != 0.0f && !g.IO.KeyCtrl)
{
- // Mouse wheel horizontal scrolling (for hardware that supports it)
- float scroll_amount = scroll_window->CalcFontSize();
- SetWindowScrollX(scroll_window, scroll_window->Scroll.x - g.IO.MouseWheelH * scroll_amount);
+ StartLockWheelingWindow(window);
+ while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.x == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))))
+ window = window->ParentWindow;
+ if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
+ {
+ float max_step = window->InnerRect.GetWidth() * 0.67f;
+ float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step));
+ SetScrollX(window, window->Scroll.x - wheel_x * scroll_step);
+ }
}
}
@@ -3071,7 +3504,7 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags()
FindHoveredWindow();
// Modal windows prevents cursor from hovering behind them.
- ImGuiWindow* modal_window = GetFrontMostPopupModal();
+ ImGuiWindow* modal_window = GetTopMostPopupModal();
if (modal_window)
if (g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, modal_window))
g.HoveredRootWindow = g.HoveredWindow = NULL;
@@ -3100,13 +3533,13 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags()
if (!mouse_avail_to_imgui && !mouse_dragging_extern_payload)
g.HoveredWindow = g.HoveredRootWindow = NULL;
- // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to imgui, false = dispatch mouse info to imgui + app)
+ // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to imgui, false = dispatch mouse info to Dear ImGui + app)
if (g.WantCaptureMouseNextFrame != -1)
g.IO.WantCaptureMouse = (g.WantCaptureMouseNextFrame != 0);
else
g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (!g.OpenPopupStack.empty());
- // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to imgui, false = dispatch keyboard info to imgui + app)
+ // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to imgui, false = dispatch keyboard info to Dear ImGui + app)
if (g.WantCaptureKeyboardNextFrame != -1)
g.IO.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
else
@@ -3118,25 +3551,23 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags()
g.IO.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
}
-void ImGui::NewFrame()
+static void NewFrameSanityChecks()
{
- IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
ImGuiContext& g = *GImGui;
-#ifdef IMGUI_ENABLE_TEST_ENGINE_HOOKS
- ImGuiTestEngineHook_PreNewFrame();
-#endif
-
// Check user data
// (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
IM_ASSERT(g.Initialized);
- IM_ASSERT(g.IO.DeltaTime >= 0.0f && "Need a positive DeltaTime (zero is tolerated but will cause some timing issues)");
- IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value");
+ IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!");
+ IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
+ IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!");
IM_ASSERT(g.IO.Fonts->Fonts.Size > 0 && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded() && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
- IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting");
- IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting. Alpha cannot be negative (allows us to avoid a few clamps in color computations)");
- IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
+ IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!");
+ IM_ASSERT(g.Style.CircleSegmentMaxError > 0.0f && "Invalid style setting!");
+ IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting. Alpha cannot be negative (allows us to avoid a few clamps in color computations)!");
+ IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
+ IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
for (int n = 0; n < ImGuiKey_COUNT; n++)
IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < IM_ARRAYSIZE(g.IO.KeysDown) && "io.KeyMap[] contains an out of bound value (need to be 0..512, or -1 for unmapped key)");
@@ -3144,9 +3575,22 @@ void ImGui::NewFrame()
if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard)
IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
- // Perform simple check: the beta io.ConfigResizeWindowsFromEdges option requires back-end to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
- if (g.IO.ConfigResizeWindowsFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
- g.IO.ConfigResizeWindowsFromEdges = false;
+ // Perform simple check: the beta io.ConfigWindowsResizeFromEdges option requires back-end to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
+ if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
+ g.IO.ConfigWindowsResizeFromEdges = false;
+}
+
+void ImGui::NewFrame()
+{
+ IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
+ ImGuiContext& g = *GImGui;
+
+#ifdef IMGUI_ENABLE_TEST_ENGINE
+ ImGuiTestEngineHook_PreNewFrame(&g);
+#endif
+
+ // Check and assert for various common IO and Configuration mistakes
+ NewFrameSanityChecks();
// Load settings on first frame (if not explicitly loaded manually before)
if (!g.SettingsLoaded)
@@ -3172,24 +3616,35 @@ void ImGui::NewFrame()
}
g.Time += g.IO.DeltaTime;
- g.FrameScopeActive = true;
+ g.WithinFrameScope = true;
g.FrameCount += 1;
g.TooltipOverrideCount = 0;
g.WindowsActiveCount = 0;
- // Setup current font and draw list
+ // Setup current font and draw list shared data
g.IO.Fonts->Locked = true;
SetCurrentFont(GetDefaultFont());
IM_ASSERT(g.Font->IsLoaded());
g.DrawListSharedData.ClipRectFullscreen = ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y);
g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
-
- g.OverlayDrawList.Clear();
- g.OverlayDrawList.PushTextureID(g.IO.Fonts->TexID);
- g.OverlayDrawList.PushClipRectFullScreen();
- g.OverlayDrawList.Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0);
-
- // Mark rendering data as invalid to prevent user who may have a handle on it to use it
+ g.DrawListSharedData.SetCircleSegmentMaxError(g.Style.CircleSegmentMaxError);
+ g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
+ if (g.Style.AntiAliasedLines)
+ g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
+ if (g.Style.AntiAliasedFill)
+ g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
+ if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
+ g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
+
+ g.BackgroundDrawList.Clear();
+ g.BackgroundDrawList.PushTextureID(g.IO.Fonts->TexID);
+ g.BackgroundDrawList.PushClipRectFullScreen();
+
+ g.ForegroundDrawList.Clear();
+ g.ForegroundDrawList.PushTextureID(g.IO.Fonts->TexID);
+ g.ForegroundDrawList.PushClipRectFullScreen();
+
+ // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
g.DrawData.Clear();
// Drag and drop keep the source ID alive so even if the source disappear our state is consistent
@@ -3215,12 +3670,18 @@ void ImGui::NewFrame()
g.LastActiveIdTimer += g.IO.DeltaTime;
g.ActiveIdPreviousFrame = g.ActiveId;
g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
- g.ActiveIdPreviousFrameHasBeenEdited = g.ActiveIdHasBeenEdited;
+ g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
g.ActiveIdIsAlive = 0;
+ g.ActiveIdHasBeenEditedThisFrame = false;
g.ActiveIdPreviousFrameIsAlive = false;
g.ActiveIdIsJustActivated = false;
- if (g.ScalarAsInputTextId && g.ActiveId != g.ScalarAsInputTextId)
- g.ScalarAsInputTextId = 0;
+ if (g.TempInputTextId != 0 && g.ActiveId != g.TempInputTextId)
+ g.TempInputTextId = 0;
+ if (g.ActiveId == 0)
+ {
+ g.ActiveIdUsingNavDirMask = g.ActiveIdUsingNavInputMask = 0;
+ g.ActiveIdUsingKeyInputMask = 0;
+ }
// Drag and drop
g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
@@ -3245,12 +3706,15 @@ void ImGui::NewFrame()
g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame))) : FLT_MAX;
- // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
- UpdateMouseMovingWindow();
+ // Find hovered window
+ // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
UpdateHoveredWindowAndCaptureFlags();
+ // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
+ UpdateMouseMovingWindowNewFrame();
+
// Background darkening/whitening
- if (GetFrontMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
+ if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
else
g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
@@ -3263,58 +3727,134 @@ void ImGui::NewFrame()
UpdateMouseWheel();
// Pressing TAB activate widget focus
- if (g.ActiveId == 0 && g.NavWindow != NULL && g.NavWindow->Active && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab, false))
+ g.FocusTabPressed = (g.NavWindow && g.NavWindow->Active && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab));
+ if (g.ActiveId == 0 && g.FocusTabPressed)
{
+ // Note that SetKeyboardFocusHere() sets the Next fields mid-frame. To be consistent we also
+ // manipulate the Next fields even, even though they will be turned into Curr fields by the code below.
+ g.FocusRequestNextWindow = g.NavWindow;
+ g.FocusRequestNextCounterRegular = INT_MAX;
if (g.NavId != 0 && g.NavIdTabCounter != INT_MAX)
- g.NavWindow->FocusIdxTabRequestNext = g.NavIdTabCounter + 1 + (g.IO.KeyShift ? -1 : 1);
+ g.FocusRequestNextCounterTabStop = g.NavIdTabCounter + 1 + (g.IO.KeyShift ? -1 : 1);
else
- g.NavWindow->FocusIdxTabRequestNext = g.IO.KeyShift ? -1 : 0;
+ g.FocusRequestNextCounterTabStop = g.IO.KeyShift ? -1 : 0;
+ }
+
+ // Turn queued focus request into current one
+ g.FocusRequestCurrWindow = NULL;
+ g.FocusRequestCurrCounterRegular = g.FocusRequestCurrCounterTabStop = INT_MAX;
+ if (g.FocusRequestNextWindow != NULL)
+ {
+ ImGuiWindow* window = g.FocusRequestNextWindow;
+ g.FocusRequestCurrWindow = window;
+ if (g.FocusRequestNextCounterRegular != INT_MAX && window->DC.FocusCounterRegular != -1)
+ g.FocusRequestCurrCounterRegular = ImModPositive(g.FocusRequestNextCounterRegular, window->DC.FocusCounterRegular + 1);
+ if (g.FocusRequestNextCounterTabStop != INT_MAX && window->DC.FocusCounterTabStop != -1)
+ g.FocusRequestCurrCounterTabStop = ImModPositive(g.FocusRequestNextCounterTabStop, window->DC.FocusCounterTabStop + 1);
+ g.FocusRequestNextWindow = NULL;
+ g.FocusRequestNextCounterRegular = g.FocusRequestNextCounterTabStop = INT_MAX;
}
+
g.NavIdTabCounter = INT_MAX;
- // Mark all windows as not visible
+ // Mark all windows as not visible and compact unused memory.
IM_ASSERT(g.WindowsFocusOrder.Size == g.Windows.Size);
+ const float memory_compact_start_time = (g.IO.ConfigWindowsMemoryCompactTimer >= 0.0f) ? (float)g.Time - g.IO.ConfigWindowsMemoryCompactTimer : FLT_MAX;
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
window->WasActive = window->Active;
+ window->BeginCount = 0;
window->Active = false;
window->WriteAccessed = false;
+
+ // Garbage collect transient buffers of recently unused windows
+ if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
+ GcCompactTransientWindowBuffers(window);
}
// Closing the focused window restore focus to the first active root window in descending z-order
if (g.NavWindow && !g.NavWindow->WasActive)
- FocusPreviousWindowIgnoringOne(NULL);
+ FocusTopMostWindowUnderOne(NULL, NULL);
// No window should be open at the beginning of the frame.
// But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
g.CurrentWindowStack.resize(0);
- g.CurrentPopupStack.resize(0);
- ClosePopupsOverWindow(g.NavWindow);
+ g.BeginPopupStack.resize(0);
+ ClosePopupsOverWindow(g.NavWindow, false);
- // Create implicit window - we will only render it if the user has added something to it.
+ // [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
+ UpdateDebugToolItemPicker();
+
+ // Create implicit/fallback window - which we will only render it if the user has added something to it.
// We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
+ // This fallback is particularly important as it avoid ImGui:: calls from crashing.
+ g.WithinFrameScopeWithImplicitWindow = true;
SetNextWindowSize(ImVec2(400,400), ImGuiCond_FirstUseEver);
Begin("Debug##Default");
+ IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
-#ifdef IMGUI_ENABLE_TEST_ENGINE_HOOKS
- ImGuiTestEngineHook_PostNewFrame();
+#ifdef IMGUI_ENABLE_TEST_ENGINE
+ ImGuiTestEngineHook_PostNewFrame(&g);
#endif
}
+// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
+void ImGui::UpdateDebugToolItemPicker()
+{
+ ImGuiContext& g = *GImGui;
+ g.DebugItemPickerBreakId = 0;
+ if (g.DebugItemPickerActive)
+ {
+ const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
+ ImGui::SetMouseCursor(ImGuiMouseCursor_Hand);
+ if (ImGui::IsKeyPressedMap(ImGuiKey_Escape))
+ g.DebugItemPickerActive = false;
+ if (ImGui::IsMouseClicked(0) && hovered_id)
+ {
+ g.DebugItemPickerBreakId = hovered_id;
+ g.DebugItemPickerActive = false;
+ }
+ ImGui::SetNextWindowBgAlpha(0.60f);
+ ImGui::BeginTooltip();
+ ImGui::Text("HoveredId: 0x%08X", hovered_id);
+ ImGui::Text("Press ESC to abort picking.");
+ ImGui::TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click to break in debugger!");
+ ImGui::EndTooltip();
+ }
+}
+
void ImGui::Initialize(ImGuiContext* context)
{
ImGuiContext& g = *context;
IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
// Add .ini handle for ImGuiWindow type
- ImGuiSettingsHandler ini_handler;
- ini_handler.TypeName = "Window";
- ini_handler.TypeHash = ImHash("Window", 0, 0);
- ini_handler.ReadOpenFn = SettingsHandlerWindow_ReadOpen;
- ini_handler.ReadLineFn = SettingsHandlerWindow_ReadLine;
- ini_handler.WriteAllFn = SettingsHandlerWindow_WriteAll;
- g.SettingsHandlers.push_front(ini_handler);
+ {
+ ImGuiSettingsHandler ini_handler;
+ ini_handler.TypeName = "Window";
+ ini_handler.TypeHash = ImHashStr("Window");
+ ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
+ ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
+ ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
+ g.SettingsHandlers.push_back(ini_handler);
+ }
+
+#ifdef IMGUI_HAS_TABLE
+ // Add .ini handle for ImGuiTable type
+ {
+ ImGuiSettingsHandler ini_handler;
+ ini_handler.TypeName = "Table";
+ ini_handler.TypeHash = ImHashStr("Table");
+ ini_handler.ReadOpenFn = TableSettingsHandler_ReadOpen;
+ ini_handler.ReadLineFn = TableSettingsHandler_ReadLine;
+ ini_handler.WriteAllFn = TableSettingsHandler_WriteAll;
+ g.SettingsHandlers.push_back(ini_handler);
+ }
+#endif // #ifdef IMGUI_HAS_TABLE
+
+#ifdef IMGUI_HAS_DOCK
+#endif // #ifdef IMGUI_HAS_DOCK
g.Initialized = true;
}
@@ -3331,7 +3871,7 @@ void ImGui::Shutdown(ImGuiContext* context)
}
g.IO.Fonts = NULL;
- // Cleanup of other data are conditional on actually having initialized ImGui.
+ // Cleanup of other data are conditional on actually having initialized Dear ImGui.
if (!g.Initialized)
return;
@@ -3349,38 +3889,42 @@ void ImGui::Shutdown(ImGuiContext* context)
IM_DELETE(g.Windows[i]);
g.Windows.clear();
g.WindowsFocusOrder.clear();
- g.WindowsSortBuffer.clear();
+ g.WindowsTempSortBuffer.clear();
g.CurrentWindow = NULL;
g.CurrentWindowStack.clear();
g.WindowsById.Clear();
g.NavWindow = NULL;
- g.HoveredWindow = NULL;
- g.HoveredRootWindow = NULL;
+ g.HoveredWindow = g.HoveredRootWindow = NULL;
g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
g.MovingWindow = NULL;
g.ColorModifiers.clear();
g.StyleModifiers.clear();
g.FontStack.clear();
g.OpenPopupStack.clear();
- g.CurrentPopupStack.clear();
+ g.BeginPopupStack.clear();
g.DrawDataBuilder.ClearFreeMemory();
- g.OverlayDrawList.ClearFreeMemory();
+ g.BackgroundDrawList.ClearFreeMemory();
+ g.ForegroundDrawList.ClearFreeMemory();
+
+ g.TabBars.Clear();
+ g.CurrentTabBarStack.clear();
+ g.ShrinkWidthBuffer.clear();
+
g.PrivateClipboard.clear();
- g.InputTextState.TextW.clear();
- g.InputTextState.InitialText.clear();
- g.InputTextState.TempBuffer.clear();
+ g.InputTextState.ClearFreeMemory();
- for (int i = 0; i < g.SettingsWindows.Size; i++)
- IM_DELETE(g.SettingsWindows[i].Name);
g.SettingsWindows.clear();
g.SettingsHandlers.clear();
- if (g.LogFile && g.LogFile != stdout)
+ if (g.LogFile)
{
- fclose(g.LogFile);
+#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
+ if (g.LogFile != stdout)
+#endif
+ ImFileClose(g.LogFile);
g.LogFile = NULL;
}
- g.LogClipboard.clear();
+ g.LogBuffer.clear();
g.Initialized = false;
}
@@ -3404,7 +3948,7 @@ static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, Im
{
int count = window->DC.ChildWindows.Size;
if (count > 1)
- ImQsort(window->DC.ChildWindows.begin(), (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
+ ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
for (int i = 0; i < count; i++)
{
ImGuiWindow* child = window->DC.ChildWindows[i];
@@ -3428,19 +3972,28 @@ static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* d
return;
}
- // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc. May trigger for you if you are using PrimXXX functions incorrectly.
+ // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc.
+ // May trigger for you if you are using PrimXXX functions incorrectly.
IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
- IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
+ if (!(draw_list->Flags & ImDrawListFlags_AllowVtxOffset))
+ IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
// Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window)
// If this assert triggers because you are drawing lots of stuff manually:
- // A) Make sure you are coarse clipping, because ImDrawList let all your vertices pass. You can use the Metrics window to inspect draw list contents.
- // B) If you need/want meshes with more than 64K vertices, uncomment the '#define ImDrawIdx unsigned int' line in imconfig.h to set the index size to 4 bytes.
- // You'll need to handle the 4-bytes indices to your renderer. For example, the OpenGL example code detect index size at compile-time by doing:
- // glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
- // Your own engine or render API may use different parameters or function calls to specify index sizes. 2 and 4 bytes indices are generally supported by most API.
- // C) If for some reason you cannot use 4 bytes indices or don't want to, a workaround is to call BeginChild()/EndChild() before reaching the 64K limit to split your draw commands in multiple draw lists.
+ // - First, make sure you are coarse clipping yourself and not trying to draw many things outside visible bounds.
+ // Be mindful that the ImDrawList API doesn't filter vertices. Use the Metrics window to inspect draw list contents.
+ // - If you want large meshes with more than 64K vertices, you can either:
+ // (A) Handle the ImDrawCmd::VtxOffset value in your renderer back-end, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'.
+ // Most example back-ends already support this from 1.71. Pre-1.71 back-ends won't.
+ // Some graphics API such as GL ES 1/2 don't have a way to offset the starting vertex so it is not supported for them.
+ // (B) Or handle 32-bit indices in your renderer back-end, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h.
+ // Most example back-ends already support this. For example, the OpenGL example code detect index size at compile-time:
+ // glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
+ // Your own engine or render API may use different parameters or function calls to specify index sizes.
+ // 2 and 4 bytes indices are generally supported by most graphics API.
+ // - If for some reason neither of those solutions works for you, a workaround is to call BeginChild()/EndChild() before reaching
+ // the 64K limit to split your draw commands in multiple draw lists.
if (sizeof(ImDrawIdx) == 2)
IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above");
@@ -3460,13 +4013,12 @@ static void AddWindowToDrawData(ImVector<ImDrawList*>* out_render_list, ImGuiWin
}
}
-static void AddWindowToDrawDataSelectLayer(ImGuiWindow* window)
+// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
+static void AddRootWindowToDrawData(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
- if (window->Flags & ImGuiWindowFlags_Tooltip)
- AddWindowToDrawData(&g.DrawDataBuilder.Layers[1], window);
- else
- AddWindowToDrawData(&g.DrawDataBuilder.Layers[0], window);
+ int layer = (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
+ AddWindowToDrawData(&g.DrawDataBuilder.Layers[layer], window);
}
void ImDrawDataBuilder::FlattenIntoSingleLayer()
@@ -3496,6 +4048,7 @@ static void SetupDrawData(ImVector<ImDrawList*>* draw_lists, ImDrawData* draw_da
draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
draw_data->DisplayPos = ImVec2(0.0f, 0.0f);
draw_data->DisplaySize = io.DisplaySize;
+ draw_data->FramebufferScale = io.DisplayFramebufferScale;
for (int n = 0; n < draw_lists->Size; n++)
{
draw_data->TotalVtxCount += draw_lists->Data[n]->VtxBuffer.Size;
@@ -3525,24 +4078,26 @@ void ImGui::EndFrame()
IM_ASSERT(g.Initialized);
if (g.FrameCountEnded == g.FrameCount) // Don't process EndFrame() multiple times.
return;
- IM_ASSERT(g.FrameScopeActive && "Forgot to call ImGui::NewFrame()");
+ IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
// Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
- if (g.IO.ImeSetInputScreenPosFn && ImLengthSqr(g.PlatformImeLastPos - g.PlatformImePos) > 0.0001f)
+ if (g.IO.ImeSetInputScreenPosFn && (g.PlatformImeLastPos.x == FLT_MAX || ImLengthSqr(g.PlatformImeLastPos - g.PlatformImePos) > 0.0001f))
{
g.IO.ImeSetInputScreenPosFn((int)g.PlatformImePos.x, (int)g.PlatformImePos.y);
g.PlatformImeLastPos = g.PlatformImePos;
}
- // Hide implicit "Debug" window if it hasn't been used
- IM_ASSERT(g.CurrentWindowStack.Size == 1); // Mismatched Begin()/End() calls, did you forget to call end on g.CurrentWindow->Name?
+ ErrorCheckEndFrame();
+
+ // Hide implicit/fallback "Debug" window if it hasn't been used
+ g.WithinFrameScopeWithImplicitWindow = false;
if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
g.CurrentWindow->Active = false;
End();
- // Show CTRL+TAB list
- if (g.NavWindowingTarget)
- NavUpdateWindowingList();
+ // Show CTRL+TAB list window
+ if (g.NavWindowingTarget != NULL)
+ NavUpdateWindowingOverlay();
// Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
if (g.DragDropActive)
@@ -3561,57 +4116,28 @@ void ImGui::EndFrame()
g.DragDropWithinSourceOrTarget = false;
}
- // Initiate moving window
- if (g.ActiveId == 0 && g.HoveredId == 0)
- {
- if (!g.NavWindow || !g.NavWindow->Appearing) // Unless we just made a window/popup appear
- {
- // Click to focus window and start moving (after we're done with all our widgets)
- if (g.IO.MouseClicked[0])
- {
- if (g.HoveredRootWindow != NULL)
- StartMouseMovingWindow(g.HoveredWindow);
- else if (g.NavWindow != NULL && GetFrontMostPopupModal() == NULL)
- FocusWindow(NULL); // Clicking on void disable focus
- }
+ // End frame
+ g.WithinFrameScope = false;
+ g.FrameCountEnded = g.FrameCount;
- // With right mouse button we close popups without changing focus
- // (The left mouse button path calls FocusWindow which will lead NewFrame->ClosePopupsOverWindow to trigger)
- if (g.IO.MouseClicked[1])
- {
- // Find the top-most window between HoveredWindow and the front most Modal Window.
- // This is where we can trim the popup stack.
- ImGuiWindow* modal = GetFrontMostPopupModal();
- bool hovered_window_above_modal = false;
- if (modal == NULL)
- hovered_window_above_modal = true;
- for (int i = g.Windows.Size - 1; i >= 0 && hovered_window_above_modal == false; i--)
- {
- ImGuiWindow* window = g.Windows[i];
- if (window == modal)
- break;
- if (window == g.HoveredWindow)
- hovered_window_above_modal = true;
- }
- ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal);
- }
- }
- }
+ // Initiate moving window + handle left-click and right-click focus
+ UpdateMouseMovingWindowEndFrame();
// Sort the window list so that all child windows are after their parent
// We cannot do that on FocusWindow() because childs may not exist yet
- g.WindowsSortBuffer.resize(0);
- g.WindowsSortBuffer.reserve(g.Windows.Size);
+ g.WindowsTempSortBuffer.resize(0);
+ g.WindowsTempSortBuffer.reserve(g.Windows.Size);
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
continue;
- AddWindowToSortBuffer(&g.WindowsSortBuffer, window);
+ AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
}
- IM_ASSERT(g.Windows.Size == g.WindowsSortBuffer.Size); // we done something wrong
- g.Windows.swap(g.WindowsSortBuffer);
+ // 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.
+ IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
+ g.Windows.swap(g.WindowsTempSortBuffer);
g.IO.MetricsActiveWindows = g.WindowsActiveCount;
// Unlock font atlas
@@ -3619,11 +4145,8 @@ void ImGui::EndFrame()
// Clear Input data for next frame
g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
- memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters));
+ g.IO.InputQueueCharacters.resize(0);
memset(g.IO.NavInputs, 0, sizeof(g.IO.NavInputs));
-
- g.FrameScopeActive = false;
- g.FrameCountEnded = g.FrameCount;
}
void ImGui::Render()
@@ -3632,39 +4155,44 @@ void ImGui::Render()
IM_ASSERT(g.Initialized);
if (g.FrameCountEnded != g.FrameCount)
- ImGui::EndFrame();
+ EndFrame();
g.FrameCountRendered = g.FrameCount;
-
- // Gather ImDrawList to render (for each active window)
- g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = g.IO.MetricsRenderWindows = 0;
+ g.IO.MetricsRenderWindows = 0;
g.DrawDataBuilder.Clear();
- ImGuiWindow* windows_to_render_front_most[2];
- windows_to_render_front_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindow : NULL;
- windows_to_render_front_most[1] = g.NavWindowingTarget ? g.NavWindowingList : NULL;
+
+ // Add background ImDrawList
+ if (!g.BackgroundDrawList.VtxBuffer.empty())
+ AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.BackgroundDrawList);
+
+ // Add ImDrawList to render
+ ImGuiWindow* windows_to_render_top_most[2];
+ windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindow : NULL;
+ windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingList : NULL);
for (int n = 0; n != g.Windows.Size; n++)
{
ImGuiWindow* window = g.Windows[n];
- if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_front_most[0] && window != windows_to_render_front_most[1])
- AddWindowToDrawDataSelectLayer(window);
+ if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
+ AddRootWindowToDrawData(window);
}
- for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_front_most); n++)
- if (windows_to_render_front_most[n] && IsWindowActiveAndVisible(windows_to_render_front_most[n])) // NavWindowingTarget is always temporarily displayed as the front-most window
- AddWindowToDrawDataSelectLayer(windows_to_render_front_most[n]);
+ for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
+ if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
+ AddRootWindowToDrawData(windows_to_render_top_most[n]);
g.DrawDataBuilder.FlattenIntoSingleLayer();
// Draw software mouse cursor if requested
if (g.IO.MouseDrawCursor)
- RenderMouseCursor(&g.OverlayDrawList, g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor);
+ RenderMouseCursor(&g.ForegroundDrawList, g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
- if (!g.OverlayDrawList.VtxBuffer.empty())
- AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.OverlayDrawList);
+ // Add foreground ImDrawList
+ if (!g.ForegroundDrawList.VtxBuffer.empty())
+ AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.ForegroundDrawList);
// Setup ImDrawData structure for end-user
SetupDrawData(&g.DrawDataBuilder.Layers[0], &g.DrawData);
g.IO.MetricsRenderVertices = g.DrawData.TotalVtxCount;
g.IO.MetricsRenderIndices = g.DrawData.TotalIdxCount;
- // Render. If user hasn't set a callback then they may retrieve the draw data via GetDrawData()
+ // (Legacy) Call the Render callback function. The current prefer way is to let the user retrieve GetDrawData() and call the render function themselves.
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
if (g.DrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL)
g.IO.RenderDrawListsFn(&g.DrawData);
@@ -3672,7 +4200,7 @@ void ImGui::Render()
}
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
-// CalcTextSize("") should return ImVec2(0.0f, GImGui->FontSize)
+// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
{
ImGuiContext& g = *GImGui;
@@ -3689,60 +4217,15 @@ ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_tex
return ImVec2(0.0f, font_size);
ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
- // Cancel out character spacing for the last character of a line (it is baked into glyph->AdvanceX field)
- const float font_scale = font_size / font->FontSize;
- const float character_spacing_x = 1.0f * font_scale;
- if (text_size.x > 0.0f)
- text_size.x -= character_spacing_x;
- text_size.x = (float)(int)(text_size.x + 0.95f);
+ // Round
+ text_size.x = IM_FLOOR(text_size.x + 0.95f);
return text_size;
}
-// Helper to calculate coarse clipping of large list of evenly sized items.
-// NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern.
-// NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX
-void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
-{
- ImGuiContext& g = *GImGui;
- ImGuiWindow* window = g.CurrentWindow;
- if (g.LogEnabled)
- {
- // If logging is active, do not perform any clipping
- *out_items_display_start = 0;
- *out_items_display_end = items_count;
- return;
- }
- if (window->SkipItems)
- {
- *out_items_display_start = *out_items_display_end = 0;
- return;
- }
-
- // We create the union of the ClipRect and the NavScoringRect which at worst should be 1 page away from ClipRect
- ImRect unclipped_rect = window->ClipRect;
- if (g.NavMoveRequest)
- unclipped_rect.Add(g.NavScoringRectScreen);
-
- const ImVec2 pos = window->DC.CursorPos;
- int start = (int)((unclipped_rect.Min.y - pos.y) / items_height);
- int end = (int)((unclipped_rect.Max.y - pos.y) / items_height);
-
- // When performing a navigation request, ensure we have one item extra in the direction we are moving to
- if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Up)
- start--;
- if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Down)
- end++;
-
- start = ImClamp(start, 0, items_count);
- end = ImClamp(end + 1, start, items_count);
- *out_items_display_start = start;
- *out_items_display_end = end;
-}
-
// Find window given position, search front-to-back
-// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programatically
-// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
+// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programatically
+// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
// called, aka before the next Begin(). Moving window isn't affected.
static void FindHoveredWindow()
{
@@ -3753,8 +4236,8 @@ static void FindHoveredWindow()
hovered_window = g.MovingWindow;
ImVec2 padding_regular = g.Style.TouchExtraPadding;
- ImVec2 padding_for_resize_from_edges = g.IO.ConfigResizeWindowsFromEdges ? ImMax(g.Style.TouchExtraPadding, ImVec2(RESIZE_WINDOWS_FROM_EDGES_HALF_THICKNESS, RESIZE_WINDOWS_FROM_EDGES_HALF_THICKNESS)) : padding_regular;
- for (int i = g.Windows.Size - 1; i >= 0 && hovered_window == NULL; i--)
+ ImVec2 padding_for_resize_from_edges = g.IO.ConfigWindowsResizeFromEdges ? ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS)) : padding_regular;
+ for (int i = g.Windows.Size - 1; i >= 0; i--)
{
ImGuiWindow* window = g.Windows[i];
if (!window->Active || window->Hidden)
@@ -3764,7 +4247,7 @@ static void FindHoveredWindow()
// Using the clipped AABB, a child window will typically be clipped by its parent (not always)
ImRect bb(window->OuterRectClipped);
- if ((window->Flags & ImGuiWindowFlags_ChildWindow) || (window->Flags & ImGuiWindowFlags_NoResize))
+ if (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize))
bb.Expand(padding_regular);
else
bb.Expand(padding_for_resize_from_edges);
@@ -3805,40 +4288,54 @@ bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool c
int ImGui::GetKeyIndex(ImGuiKey imgui_key)
{
IM_ASSERT(imgui_key >= 0 && imgui_key < ImGuiKey_COUNT);
- return GImGui->IO.KeyMap[imgui_key];
+ ImGuiContext& g = *GImGui;
+ return g.IO.KeyMap[imgui_key];
}
-// Note that imgui doesn't know the semantic of each entry of io.KeysDown[]. Use your own indices/enums according to how your back-end/engine stored them into io.KeysDown[]!
+// Note that dear imgui doesn't know the semantic of each entry of io.KeysDown[]!
+// Use your own indices/enums according to how your back-end/engine stored them into io.KeysDown[]!
bool ImGui::IsKeyDown(int user_key_index)
{
- if (user_key_index < 0) return false;
- IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(GImGui->IO.KeysDown));
- return GImGui->IO.KeysDown[user_key_index];
+ if (user_key_index < 0)
+ return false;
+ ImGuiContext& g = *GImGui;
+ IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
+ return g.IO.KeysDown[user_key_index];
}
-int ImGui::CalcTypematicPressedRepeatAmount(float t, float t_prev, float repeat_delay, float repeat_rate)
+// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
+// t1 = current time (e.g.: g.Time)
+// An event is triggered at:
+// t = 0.0f t = repeat_delay, t = repeat_delay + repeat_rate*N
+int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
{
- if (t == 0.0f)
+ if (t1 == 0.0f)
return 1;
- if (t <= repeat_delay || repeat_rate <= 0.0f)
+ if (t0 >= t1)
return 0;
- const int count = (int)((t - repeat_delay) / repeat_rate) - (int)((t_prev - repeat_delay) / repeat_rate);
- return (count > 0) ? count : 0;
+ if (repeat_rate <= 0.0f)
+ return (t0 < repeat_delay) && (t1 >= repeat_delay);
+ const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
+ const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
+ const int count = count_t1 - count_t0;
+ return count;
}
int ImGui::GetKeyPressedAmount(int key_index, float repeat_delay, float repeat_rate)
{
ImGuiContext& g = *GImGui;
- if (key_index < 0) return false;
+ if (key_index < 0)
+ return 0;
IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown));
const float t = g.IO.KeysDownDuration[key_index];
- return CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, repeat_delay, repeat_rate);
+ return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
}
bool ImGui::IsKeyPressed(int user_key_index, bool repeat)
{
ImGuiContext& g = *GImGui;
- if (user_key_index < 0) return false;
+ if (user_key_index < 0)
+ return false;
IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
const float t = g.IO.KeysDownDuration[user_key_index];
if (t == 0.0f)
@@ -3856,23 +4353,14 @@ bool ImGui::IsKeyReleased(int user_key_index)
return g.IO.KeysDownDurationPrev[user_key_index] >= 0.0f && !g.IO.KeysDown[user_key_index];
}
-bool ImGui::IsMouseDown(int button)
+bool ImGui::IsMouseDown(ImGuiMouseButton button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseDown[button];
}
-bool ImGui::IsAnyMouseDown()
-{
- ImGuiContext& g = *GImGui;
- for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
- if (g.IO.MouseDown[n])
- return true;
- return false;
-}
-
-bool ImGui::IsMouseClicked(int button, bool repeat)
+bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
@@ -3882,76 +4370,99 @@ bool ImGui::IsMouseClicked(int button, bool repeat)
if (repeat && t > g.IO.KeyRepeatDelay)
{
- float delay = g.IO.KeyRepeatDelay, rate = g.IO.KeyRepeatRate;
- if ((ImFmod(t - delay, rate) > rate*0.5f) != (ImFmod(t - delay - g.IO.DeltaTime, rate) > rate*0.5f))
+ // FIXME: 2019/05/03: Our old repeat code was wrong here and led to doubling the repeat rate, which made it an ok rate for repeat on mouse hold.
+ int amount = CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate * 0.50f);
+ if (amount > 0)
return true;
}
-
return false;
}
-bool ImGui::IsMouseReleased(int button)
+bool ImGui::IsMouseReleased(ImGuiMouseButton button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseReleased[button];
}
-bool ImGui::IsMouseDoubleClicked(int button)
+bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseDoubleClicked[button];
}
-bool ImGui::IsMouseDragging(int button, float lock_threshold)
+// [Internal] This doesn't test if the button is pressed
+bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
- if (!g.IO.MouseDown[button])
- return false;
if (lock_threshold < 0.0f)
lock_threshold = g.IO.MouseDragThreshold;
return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
}
+bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
+{
+ ImGuiContext& g = *GImGui;
+ IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
+ if (!g.IO.MouseDown[button])
+ return false;
+ return IsMouseDragPastThreshold(button, lock_threshold);
+}
+
ImVec2 ImGui::GetMousePos()
{
- return GImGui->IO.MousePos;
+ ImGuiContext& g = *GImGui;
+ return g.IO.MousePos;
}
// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
{
ImGuiContext& g = *GImGui;
- if (g.CurrentPopupStack.Size > 0)
- return g.OpenPopupStack[g.CurrentPopupStack.Size-1].OpenMousePos;
+ if (g.BeginPopupStack.Size > 0)
+ return g.OpenPopupStack[g.BeginPopupStack.Size-1].OpenMousePos;
return g.IO.MousePos;
}
-// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position
+// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
{
- if (mouse_pos == NULL)
- mouse_pos = &GImGui->IO.MousePos;
+ // The assert is only to silence a false-positive in XCode Static Analysis.
+ // Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
+ IM_ASSERT(GImGui != NULL);
const float MOUSE_INVALID = -256000.0f;
- return mouse_pos->x >= MOUSE_INVALID && mouse_pos->y >= MOUSE_INVALID;
+ ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
+ return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
+}
+
+bool ImGui::IsAnyMouseDown()
+{
+ ImGuiContext& g = *GImGui;
+ for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
+ if (g.IO.MouseDown[n])
+ return true;
+ return false;
}
+// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
+// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
// NB: This is only valid if IsMousePosValid(). Back-ends in theory should always keep mouse position valid when dragging even outside the client window.
-ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold)
+ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
if (lock_threshold < 0.0f)
lock_threshold = g.IO.MouseDragThreshold;
- if (g.IO.MouseDown[button])
+ if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
- return g.IO.MousePos - g.IO.MouseClickedPos[button]; // Assume we can only get active with left-mouse button (at the moment).
+ if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
+ return g.IO.MousePos - g.IO.MouseClickedPos[button];
return ImVec2(0.0f, 0.0f);
}
-void ImGui::ResetMouseDragDelta(int button)
+void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
@@ -3990,30 +4501,60 @@ bool ImGui::IsItemActive()
return false;
}
+bool ImGui::IsItemActivated()
+{
+ ImGuiContext& g = *GImGui;
+ if (g.ActiveId)
+ {
+ ImGuiWindow* window = g.CurrentWindow;
+ if (g.ActiveId == window->DC.LastItemId && g.ActiveIdPreviousFrame != window->DC.LastItemId)
+ return true;
+ }
+ return false;
+}
+
bool ImGui::IsItemDeactivated()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
+ if (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDeactivated)
+ return (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
return (g.ActiveIdPreviousFrame == window->DC.LastItemId && g.ActiveIdPreviousFrame != 0 && g.ActiveId != window->DC.LastItemId);
}
bool ImGui::IsItemDeactivatedAfterEdit()
{
ImGuiContext& g = *GImGui;
- return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEdited || (g.ActiveId == 0 && g.ActiveIdHasBeenEdited));
+ return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
}
bool ImGui::IsItemFocused()
{
ImGuiContext& g = *GImGui;
- return g.NavId && !g.NavDisableHighlight && g.NavId == g.CurrentWindow->DC.LastItemId;
+ ImGuiWindow* window = g.CurrentWindow;
+
+ if (g.NavId == 0 || g.NavDisableHighlight || g.NavId != window->DC.LastItemId)
+ return false;
+ return true;
}
-bool ImGui::IsItemClicked(int mouse_button)
+bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
{
return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
}
+bool ImGui::IsItemToggledOpen()
+{
+ ImGuiContext& g = *GImGui;
+ return (g.CurrentWindow->DC.LastItemStatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
+}
+
+bool ImGui::IsItemToggledSelection()
+{
+ ImGuiContext& g = *GImGui;
+ return (g.CurrentWindow->DC.LastItemStatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
+}
+
bool ImGui::IsAnyItemHovered()
{
ImGuiContext& g = *GImGui;
@@ -4075,12 +4616,10 @@ ImVec2 ImGui::GetItemRectSize()
static ImRect GetViewportRect()
{
ImGuiContext& g = *GImGui;
- if (g.IO.DisplayVisibleMin.x != g.IO.DisplayVisibleMax.x && g.IO.DisplayVisibleMin.y != g.IO.DisplayVisibleMax.y)
- return ImRect(g.IO.DisplayVisibleMin, g.IO.DisplayVisibleMax);
return ImRect(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y);
}
-static bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags)
+bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* parent_window = g.CurrentWindow;
@@ -4113,7 +4652,12 @@ static bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size
ImGuiWindow* child_window = g.CurrentWindow;
child_window->ChildId = id;
- child_window->AutoFitChildAxises = auto_fit_axises;
+ child_window->AutoFitChildAxises = (ImS8)auto_fit_axises;
+
+ // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
+ // While this is not really documented/defined, it seems that the expected thing to do.
+ if (child_window->BeginCount == 1)
+ parent_window->DC.CursorPos = child_window->Pos;
// Process navigation-in immediately so NavInit can run on first frame
if (g.NavActivateId == id && !(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayerActiveMask != 0 || child_window->DC.NavHasScroll))
@@ -4143,7 +4687,10 @@ void ImGui::EndChild()
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
- IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() callss
+ IM_ASSERT(g.WithinEndChild == false);
+ IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() calls
+
+ g.WithinEndChild = true;
if (window->BeginCount > 1)
{
End();
@@ -4175,6 +4722,7 @@ void ImGui::EndChild()
ItemAdd(bb, 0);
}
}
+ g.WithinEndChild = false;
}
// Helper to create a child window / scrolling region that looks like a normal widget frame.
@@ -4197,22 +4745,6 @@ void ImGui::EndChildFrame()
EndChild();
}
-// Save and compare stack sizes on Begin()/End() to detect usage errors
-static void CheckStacksSize(ImGuiWindow* window, bool write)
-{
- // NOT checking: DC.ItemWidth, DC.AllowKeyboardFocus, DC.ButtonRepeat, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
- ImGuiContext& g = *GImGui;
- int* p_backup = &window->DC.StackSizesBackup[0];
- { int current = window->IDStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushID/PopID or TreeNode/TreePop Mismatch!"); p_backup++; } // Too few or too many PopID()/TreePop()
- { int current = window->DC.GroupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginGroup/EndGroup Mismatch!"); p_backup++; } // Too few or too many EndGroup()
- { int current = g.CurrentPopupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch"); p_backup++;}// Too few or too many EndMenu()/EndPopup()
- // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
- { int current = g.ColorModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup >= current && "PushStyleColor/PopStyleColor Mismatch!"); p_backup++; } // Too few or too many PopStyleColor()
- { int current = g.StyleModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup >= current && "PushStyleVar/PopStyleVar Mismatch!"); p_backup++; } // Too few or too many PopStyleVar()
- { int current = g.FontStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup >= current && "PushFont/PopFont Mismatch!"); p_backup++; } // Too few or too many PopFont()
- IM_ASSERT(p_backup == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup));
-}
-
static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
{
window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags);
@@ -4220,16 +4752,22 @@ static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, b
window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
}
-ImGuiWindow* ImGui::FindWindowByName(const char* name)
+ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
- ImGuiID id = ImHash(name, 0);
return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
}
+ImGuiWindow* ImGui::FindWindowByName(const char* name)
+{
+ ImGuiID id = ImHashStr(name);
+ return FindWindowByID(id);
+}
+
static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
+ //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
// Create window the first time
ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
@@ -4244,15 +4782,15 @@ static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFl
if (ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID))
{
// Retrieve settings from .ini file
- window->SettingsIdx = g.SettingsWindows.index_from_pointer(settings);
+ window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
- window->Pos = ImFloor(settings->Pos);
+ window->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
window->Collapsed = settings->Collapsed;
- if (ImLengthSqr(settings->Size) > 0.00001f)
- size = ImFloor(settings->Size);
+ if (settings->Size.x > 0 && settings->Size.y > 0)
+ size = ImVec2(settings->Size.x, settings->Size.y);
}
- window->Size = window->SizeFull = window->SizeFullAtLastBegin = ImFloor(size);
- window->DC.CursorMaxPos = window->Pos; // So first call to CalcSizeContents() doesn't return crazy values
+ window->Size = window->SizeFull = ImFloor(size);
+ window->DC.CursorStartPos = window->DC.CursorMaxPos = window->Pos; // So first call to CalcContentSize() doesn't return crazy values
if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
{
@@ -4276,10 +4814,10 @@ static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFl
return window;
}
-static ImVec2 CalcSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size)
+static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size)
{
ImGuiContext& g = *GImGui;
- if (g.NextWindowData.SizeConstraintCond != 0)
+ if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
{
// Using -1,-1 on either X/Y axis to preserve the current size.
ImRect cr = g.NextWindowData.SizeConstraintRect;
@@ -4295,47 +4833,64 @@ static ImVec2 CalcSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size)
g.NextWindowData.SizeCallback(&data);
new_size = data.DesiredSize;
}
+ new_size.x = IM_FLOOR(new_size.x);
+ new_size.y = IM_FLOOR(new_size.y);
}
// Minimum size
if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
{
+ ImGuiWindow* window_for_height = window;
new_size = ImMax(new_size, g.Style.WindowMinSize);
- new_size.y = ImMax(new_size.y, window->TitleBarHeight() + window->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows
+ new_size.y = ImMax(new_size.y, window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows
}
return new_size;
}
-static ImVec2 CalcSizeContents(ImGuiWindow* window)
+static ImVec2 CalcWindowContentSize(ImGuiWindow* window)
{
+ if (window->Collapsed)
+ if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
+ return window->ContentSize;
+ if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
+ return window->ContentSize;
+
ImVec2 sz;
- sz.x = (float)(int)((window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : (window->DC.CursorMaxPos.x - window->Pos.x + window->Scroll.x));
- sz.y = (float)(int)((window->SizeContentsExplicit.y != 0.0f) ? window->SizeContentsExplicit.y : (window->DC.CursorMaxPos.y - window->Pos.y + window->Scroll.y));
- return sz + window->WindowPadding;
+ sz.x = IM_FLOOR((window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
+ sz.y = IM_FLOOR((window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
+ return sz;
}
-static ImVec2 CalcSizeAutoFit(ImGuiWindow* window, const ImVec2& size_contents)
+static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
{
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
+ ImVec2 size_decorations = ImVec2(0.0f, window->TitleBarHeight() + window->MenuBarHeight());
+ ImVec2 size_pad = window->WindowPadding * 2.0f;
+ ImVec2 size_desired = size_contents + size_pad + size_decorations;
if (window->Flags & ImGuiWindowFlags_Tooltip)
{
// Tooltip always resize
- return size_contents;
+ return size_desired;
}
else
{
- // When the window cannot fit all contents (either because of constraints, either because screen is too small): we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than DisplaySize-WindowPadding.
+ // Maximum window size is determined by the viewport size or monitor size
const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0;
const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0;
ImVec2 size_min = style.WindowMinSize;
if (is_popup || is_menu) // Popups and menus bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
size_min = ImMin(size_min, ImVec2(4.0f, 4.0f));
- ImVec2 size_auto_fit = ImClamp(size_contents, size_min, ImMax(size_min, g.IO.DisplaySize - style.DisplaySafeAreaPadding * 2.0f));
- ImVec2 size_auto_fit_after_constraint = CalcSizeAfterConstraint(window, size_auto_fit);
- if (size_auto_fit_after_constraint.x < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar))
+ ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, g.IO.DisplaySize - style.DisplaySafeAreaPadding * 2.0f));
+
+ // When the window cannot fit all contents (either because of constraints, either because screen is too small),
+ // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
+ ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
+ bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - size_decorations.x < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
+ bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - size_decorations.y < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
+ if (will_have_scrollbar_x)
size_auto_fit.y += style.ScrollbarSize;
- if (size_auto_fit_after_constraint.y < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar))
+ if (will_have_scrollbar_y)
size_auto_fit.x += style.ScrollbarSize;
return size_auto_fit;
}
@@ -4343,47 +4898,10 @@ static ImVec2 CalcSizeAutoFit(ImGuiWindow* window, const ImVec2& size_contents)
ImVec2 ImGui::CalcWindowExpectedSize(ImGuiWindow* window)
{
- ImVec2 size_contents = CalcSizeContents(window);
- return CalcSizeAfterConstraint(window, CalcSizeAutoFit(window, size_contents));
-}
-
-float ImGui::GetWindowScrollMaxX(ImGuiWindow* window)
-{
- return ImMax(0.0f, window->SizeContents.x - (window->SizeFull.x - window->ScrollbarSizes.x));
-}
-
-float ImGui::GetWindowScrollMaxY(ImGuiWindow* window)
-{
- return ImMax(0.0f, window->SizeContents.y - (window->SizeFull.y - window->ScrollbarSizes.y));
-}
-
-static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges)
-{
- ImGuiContext& g = *GImGui;
- ImVec2 scroll = window->Scroll;
- if (window->ScrollTarget.x < FLT_MAX)
- {
- float cr_x = window->ScrollTargetCenterRatio.x;
- scroll.x = window->ScrollTarget.x - cr_x * (window->SizeFull.x - window->ScrollbarSizes.x);
- }
- if (window->ScrollTarget.y < FLT_MAX)
- {
- // 'snap_on_edges' allows for a discontinuity at the edge of scrolling limits to take account of WindowPadding so that scrolling to make the last item visible scroll far enough to see the padding.
- float cr_y = window->ScrollTargetCenterRatio.y;
- float target_y = window->ScrollTarget.y;
- if (snap_on_edges && cr_y <= 0.0f && target_y <= window->WindowPadding.y)
- target_y = 0.0f;
- if (snap_on_edges && cr_y >= 1.0f && target_y >= window->SizeContents.y - window->WindowPadding.y + g.Style.ItemSpacing.y)
- target_y = window->SizeContents.y;
- scroll.y = target_y - (1.0f - cr_y) * (window->TitleBarHeight() + window->MenuBarHeight()) - cr_y * (window->SizeFull.y - window->ScrollbarSizes.y);
- }
- scroll = ImMax(scroll, ImVec2(0.0f, 0.0f));
- if (!window->Collapsed && !window->SkipItems)
- {
- scroll.x = ImMin(scroll.x, ImGui::GetWindowScrollMaxX(window));
- scroll.y = ImMin(scroll.y, ImGui::GetWindowScrollMaxY(window));
- }
- return scroll;
+ ImVec2 size_contents = CalcWindowContentSize(window);
+ ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents);
+ ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
+ return size_final;
}
static ImGuiCol GetWindowBgColorIdxFromFlags(ImGuiWindowFlags flags)
@@ -4400,7 +4918,7 @@ static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& co
ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left
ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
ImVec2 size_expected = pos_max - pos_min;
- ImVec2 size_constrained = CalcSizeAfterConstraint(window, size_expected);
+ ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
*out_pos = pos_min;
if (corner_norm.x == 0.0f)
out_pos->x -= (size_constrained.x - size_expected.x);
@@ -4411,78 +4929,97 @@ static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& co
struct ImGuiResizeGripDef
{
- ImVec2 CornerPos;
+ ImVec2 CornerPosN;
ImVec2 InnerDir;
int AngleMin12, AngleMax12;
};
-const ImGuiResizeGripDef resize_grip_def[4] =
+static const ImGuiResizeGripDef resize_grip_def[4] =
{
- { ImVec2(1,1), ImVec2(-1,-1), 0, 3 }, // Lower right
- { ImVec2(0,1), ImVec2(+1,-1), 3, 6 }, // Lower left
- { ImVec2(0,0), ImVec2(+1,+1), 6, 9 }, // Upper left
- { ImVec2(1,0), ImVec2(-1,+1), 9,12 }, // Upper right
+ { ImVec2(1,1), ImVec2(-1,-1), 0, 3 }, // Lower-right
+ { ImVec2(0,1), ImVec2(+1,-1), 3, 6 }, // Lower-left
+ { ImVec2(0,0), ImVec2(+1,+1), 6, 9 }, // Upper-left (Unused)
+ { ImVec2(1,0), ImVec2(-1,+1), 9,12 }, // Upper-right (Unused)
};
static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
{
ImRect rect = window->Rect();
if (thickness == 0.0f) rect.Max -= ImVec2(1,1);
- if (border_n == 0) return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness);
- if (border_n == 1) return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding);
- if (border_n == 2) return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness);
- if (border_n == 3) return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding);
+ if (border_n == 0) return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness); // Top
+ if (border_n == 1) return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding); // Right
+ if (border_n == 2) return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness); // Bottom
+ if (border_n == 3) return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding); // Left
IM_ASSERT(0);
return ImRect();
}
+// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
+// 4..7: borders (Top, Right, Bottom, Left)
+ImGuiID ImGui::GetWindowResizeID(ImGuiWindow* window, int n)
+{
+ IM_ASSERT(n >= 0 && n <= 7);
+ ImGuiID id = window->ID;
+ id = ImHashStr("#RESIZE", 0, id);
+ id = ImHashData(&n, sizeof(int), id);
+ return id;
+}
+
// Handle resize for: Resize Grips, Borders, Gamepad
-static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4])
+// Return true when using auto-fit (double click on resize grip)
+static bool ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4])
{
ImGuiContext& g = *GImGui;
ImGuiWindowFlags flags = window->Flags;
+
if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
- return;
- if (window->WasActive == false) // Early out to avoid running this code for e.g. an hidden implicit Debug window.
- return;
+ return false;
+ if (window->WasActive == false) // Early out to avoid running this code for e.g. an hidden implicit/fallback Debug window.
+ return false;
- const int resize_border_count = g.IO.ConfigResizeWindowsFromEdges ? 4 : 0;
- const float grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f);
- const float grip_hover_inner_size = (float)(int)(grip_draw_size * 0.75f);
- const float grip_hover_outer_size = g.IO.ConfigResizeWindowsFromEdges ? RESIZE_WINDOWS_FROM_EDGES_HALF_THICKNESS : 0.0f;
+ bool ret_auto_fit = false;
+ const int resize_border_count = g.IO.ConfigWindowsResizeFromEdges ? 4 : 0;
+ const float grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
+ const float grip_hover_inner_size = IM_FLOOR(grip_draw_size * 0.75f);
+ const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS : 0.0f;
ImVec2 pos_target(FLT_MAX, FLT_MAX);
ImVec2 size_target(FLT_MAX, FLT_MAX);
+ // Resize grips and borders are on layer 1
+ window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
+ window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu);
+
// Manual resize grips
PushID("#RESIZE");
for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
{
const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
- const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPos);
+ const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
// Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
ImRect resize_rect(corner - grip.InnerDir * grip_hover_outer_size, corner + grip.InnerDir * grip_hover_inner_size);
if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
bool hovered, held;
- ButtonBehavior(resize_rect, window->GetID((void*)(intptr_t)resize_grip_n), &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
- //GetOverlayDrawList()->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
+ ButtonBehavior(resize_rect, window->GetID(resize_grip_n), &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
+ //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
if (hovered || held)
g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
if (held && g.IO.MouseDoubleClicked[0] && resize_grip_n == 0)
{
// Manual auto-fit when double-clicking
- size_target = CalcSizeAfterConstraint(window, size_auto_fit);
+ size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
+ ret_auto_fit = true;
ClearActiveID();
}
else if (held)
{
// Resize from any of the four corners
// We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
- ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(grip.InnerDir * grip_hover_outer_size, grip.InnerDir * -grip_hover_inner_size, grip.CornerPos); // Corner of the window corresponding to our corner grip
- CalcResizePosSizeFromAnyCorner(window, corner_target, grip.CornerPos, &pos_target, &size_target);
+ ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(grip.InnerDir * grip_hover_outer_size, grip.InnerDir * -grip_hover_inner_size, grip.CornerPosN); // Corner of the window corresponding to our corner grip
+ CalcResizePosSizeFromAnyCorner(window, corner_target, grip.CornerPosN, &pos_target, &size_target);
}
if (resize_grip_n == 0 || held || hovered)
resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
@@ -4490,27 +5027,32 @@ static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au
for (int border_n = 0; border_n < resize_border_count; border_n++)
{
bool hovered, held;
- ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, RESIZE_WINDOWS_FROM_EDGES_HALF_THICKNESS);
- ButtonBehavior(border_rect, window->GetID((void*)(intptr_t)(border_n + 4)), &hovered, &held, ImGuiButtonFlags_FlattenChildren);
- //GetOverlayDrawList()->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
- if ((hovered && g.HoveredIdTimer > RESIZE_WINDOWS_FROM_EDGES_FEEDBACK_TIMER) || held)
+ ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS);
+ ButtonBehavior(border_rect, window->GetID(border_n + 4), &hovered, &held, ImGuiButtonFlags_FlattenChildren);
+ //GetForegroundDrawLists(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
+ if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held)
{
g.MouseCursor = (border_n & 1) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
- if (held) *border_held = border_n;
+ if (held)
+ *border_held = border_n;
}
if (held)
{
ImVec2 border_target = window->Pos;
ImVec2 border_posn;
- if (border_n == 0) { border_posn = ImVec2(0, 0); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + RESIZE_WINDOWS_FROM_EDGES_HALF_THICKNESS); }
- if (border_n == 1) { border_posn = ImVec2(1, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + RESIZE_WINDOWS_FROM_EDGES_HALF_THICKNESS); }
- if (border_n == 2) { border_posn = ImVec2(0, 1); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + RESIZE_WINDOWS_FROM_EDGES_HALF_THICKNESS); }
- if (border_n == 3) { border_posn = ImVec2(0, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + RESIZE_WINDOWS_FROM_EDGES_HALF_THICKNESS); }
+ if (border_n == 0) { border_posn = ImVec2(0, 0); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Top
+ if (border_n == 1) { border_posn = ImVec2(1, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Right
+ if (border_n == 2) { border_posn = ImVec2(0, 1); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Bottom
+ if (border_n == 3) { border_posn = ImVec2(0, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Left
CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target);
}
}
PopID();
+ // Restore nav layer
+ window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
+ window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
+
// Navigation resize (keyboard/gamepad)
if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindow == window)
{
@@ -4527,7 +5069,7 @@ static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au
g.NavDisableMouseHover = true;
resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
// FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
- size_target = CalcSizeAfterConstraint(window, window->SizeFull + nav_resize_delta);
+ size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + nav_resize_delta);
}
}
@@ -4544,6 +5086,220 @@ static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au
}
window->Size = window->SizeFull;
+ return ret_auto_fit;
+}
+
+static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& rect, const ImVec2& padding)
+{
+ ImGuiContext& g = *GImGui;
+ ImVec2 size_for_clamping = (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) ? ImVec2(window->Size.x, window->TitleBarHeight()) : window->Size;
+ window->Pos = ImMin(rect.Max - padding, ImMax(window->Pos + size_for_clamping, rect.Min + padding) - size_for_clamping);
+}
+
+static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
+{
+ ImGuiContext& g = *GImGui;
+ float rounding = window->WindowRounding;
+ float border_size = window->WindowBorderSize;
+ if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground))
+ window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
+
+ int border_held = window->ResizeBorderHeld;
+ if (border_held != -1)
+ {
+ struct ImGuiResizeBorderDef
+ {
+ ImVec2 InnerDir;
+ ImVec2 CornerPosN1, CornerPosN2;
+ float OuterAngle;
+ };
+ static const ImGuiResizeBorderDef resize_border_def[4] =
+ {
+ { ImVec2(0,+1), ImVec2(0,0), ImVec2(1,0), IM_PI*1.50f }, // Top
+ { ImVec2(-1,0), ImVec2(1,0), ImVec2(1,1), IM_PI*0.00f }, // Right
+ { ImVec2(0,-1), ImVec2(1,1), ImVec2(0,1), IM_PI*0.50f }, // Bottom
+ { ImVec2(+1,0), ImVec2(0,1), ImVec2(0,0), IM_PI*1.00f } // Left
+ };
+ const ImGuiResizeBorderDef& def = resize_border_def[border_held];
+ ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f);
+ window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI*0.25f, def.OuterAngle);
+ window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI*0.25f);
+ window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), false, ImMax(2.0f, border_size)); // Thicker than usual
+ }
+ if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
+ {
+ float y = window->Pos.y + window->TitleBarHeight() - 1;
+ window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), GetColorU32(ImGuiCol_Border), g.Style.FrameBorderSize);
+ }
+}
+
+// Draw background and borders
+// Draw and handle scrollbars
+void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiStyle& style = g.Style;
+ ImGuiWindowFlags flags = window->Flags;
+
+ // Ensure that ScrollBar doesn't read last frame's SkipItems
+ window->SkipItems = false;
+
+ // Draw window + handle manual resize
+ // As we highlight the title bar when want_focus is set, multiple reappearing windows will have have their title bar highlighted on their reappearing frame.
+ const float window_rounding = window->WindowRounding;
+ const float window_border_size = window->WindowBorderSize;
+ if (window->Collapsed)
+ {
+ // Title bar only
+ float backup_border_size = style.FrameBorderSize;
+ g.Style.FrameBorderSize = window->WindowBorderSize;
+ ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
+ RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
+ g.Style.FrameBorderSize = backup_border_size;
+ }
+ else
+ {
+ // Window background
+ if (!(flags & ImGuiWindowFlags_NoBackground))
+ {
+ ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags));
+ bool override_alpha = false;
+ float alpha = 1.0f;
+ if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
+ {
+ alpha = g.NextWindowData.BgAlphaVal;
+ override_alpha = true;
+ }
+ if (override_alpha)
+ bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
+ window->DrawList->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Bot);
+ }
+
+ // Title bar
+ if (!(flags & ImGuiWindowFlags_NoTitleBar))
+ {
+ ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
+ window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawCornerFlags_Top);
+ }
+
+ // Menu bar
+ if (flags & ImGuiWindowFlags_MenuBar)
+ {
+ ImRect menu_bar_rect = window->MenuBarRect();
+ menu_bar_rect.ClipWith(window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
+ window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawCornerFlags_Top);
+ if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
+ window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
+ }
+
+ // Scrollbars
+ if (window->ScrollbarX)
+ Scrollbar(ImGuiAxis_X);
+ if (window->ScrollbarY)
+ Scrollbar(ImGuiAxis_Y);
+
+ // Render resize grips (after their input handling so we don't have a frame of latency)
+ if (!(flags & ImGuiWindowFlags_NoResize))
+ {
+ for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
+ {
+ const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
+ const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
+ window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
+ window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
+ window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
+ window->DrawList->PathFillConvex(resize_grip_col[resize_grip_n]);
+ }
+ }
+
+ // Borders
+ RenderWindowOuterBorders(window);
+ }
+}
+
+// Render title text, collapse button, close button
+void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiStyle& style = g.Style;
+ ImGuiWindowFlags flags = window->Flags;
+
+ const bool has_close_button = (p_open != NULL);
+ const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
+
+ // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
+ const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags;
+ window->DC.ItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
+ window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
+ window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu);
+
+ // Layout buttons
+ // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
+ float pad_l = style.FramePadding.x;
+ float pad_r = style.FramePadding.x;
+ float button_sz = g.FontSize;
+ ImVec2 close_button_pos;
+ ImVec2 collapse_button_pos;
+ if (has_close_button)
+ {
+ pad_r += button_sz;
+ close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
+ }
+ if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
+ {
+ pad_r += button_sz;
+ collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
+ }
+ if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
+ {
+ collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l - style.FramePadding.x, title_bar_rect.Min.y);
+ pad_l += button_sz;
+ }
+
+ // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
+ if (has_collapse_button)
+ if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos))
+ window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
+
+ // Close button
+ if (has_close_button)
+ if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
+ *p_open = false;
+
+ window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
+ window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
+ window->DC.ItemFlags = item_flags_backup;
+
+ // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
+ // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
+ const char* UNSAVED_DOCUMENT_MARKER = "*";
+ const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? CalcTextSize(UNSAVED_DOCUMENT_MARKER, NULL, false).x : 0.0f;
+ const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
+
+ // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
+ // while uncentered title text will still reach edges correct.
+ if (pad_l > style.FramePadding.x)
+ pad_l += g.Style.ItemInnerSpacing.x;
+ if (pad_r > style.FramePadding.x)
+ pad_r += g.Style.ItemInnerSpacing.x;
+ if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
+ {
+ float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
+ float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
+ pad_l = ImMax(pad_l, pad_extend * centerness);
+ pad_r = ImMax(pad_r, pad_extend * centerness);
+ }
+
+ ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);
+ ImRect clip_r(layout_r.Min.x, layout_r.Min.y, layout_r.Max.x + g.Style.ItemInnerSpacing.x, layout_r.Max.y);
+ //if (g.IO.KeyCtrl) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
+ RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
+ if (flags & ImGuiWindowFlags_UnsavedDocument)
+ {
+ ImVec2 marker_pos = ImVec2(ImMax(layout_r.Min.x, layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x) + text_size.x, layout_r.Min.y) + ImVec2(2 - marker_size_x, 0.0f);
+ ImVec2 off = ImVec2(0.0f, IM_FLOOR(-g.FontSize * 0.25f));
+ RenderTextClipped(marker_pos + off, layout_r.Max + off, UNSAVED_DOCUMENT_MARKER, NULL, NULL, ImVec2(0, style.WindowTitleAlign.y), &clip_r);
+ }
}
void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
@@ -4555,10 +5311,13 @@ void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags
if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)))
window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
+ {
+ IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
+ }
}
-// Push a new ImGui window to add widgets to.
+// Push a new Dear ImGui window to add widgets to.
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
// - Begin/End can be called multiple times during the frame with the same window name to append content.
// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
@@ -4569,8 +5328,8 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
- IM_ASSERT(name != NULL); // Window name required
- IM_ASSERT(g.FrameScopeActive); // Forgot to call ImGui::NewFrame()
+ IM_ASSERT(name != NULL && name[0] != '\0'); // Window name required
+ IM_ASSERT(g.WithinFrameScope); // Forgot to call ImGui::NewFrame()
IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
// Find or create
@@ -4578,7 +5337,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
const bool window_just_created = (window == NULL);
if (window_just_created)
{
- ImVec2 size_on_first_use = (g.NextWindowData.SizeCond != 0) ? g.NextWindowData.SizeVal : ImVec2(0.0f, 0.0f); // Any condition flag will do since we are creating a new window here.
+ ImVec2 size_on_first_use = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) ? g.NextWindowData.SizeVal : ImVec2(0.0f, 0.0f); // Any condition flag will do since we are creating a new window here.
window = CreateNewWindow(name, size_on_first_use, flags);
}
@@ -4591,23 +5350,14 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
const int current_frame = g.FrameCount;
const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
- if (first_begin_of_the_frame)
- window->Flags = (ImGuiWindowFlags)flags;
- else
- flags = window->Flags;
-
- // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
- ImGuiWindow* parent_window_in_stack = g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back();
- ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
- IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
- window->HasCloseButton = (p_open != NULL);
+ window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
// Update the Appearing flag
bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
- const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesForResize > 0);
+ const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
if (flags & ImGuiWindowFlags_Popup)
{
- ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.CurrentPopupStack.Size];
+ ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
window_just_activated_by_user |= (window != popup_ref.Window);
}
@@ -4615,25 +5365,53 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
if (window->Appearing)
SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
+ // Update Flags, LastFrameActive, BeginOrderXXX fields
+ if (first_begin_of_the_frame)
+ {
+ window->Flags = (ImGuiWindowFlags)flags;
+ window->LastFrameActive = current_frame;
+ window->LastTimeActive = (float)g.Time;
+ window->BeginOrderWithinParent = 0;
+ window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
+ }
+ else
+ {
+ flags = window->Flags;
+ }
+
+ // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
+ ImGuiWindow* parent_window_in_stack = g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back();
+ ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
+ IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
+
+ // We allow window memory to be compacted so recreate the base stack when needed.
+ if (window->IDStack.Size == 0)
+ window->IDStack.push_back(window->ID);
+
// Add to stack
+ // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
g.CurrentWindowStack.push_back(window);
- SetCurrentWindow(window);
- CheckStacksSize(window, true);
+ g.CurrentWindow = NULL;
+ ErrorCheckBeginEndCompareStacksSize(window, true);
if (flags & ImGuiWindowFlags_Popup)
{
- ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.CurrentPopupStack.Size];
+ ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
popup_ref.Window = window;
- g.CurrentPopupStack.push_back(popup_ref);
+ g.BeginPopupStack.push_back(popup_ref);
window->PopupId = popup_ref.PopupId;
}
if (window_just_appearing_after_hidden_for_resize && !(flags & ImGuiWindowFlags_ChildWindow))
window->NavLastIds[0] = 0;
+ // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
+ if (first_begin_of_the_frame)
+ UpdateWindowParentAndRootLinks(window, flags, parent_window);
+
// Process SetNextWindow***() calls
bool window_pos_set_by_api = false;
bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
- if (g.NextWindowData.PosCond)
+ if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
{
window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
@@ -4649,26 +5427,19 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
}
}
- if (g.NextWindowData.SizeCond)
+ if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
{
window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
}
- if (g.NextWindowData.ContentSizeCond)
- {
- // Adjust passed "client size" to become a "window size"
- window->SizeContentsExplicit = g.NextWindowData.ContentSizeVal;
- if (window->SizeContentsExplicit.y != 0.0f)
- window->SizeContentsExplicit.y += window->TitleBarHeight() + window->MenuBarHeight();
- }
+ if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
+ window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
else if (first_begin_of_the_frame)
- {
- window->SizeContentsExplicit = ImVec2(0.0f, 0.0f);
- }
- if (g.NextWindowData.CollapsedCond)
+ window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
+ if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
- if (g.NextWindowData.FocusCond)
+ if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
FocusWindow(window);
if (window->Appearing)
SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
@@ -4678,53 +5449,68 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
{
// Initialize
const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
- UpdateWindowParentAndRootLinks(window, flags, parent_window);
-
window->Active = true;
- window->BeginOrderWithinParent = 0;
- window->BeginOrderWithinContext = g.WindowsActiveCount++;
- window->BeginCount = 0;
+ window->HasCloseButton = (p_open != NULL);
window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX);
- window->LastFrameActive = current_frame;
window->IDStack.resize(1);
+ // Restore buffer capacity when woken from a compacted state, to avoid
+ if (window->MemoryCompacted)
+ GcAwakeTransientWindowBuffers(window);
+
+ // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
+ // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
+ bool window_title_visible_elsewhere = false;
+ if (g.NavWindowingList != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB
+ window_title_visible_elsewhere = true;
+ if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
+ {
+ size_t buf_len = (size_t)window->NameBufLen;
+ window->Name = ImStrdupcpy(window->Name, &buf_len, name);
+ window->NameBufLen = (int)buf_len;
+ }
+
// UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
// Update contents size from last frame for auto-fitting (or use explicit size)
- window->SizeContents = CalcSizeContents(window);
- if (window->HiddenFramesRegular > 0)
- window->HiddenFramesRegular--;
- if (window->HiddenFramesForResize > 0)
- window->HiddenFramesForResize--;
+ window->ContentSize = CalcWindowContentSize(window);
+ if (window->HiddenFramesCanSkipItems > 0)
+ window->HiddenFramesCanSkipItems--;
+ if (window->HiddenFramesCannotSkipItems > 0)
+ window->HiddenFramesCannotSkipItems--;
// Hide new windows for one frame until they calculate their size
if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
- window->HiddenFramesForResize = 1;
+ window->HiddenFramesCannotSkipItems = 1;
// Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
- // We reset Size/SizeContents for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
+ // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
{
- window->HiddenFramesForResize = 1;
+ window->HiddenFramesCannotSkipItems = 1;
if (flags & ImGuiWindowFlags_AlwaysAutoResize)
{
if (!window_size_x_set_by_api)
window->Size.x = window->SizeFull.x = 0.f;
if (!window_size_y_set_by_api)
window->Size.y = window->SizeFull.y = 0.f;
- window->SizeContents = ImVec2(0.f, 0.f);
+ window->ContentSize = ImVec2(0.f, 0.f);
}
}
+ // SELECT VIEWPORT
+ // FIXME-VIEWPORT: In the docking/viewport branch, this is the point where we select the current viewport (which may affect the style)
SetCurrentWindow(window);
- // Lock border size and padding for the frame (so that altering them doesn't cause inconsistencies)
- window->WindowBorderSize = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildBorderSize : ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
+ // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
+
+ if (flags & ImGuiWindowFlags_ChildWindow)
+ window->WindowBorderSize = style.ChildBorderSize;
+ else
+ window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
window->WindowPadding = style.WindowPadding;
if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)
window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
- window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
- window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
// Collapse window by double-clicking on title bar
// At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
@@ -4750,46 +5536,47 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
// SIZE
// Calculate auto-fit size, handle automatic resize
- const ImVec2 size_auto_fit = CalcSizeAutoFit(window, window->SizeContents);
- ImVec2 size_full_modified(FLT_MAX, FLT_MAX);
+ const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSize);
+ bool use_current_size_for_scrollbar_x = window_just_created;
+ bool use_current_size_for_scrollbar_y = window_just_created;
if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
{
// Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
if (!window_size_x_set_by_api)
- window->SizeFull.x = size_full_modified.x = size_auto_fit.x;
+ {
+ window->SizeFull.x = size_auto_fit.x;
+ use_current_size_for_scrollbar_x = true;
+ }
if (!window_size_y_set_by_api)
- window->SizeFull.y = size_full_modified.y = size_auto_fit.y;
+ {
+ window->SizeFull.y = size_auto_fit.y;
+ use_current_size_for_scrollbar_y = true;
+ }
}
else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
{
// Auto-fit may only grow window during the first few frames
// We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
- window->SizeFull.x = size_full_modified.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
+ {
+ window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
+ use_current_size_for_scrollbar_x = true;
+ }
if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
- window->SizeFull.y = size_full_modified.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
+ {
+ window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
+ use_current_size_for_scrollbar_y = true;
+ }
if (!window->Collapsed)
MarkIniSettingsDirty(window);
}
// Apply minimum/maximum window size constraints and final size
- window->SizeFull = CalcSizeAfterConstraint(window, window->SizeFull);
+ window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
- // SCROLLBAR STATUS
-
- // Update scrollbar status (based on the Size that was effective during last frame or the auto-resized Size).
- if (!window->Collapsed)
- {
- // When reading the current size we need to read it after size constraints have been applied
- float size_x_for_scrollbars = size_full_modified.x != FLT_MAX ? window->SizeFull.x : window->SizeFullAtLastBegin.x;
- float size_y_for_scrollbars = size_full_modified.y != FLT_MAX ? window->SizeFull.y : window->SizeFullAtLastBegin.y;
- window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((window->SizeContents.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
- window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((window->SizeContents.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
- if (window->ScrollbarX && !window->ScrollbarY)
- window->ScrollbarY = (window->SizeContents.y > size_y_for_scrollbars - style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar);
- window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
- }
+ // Decoration size
+ const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
// POSITION
@@ -4798,21 +5585,22 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
{
window->AutoPosLastDirection = ImGuiDir_None;
if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api)
- window->Pos = g.CurrentPopupStack.back().OpenPopupPos;
+ window->Pos = g.BeginPopupStack.back().OpenPopupPos;
}
// Position child window
if (flags & ImGuiWindowFlags_ChildWindow)
{
- window->BeginOrderWithinParent = parent_window->DC.ChildWindows.Size;
+ IM_ASSERT(parent_window && parent_window->Active);
+ window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
parent_window->DC.ChildWindows.push_back(window);
if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
window->Pos = parent_window->DC.CursorPos;
}
- const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesForResize == 0);
+ const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
if (window_pos_with_pivot)
- SetWindowPos(window, ImMax(style.DisplaySafeAreaPadding, window->SetWindowPosVal - window->SizeFull * window->SetWindowPosPivot), 0); // Position given a pivot (e.g. for centering)
+ SetWindowPos(window, window->SetWindowPosVal - window->SizeFull * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
window->Pos = FindBestWindowPosForPopup(window);
else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
@@ -4820,14 +5608,15 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
window->Pos = FindBestWindowPosForPopup(window);
- // Clamp position so it stays visible
- if (!(flags & ImGuiWindowFlags_ChildWindow))
+ // Clamp position/size so window stays visible within its viewport or monitor
+ // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
+ ImRect viewport_rect(GetViewportRect());
+ if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
{
- if (!window_pos_set_by_api && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && g.IO.DisplaySize.x > 0.0f && g.IO.DisplaySize.y > 0.0f) // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
+ ImVec2 clamp_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
+ if (viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
{
- ImVec2 padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
- window->Pos = ImMax(window->Pos + window->Size, padding) - window->Size;
- window->Pos = ImMin(window->Pos, g.IO.DisplaySize - padding);
+ ClampWindowRect(window, viewport_rect, clamp_padding);
}
}
window->Pos = ImFloor(window->Pos);
@@ -4835,50 +5624,113 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
// Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
- // Prepare for item focus requests
- window->FocusIdxAllRequestCurrent = (window->FocusIdxAllRequestNext == INT_MAX || window->FocusIdxAllCounter == -1) ? INT_MAX : (window->FocusIdxAllRequestNext + (window->FocusIdxAllCounter+1)) % (window->FocusIdxAllCounter+1);
- window->FocusIdxTabRequestCurrent = (window->FocusIdxTabRequestNext == INT_MAX || window->FocusIdxTabCounter == -1) ? INT_MAX : (window->FocusIdxTabRequestNext + (window->FocusIdxTabCounter+1)) % (window->FocusIdxTabCounter+1);
- window->FocusIdxAllCounter = window->FocusIdxTabCounter = -1;
- window->FocusIdxAllRequestNext = window->FocusIdxTabRequestNext = INT_MAX;
-
- // Apply scrolling
- window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window, true);
- window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
-
// Apply window focus (new and reactivated windows are moved to front)
bool want_focus = false;
if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
- if (!(flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) || (flags & ImGuiWindowFlags_Popup))
+ {
+ if (flags & ImGuiWindowFlags_Popup)
+ want_focus = true;
+ else if ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) == 0)
want_focus = true;
+ }
// Handle manual resize: Resize Grips, Borders, Gamepad
int border_held = -1;
- ImU32 resize_grip_col[4] = { 0 };
- const int resize_grip_count = g.IO.ConfigResizeWindowsFromEdges ? 2 : 1; // 4
- const float grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f);
+ ImU32 resize_grip_col[4] = {};
+ const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
+ const float resize_grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
if (!window->Collapsed)
- UpdateManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0]);
+ if (UpdateManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0]))
+ use_current_size_for_scrollbar_x = use_current_size_for_scrollbar_y = true;
+ window->ResizeBorderHeld = (signed char)border_held;
+
+ // SCROLLBAR VISIBILITY
+
+ // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
+ if (!window->Collapsed)
+ {
+ // When reading the current size we need to read it after size constraints have been applied.
+ // When we use InnerRect here we are intentionally reading last frame size, same for ScrollbarSizes values before we set them again.
+ ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - decoration_up_height);
+ ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + window->ScrollbarSizes;
+ ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
+ float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
+ float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
+ //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
+ window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
+ window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
+ if (window->ScrollbarX && !window->ScrollbarY)
+ window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar);
+ window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
+ }
+
+ // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
+ // Update various regions. Variables they depends on should be set above in this function.
+ // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
+
+ // Outer rectangle
+ // Not affected by window border size. Used by:
+ // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
+ // - Begin() initial clipping rect for drawing window background and borders.
+ // - Begin() clipping whole child
+ const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
+ const ImRect outer_rect = window->Rect();
+ const ImRect title_bar_rect = window->TitleBarRect();
+ window->OuterRectClipped = outer_rect;
+ window->OuterRectClipped.ClipWith(host_rect);
+
+ // Inner rectangle
+ // Not affected by window border size. Used by:
+ // - InnerClipRect
+ // - ScrollToBringRectIntoView()
+ // - NavUpdatePageUpPageDown()
+ // - Scrollbar()
+ window->InnerRect.Min.x = window->Pos.x;
+ window->InnerRect.Min.y = window->Pos.y + decoration_up_height;
+ window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->ScrollbarSizes.x;
+ window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->ScrollbarSizes.y;
+
+ // Inner clipping rectangle.
+ // Will extend a little bit outside the normal work region.
+ // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
+ // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
+ // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
+ // Affected by window/frame border size. Used by:
+ // - Begin() initial clip rect
+ float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
+ window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
+ window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
+ window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
+ window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
+ window->InnerClipRect.ClipWithFull(host_rect);
// Default item width. Make it proportional to window size if window manually resizes
if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
- window->ItemWidthDefault = (float)(int)(window->Size.x * 0.65f);
+ window->ItemWidthDefault = ImFloor(window->Size.x * 0.65f);
else
- window->ItemWidthDefault = (float)(int)(g.FontSize * 16.0f);
+ window->ItemWidthDefault = ImFloor(g.FontSize * 16.0f);
+
+ // SCROLLING
+
+ // Lock down maximum scrolling
+ // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
+ // for right/bottom aligned items without creating a scrollbar.
+ window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
+ window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
+
+ // Apply scrolling
+ window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window, true);
+ window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
// DRAWING
// Setup draw list and outer clipping rectangle
window->DrawList->Clear();
- window->DrawList->Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0);
window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
- ImRect viewport_rect(GetViewportRect());
- if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
- PushClipRect(parent_window->ClipRect.Min, parent_window->ClipRect.Max, true);
- else
- PushClipRect(viewport_rect.Min, viewport_rect.Max, true);
+ PushClipRect(host_rect.Min, host_rect.Max, false);
// Draw modal window background (darkens what is behind them, all viewports)
- const bool dim_bg_for_modal = (flags & ImGuiWindowFlags_Modal) && window == GetFrontMostPopupModal() && window->HiddenFramesForResize <= 0;
+ const bool dim_bg_for_modal = (flags & ImGuiWindowFlags_Modal) && window == GetTopMostPopupModal() && window->HiddenFramesCannotSkipItems <= 0;
const bool dim_bg_for_window_list = g.NavWindowingTargetAnim && (window == g.NavWindowingTargetAnim->RootWindow);
if (dim_bg_for_modal || dim_bg_for_window_list)
{
@@ -4895,78 +5747,26 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha * 0.25f), g.Style.WindowRounding);
}
- // Draw window + handle manual resize
- const float window_rounding = window->WindowRounding;
- const float window_border_size = window->WindowBorderSize;
- const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
- const bool title_bar_is_highlight = want_focus || (window_to_highlight && window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight);
- const ImRect title_bar_rect = window->TitleBarRect();
- if (window->Collapsed)
+ // Since 1.71, child window can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call.
+ // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
+ // We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping child.
+ // We also disabled this when we have dimming overlay behind this specific one child.
+ // FIXME: More code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected.
{
- // Title bar only
- float backup_border_size = style.FrameBorderSize;
- g.Style.FrameBorderSize = window->WindowBorderSize;
- ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
- RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
- g.Style.FrameBorderSize = backup_border_size;
- }
- else
- {
- // Window background
- if (!(flags & ImGuiWindowFlags_NoBackground))
- {
- ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags));
- if (g.NextWindowData.BgAlphaCond != 0)
- bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(g.NextWindowData.BgAlphaVal) << IM_COL32_A_SHIFT);
- window->DrawList->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Bot);
- }
- g.NextWindowData.BgAlphaCond = 0;
-
- // Title bar
- ImU32 title_bar_col = GetColorU32(window->Collapsed ? ImGuiCol_TitleBgCollapsed : title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
- if (!(flags & ImGuiWindowFlags_NoTitleBar))
- window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawCornerFlags_Top);
-
- // Menu bar
- if (flags & ImGuiWindowFlags_MenuBar)
- {
- ImRect menu_bar_rect = window->MenuBarRect();
- menu_bar_rect.ClipWith(window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
- window->DrawList->AddRectFilled(menu_bar_rect.Min, menu_bar_rect.Max, GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawCornerFlags_Top);
- if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
- window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
- }
-
- // Scrollbars
- if (window->ScrollbarX)
- Scrollbar(ImGuiLayoutType_Horizontal);
- if (window->ScrollbarY)
- Scrollbar(ImGuiLayoutType_Vertical);
-
- // Render resize grips (after their input handling so we don't have a frame of latency)
- if (!(flags & ImGuiWindowFlags_NoResize))
- {
- for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
- {
- const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
- const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPos);
- window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, grip_draw_size) : ImVec2(grip_draw_size, window_border_size)));
- window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(grip_draw_size, window_border_size) : ImVec2(window_border_size, grip_draw_size)));
- window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
- window->DrawList->PathFillConvex(resize_grip_col[resize_grip_n]);
- }
- }
-
- // Borders
- if (window_border_size > 0.0f && !(flags & ImGuiWindowFlags_NoBackground))
- window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), window_rounding, ImDrawCornerFlags_All, window_border_size);
- if (border_held != -1)
- {
- ImRect border = GetResizeBorderRect(window, border_held, grip_draw_size, 0.0f);
- window->DrawList->AddLine(border.Min, border.Max, GetColorU32(ImGuiCol_SeparatorActive), ImMax(1.0f, window_border_size));
- }
- if (style.FrameBorderSize > 0 && !(flags & ImGuiWindowFlags_NoTitleBar))
- window->DrawList->AddLine(title_bar_rect.GetBL() + ImVec2(style.WindowBorderSize, -1), title_bar_rect.GetBR() + ImVec2(-style.WindowBorderSize, -1), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
+ bool render_decorations_in_parent = false;
+ if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
+ if (window->DrawList->CmdBuffer.back().ElemCount == 0 && parent_window->DrawList->VtxBuffer.Size > 0)
+ render_decorations_in_parent = true;
+ if (render_decorations_in_parent)
+ window->DrawList = parent_window->DrawList;
+
+ // Handle title bar, scrollbar, resize grips and resize borders
+ const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
+ const bool title_bar_is_highlight = want_focus || (window_to_highlight && window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight);
+ RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, resize_grip_count, resize_grip_col, resize_grip_draw_size);
+
+ if (render_decorations_in_parent)
+ window->DrawList = &window->DrawListInst;
}
// Draw navigation selection/windowing rectangle border
@@ -4983,48 +5783,71 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), rounding, ~0, 3.0f);
}
- // Store a backup of SizeFull which we will use next frame to decide if we need scrollbars.
- window->SizeFullAtLastBegin = window->SizeFull;
-
- // Update various regions. Variables they depends on are set above in this function.
- // FIXME: window->ContentsRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
- window->ContentsRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x;
- window->ContentsRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->TitleBarHeight() + window->MenuBarHeight();
- window->ContentsRegionRect.Max.x = window->Pos.x - window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x));
- window->ContentsRegionRect.Max.y = window->Pos.y - window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y));
+ // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
+
+ // Work rectangle.
+ // Affected by window padding and border size. Used by:
+ // - Columns() for right-most edge
+ // - TreeNode(), CollapsingHeader() for right-most edge
+ // - BeginTabBar() for right-most edge
+ const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
+ const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
+ const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - window->ScrollbarSizes.x));
+ const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - decoration_up_height - window->ScrollbarSizes.y));
+ window->WorkRect.Min.x = ImFloor(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
+ window->WorkRect.Min.y = ImFloor(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
+ window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
+ window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
+
+ // [LEGACY] Content Region
+ // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
+ // Used by:
+ // - Mouse wheel scrolling + many other things
+ window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x;
+ window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + decoration_up_height;
+ window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - window->ScrollbarSizes.x));
+ window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - decoration_up_height - window->ScrollbarSizes.y));
// Setup drawing context
// (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
window->DC.Indent.x = 0.0f + window->WindowPadding.x - window->Scroll.x;
window->DC.GroupOffset.x = 0.0f;
window->DC.ColumnsOffset.x = 0.0f;
- window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.Indent.x + window->DC.ColumnsOffset.x, window->TitleBarHeight() + window->MenuBarHeight() + window->WindowPadding.y - window->Scroll.y);
+ window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.Indent.x + window->DC.ColumnsOffset.x, decoration_up_height + window->WindowPadding.y - window->Scroll.y);
window->DC.CursorPos = window->DC.CursorStartPos;
window->DC.CursorPosPrevLine = window->DC.CursorPos;
window->DC.CursorMaxPos = window->DC.CursorStartPos;
- window->DC.CurrentLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
- window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
- window->DC.NavHideHighlightOneFrame = false;
- window->DC.NavHasScroll = (GetScrollMaxY() > 0.0f);
+ window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
+ window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
+
+ window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
+ window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
window->DC.NavLayerActiveMask = window->DC.NavLayerActiveMaskNext;
window->DC.NavLayerActiveMaskNext = 0x00;
+ window->DC.NavFocusScopeIdCurrent = 0;
+ window->DC.NavHideHighlightOneFrame = false;
+ window->DC.NavHasScroll = (window->ScrollMax.y > 0.0f);
+
window->DC.MenuBarAppending = false;
- window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f;
+ window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
+ window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
+ window->DC.MenuColumns.Update(3, style.ItemSpacing.x, window_just_activated_by_user);
+ window->DC.TreeDepth = 0;
+ window->DC.TreeJumpToParentOnPopMask = 0x00;
window->DC.ChildWindows.resize(0);
+ window->DC.StateStorage = &window->StateStorage;
+ window->DC.CurrentColumns = NULL;
window->DC.LayoutType = ImGuiLayoutType_Vertical;
window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
+ window->DC.FocusCounterRegular = window->DC.FocusCounterTabStop = -1;
+
window->DC.ItemFlags = parent_window ? parent_window->DC.ItemFlags : ImGuiItemFlags_Default_;
window->DC.ItemWidth = window->ItemWidthDefault;
window->DC.TextWrapPos = -1.0f; // disabled
window->DC.ItemFlagsStack.resize(0);
window->DC.ItemWidthStack.resize(0);
window->DC.TextWrapPosStack.resize(0);
- window->DC.ColumnsSet = NULL;
- window->DC.TreeDepth = 0;
- window->DC.TreeDepthMayJumpToParentOnPop = 0x00;
- window->DC.StateStorage = &window->StateStorage;
window->DC.GroupStack.resize(0);
- window->MenuColumns.Update(3, style.ItemSpacing.x, window_just_activated_by_user);
if ((flags & ImGuiWindowFlags_ChildWindow) && (window->DC.ItemFlags != parent_window->DC.ItemFlags))
{
@@ -5046,48 +5869,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
// Title bar
if (!(flags & ImGuiWindowFlags_NoTitleBar))
- {
- // Close & collapse button are on layer 1 (same as menus) and don't default focus
- const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags;
- window->DC.ItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
- window->DC.NavLayerCurrent++;
- window->DC.NavLayerCurrentMask <<= 1;
-
- // Collapse button
- if (!(flags & ImGuiWindowFlags_NoCollapse))
- if (CollapseButton(window->GetID("#COLLAPSE"), window->Pos))
- window->WantCollapseToggle = true; // Defer collapsing to next frame as we are too far in the Begin() function
-
- // Close button
- if (p_open != NULL)
- {
- const float pad = style.FramePadding.y;
- const float rad = g.FontSize * 0.5f;
- if (CloseButton(window->GetID("#CLOSE"), window->Rect().GetTR() + ImVec2(-pad - rad, pad + rad), rad + 1))
- *p_open = false;
- }
-
- window->DC.NavLayerCurrent--;
- window->DC.NavLayerCurrentMask >>= 1;
- window->DC.ItemFlags = item_flags_backup;
-
- // Title text (FIXME: refactor text alignment facilities along with RenderText helpers, this is too much code for what it does.)
- ImVec2 text_size = CalcTextSize(name, NULL, true);
- ImRect text_r = title_bar_rect;
- float pad_left = (flags & ImGuiWindowFlags_NoCollapse) ? style.FramePadding.x : (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x);
- float pad_right = (p_open == NULL) ? style.FramePadding.x : (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x);
- if (style.WindowTitleAlign.x > 0.0f)
- pad_right = ImLerp(pad_right, pad_left, style.WindowTitleAlign.x);
- text_r.Min.x += pad_left;
- text_r.Max.x -= pad_right;
- ImRect clip_rect = text_r;
- clip_rect.Max.x = window->Pos.x + window->Size.x - (p_open ? title_bar_rect.GetHeight() - 3 : style.FramePadding.x); // Match the size of CloseButton()
- RenderTextClipped(text_r.Min, text_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_rect);
- }
-
- // Save clipped aabb so we can access it in constant-time in FindHoveredWindow()
- window->OuterRectClipped = window->Rect();
- window->OuterRectClipped.ClipWith(window->ClipRect);
+ RenderWindowTitleBarContents(window, title_bar_rect, name, p_open);
// Pressing CTRL+C while holding on a window copy its content to the clipboard
// This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
@@ -5095,29 +5877,23 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
/*
if (g.ActiveId == move_id)
if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C))
- ImGui::LogToClipboard();
+ LogToClipboard();
*/
- // Inner rectangle
- // We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame
- // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
- window->InnerMainRect.Min.x = title_bar_rect.Min.x + window->WindowBorderSize;
- window->InnerMainRect.Min.y = title_bar_rect.Max.y + window->MenuBarHeight() + (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
- window->InnerMainRect.Max.x = window->Pos.x + window->Size.x - window->ScrollbarSizes.x - window->WindowBorderSize;
- window->InnerMainRect.Max.y = window->Pos.y + window->Size.y - window->ScrollbarSizes.y - window->WindowBorderSize;
- //window->DrawList->AddRect(window->InnerRect.Min, window->InnerRect.Max, IM_COL32_WHITE);
-
- // Inner clipping rectangle
- // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
- window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerMainRect.Min.x + ImMax(0.0f, ImFloor(window->WindowPadding.x*0.5f - window->WindowBorderSize)));
- window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerMainRect.Min.y);
- window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerMainRect.Max.x - ImMax(0.0f, ImFloor(window->WindowPadding.x*0.5f - window->WindowBorderSize)));
- window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerMainRect.Max.y);
-
- // After Begin() we fill the last item / hovered data based on title bar data. It is a standard behavior (to allow creation of context menus on title bar only, etc.).
+ // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
+ // This is useful to allow creating context menus on title bar only, etc.
window->DC.LastItemId = window->MoveId;
window->DC.LastItemStatusFlags = IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0;
window->DC.LastItemRect = title_bar_rect;
+#ifdef IMGUI_ENABLE_TEST_ENGINE
+ if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
+ IMGUI_TEST_ENGINE_ITEM_ADD(window->DC.LastItemRect, window->DC.LastItemId);
+#endif
+ }
+ else
+ {
+ // Append
+ SetCurrentWindow(window);
}
PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
@@ -5127,58 +5903,60 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
window->WriteAccessed = false;
window->BeginCount++;
- g.NextWindowData.Clear();
+ g.NextWindowData.ClearFlags();
if (flags & ImGuiWindowFlags_ChildWindow)
{
// Child window can be out of sight and have "negative" clip windows.
// Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0);
-
if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
- window->HiddenFramesRegular = 1;
+ window->HiddenFramesCanSkipItems = 1;
- // Completely hide along with parent or if parent is collapsed
- if (parent_window && (parent_window->Collapsed || parent_window->Hidden))
- window->HiddenFramesRegular = 1;
+ // Hide along with parent or if parent is collapsed
+ if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
+ window->HiddenFramesCanSkipItems = 1;
+ if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
+ window->HiddenFramesCannotSkipItems = 1;
}
// Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
if (style.Alpha <= 0.0f)
- window->HiddenFramesRegular = 1;
+ window->HiddenFramesCanSkipItems = 1;
// Update the Hidden flag
- window->Hidden = (window->HiddenFramesRegular > 0) || (window->HiddenFramesForResize);
+ window->Hidden = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
- // Return false if we don't intend to display anything to allow user to perform an early out optimization
- window->SkipItems = (window->Collapsed || !window->Active || window->Hidden) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesForResize <= 0;
+ // Update the SkipItems flag, used to early out of all items functions (no layout required)
+ bool skip_items = false;
+ if (window->Collapsed || !window->Active || window->Hidden)
+ if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
+ skip_items = true;
+ window->SkipItems = skip_items;
- return !window->SkipItems;
+ return !skip_items;
}
-// Old Begin() API with 5 parameters, avoid calling this version directly! Use SetNextWindowSize()/SetNextWindowBgAlpha() + Begin() instead.
-#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
-bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_first_use, float bg_alpha_override, ImGuiWindowFlags flags)
-{
- // Old API feature: we could pass the initial window size as a parameter. This was misleading because it only had an effect if the window didn't have data in the .ini file.
- if (size_first_use.x != 0.0f || size_first_use.y != 0.0f)
- ImGui::SetNextWindowSize(size_first_use, ImGuiCond_FirstUseEver);
-
- // Old API feature: override the window background alpha with a parameter.
- if (bg_alpha_override >= 0.0f)
- ImGui::SetNextWindowBgAlpha(bg_alpha_override);
-
- return ImGui::Begin(name, p_open, flags);
-}
-#endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS
-
void ImGui::End()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
- if (window->DC.ColumnsSet != NULL)
+ // Error checking: verify that user hasn't called End() too many times!
+ if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
+ {
+ IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
+ return;
+ }
+ IM_ASSERT(g.CurrentWindowStack.Size > 0);
+
+ // Error checking: verify that user doesn't directly call End() on a child window.
+ if (window->Flags & ImGuiWindowFlags_ChildWindow)
+ IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
+
+ // Close anything that is open
+ if (window->DC.CurrentColumns)
EndColumns();
PopClipRect(); // Inner window clip rectangle
@@ -5189,8 +5967,8 @@ void ImGui::End()
// Pop from window stack
g.CurrentWindowStack.pop_back();
if (window->Flags & ImGuiWindowFlags_Popup)
- g.CurrentPopupStack.pop_back();
- CheckStacksSize(window, false);
+ g.BeginPopupStack.pop_back();
+ ErrorCheckBeginEndCompareStacksSize(window, false);
SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back());
}
@@ -5199,7 +5977,7 @@ void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
ImGuiContext& g = *GImGui;
if (g.WindowsFocusOrder.back() == window)
return;
- for (int i = g.WindowsFocusOrder.Size - 2; i >= 0; i--) // We can ignore the front most window
+ for (int i = g.WindowsFocusOrder.Size - 2; i >= 0; i--) // We can ignore the top-most window
if (g.WindowsFocusOrder[i] == window)
{
memmove(&g.WindowsFocusOrder[i], &g.WindowsFocusOrder[i + 1], (size_t)(g.WindowsFocusOrder.Size - i - 1) * sizeof(ImGuiWindow*));
@@ -5214,7 +5992,7 @@ void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
ImGuiWindow* current_front_window = g.Windows.back();
if (current_front_window == window || current_front_window->RootWindow == window)
return;
- for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the front most window
+ for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
if (g.Windows[i] == window)
{
memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
@@ -5249,64 +6027,89 @@ void ImGui::FocusWindow(ImGuiWindow* window)
g.NavMousePosDirty = true;
g.NavInitRequest = false;
g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
+ g.NavFocusScopeId = 0;
g.NavIdIsAlive = false;
- g.NavLayer = 0;
- //printf("[%05d] FocusWindow(\"%s\")\n", g.FrameCount, window ? window->Name : NULL);
+ g.NavLayer = ImGuiNavLayer_Main;
+ //IMGUI_DEBUG_LOG("FocusWindow(\"%s\")\n", window ? window->Name : NULL);
}
+ // Close popups if any
+ ClosePopupsOverWindow(window, false);
+
// Passing NULL allow to disable keyboard focus
if (!window)
return;
// Move the root window to the top of the pile
- if (window->RootWindow)
- window = window->RootWindow;
+ IM_ASSERT(window->RootWindow != NULL);
+ ImGuiWindow* focus_front_window = window->RootWindow; // NB: In docking branch this is window->RootWindowDockStop
+ ImGuiWindow* display_front_window = window->RootWindow;
// Steal focus on active widgets
- if (window->Flags & ImGuiWindowFlags_Popup) // FIXME: This statement should be unnecessary. Need further testing before removing it..
- if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != window)
+ if (focus_front_window->Flags & ImGuiWindowFlags_Popup) // FIXME: This statement may be unnecessary? Need further testing before removing it..
+ if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
ClearActiveID();
// Bring to front
- BringWindowToFocusFront(window);
- if (!(window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus))
- BringWindowToDisplayFront(window);
+ BringWindowToFocusFront(focus_front_window);
+ if (((window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
+ BringWindowToDisplayFront(display_front_window);
}
-void ImGui::FocusPreviousWindowIgnoringOne(ImGuiWindow* ignore_window)
+void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window)
{
ImGuiContext& g = *GImGui;
- for (int i = g.WindowsFocusOrder.Size - 1; i >= 0; i--)
+
+ int start_idx = g.WindowsFocusOrder.Size - 1;
+ if (under_this_window != NULL)
{
+ int under_this_window_idx = FindWindowFocusIndex(under_this_window);
+ if (under_this_window_idx != -1)
+ start_idx = under_this_window_idx - 1;
+ }
+ for (int i = start_idx; i >= 0; i--)
+ {
+ // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
ImGuiWindow* window = g.WindowsFocusOrder[i];
if (window != ignore_window && window->WasActive && !(window->Flags & ImGuiWindowFlags_ChildWindow))
- {
- ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(window);
- FocusWindow(focus_window);
- return;
- }
+ if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
+ {
+ ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(window);
+ FocusWindow(focus_window);
+ return;
+ }
}
+ FocusWindow(NULL);
+}
+
+void ImGui::SetNextItemWidth(float item_width)
+{
+ ImGuiContext& g = *GImGui;
+ g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
+ g.NextItemData.Width = item_width;
}
void ImGui::PushItemWidth(float item_width)
{
- ImGuiWindow* window = GetCurrentWindow();
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
window->DC.ItemWidthStack.push_back(window->DC.ItemWidth);
+ g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
}
void ImGui::PushMultiItemsWidths(int components, float w_full)
{
- ImGuiWindow* window = GetCurrentWindow();
- const ImGuiStyle& style = GImGui->Style;
- if (w_full <= 0.0f)
- w_full = CalcItemWidth();
- const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components));
- const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1)));
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ const ImGuiStyle& style = g.Style;
+ const float w_item_one = ImMax(1.0f, IM_FLOOR((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components));
+ const float w_item_last = ImMax(1.0f, IM_FLOOR(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1)));
window->DC.ItemWidthStack.push_back(w_item_last);
for (int i = 0; i < components-1; i++)
window->DC.ItemWidthStack.push_back(w_item_one);
window->DC.ItemWidth = window->DC.ItemWidthStack.back();
+ g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
}
void ImGui::PopItemWidth()
@@ -5316,27 +6119,58 @@ void ImGui::PopItemWidth()
window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back();
}
+// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
+// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
float ImGui::CalcItemWidth()
{
- ImGuiWindow* window = GetCurrentWindowRead();
- float w = window->DC.ItemWidth;
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ float w;
+ if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
+ w = g.NextItemData.Width;
+ else
+ w = window->DC.ItemWidth;
if (w < 0.0f)
{
- // Align to a right-side limit. We include 1 frame padding in the calculation because this is how the width is always used (we add 2 frame padding to it), but we could move that responsibility to the widget as well.
- float width_to_right_edge = GetContentRegionAvail().x;
- w = ImMax(1.0f, width_to_right_edge + w);
+ float region_max_x = GetContentRegionMaxAbs().x;
+ w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
}
- w = (float)(int)w;
+ w = IM_FLOOR(w);
return w;
}
+// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
+// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
+// Note that only CalcItemWidth() is publicly exposed.
+// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
+ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
+{
+ ImGuiWindow* window = GImGui->CurrentWindow;
+
+ ImVec2 region_max;
+ if (size.x < 0.0f || size.y < 0.0f)
+ region_max = GetContentRegionMaxAbs();
+
+ if (size.x == 0.0f)
+ size.x = default_w;
+ else if (size.x < 0.0f)
+ size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
+
+ if (size.y == 0.0f)
+ size.y = default_h;
+ else if (size.y < 0.0f)
+ size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
+
+ return size;
+}
+
void ImGui::SetCurrentFont(ImFont* font)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
IM_ASSERT(font->Scale > 0.0f);
g.Font = font;
- g.FontBaseSize = g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale;
+ g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
ImFontAtlas* atlas = g.Font->ContainerAtlas;
@@ -5458,27 +6292,29 @@ struct ImGuiStyleVarInfo
static const ImGuiStyleVarInfo GStyleVarInfo[] =
{
- { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
- { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
- { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
- { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
- { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
- { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
- { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
- { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
- { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
- { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
- { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
- { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
- { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
- { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
- { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
- { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
- { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
- { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
- { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
- { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
- { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
+ { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
+ { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
+ { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
+ { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
+ { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
+ { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding
+ { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
+ { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
};
static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx)
@@ -5499,7 +6335,7 @@ void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
*pvar = val;
return;
}
- IM_ASSERT(0); // Called function with wrong-type? Variable is not a float.
+ IM_ASSERT(0 && "Called PushStyleVar() float variant but variable is not a float!");
}
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
@@ -5513,7 +6349,7 @@ void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
*pvar = val;
return;
}
- IM_ASSERT(0); // Called function with wrong-type? Variable is not a ImVec2.
+ IM_ASSERT(0 && "Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!");
}
void ImGui::PopStyleVar(int count)
@@ -5570,6 +6406,11 @@ const char* ImGui::GetStyleColorName(ImGuiCol idx)
case ImGuiCol_ResizeGrip: return "ResizeGrip";
case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
+ case ImGuiCol_Tab: return "Tab";
+ case ImGuiCol_TabHovered: return "TabHovered";
+ case ImGuiCol_TabActive: return "TabActive";
+ case ImGuiCol_TabUnfocused: return "TabUnfocused";
+ case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
case ImGuiCol_PlotLines: return "PlotLines";
case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
case ImGuiCol_PlotHistogram: return "PlotHistogram";
@@ -5631,7 +6472,7 @@ bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
}
}
- if (!IsWindowContentHoverable(g.HoveredRootWindow, flags))
+ if (!IsWindowContentHoverable(g.HoveredWindow, flags))
return false;
if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != g.HoveredWindow->MoveId)
@@ -5642,11 +6483,11 @@ bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
{
ImGuiContext& g = *GImGui;
- IM_ASSERT(g.CurrentWindow); // Not inside a Begin()/End()
if (flags & ImGuiFocusedFlags_AnyWindow)
return g.NavWindow != NULL;
+ IM_ASSERT(g.CurrentWindow); // Not inside a Begin()/End()
switch (flags & (ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows))
{
case ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows:
@@ -5661,6 +6502,8 @@ bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
}
// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
+// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmaticaly.
+// If you want a window to never be focused, you may use the e.g. NoInputs flag.
bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
{
return window->Active && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
@@ -5685,21 +6528,7 @@ ImVec2 ImGui::GetWindowPos()
return window->Pos;
}
-void ImGui::SetWindowScrollX(ImGuiWindow* window, float new_scroll_x)
-{
- window->DC.CursorMaxPos.x += window->Scroll.x; // SizeContents is generally computed based on CursorMaxPos which is affected by scroll position, so we need to apply our change to it.
- window->Scroll.x = new_scroll_x;
- window->DC.CursorMaxPos.x -= window->Scroll.x;
-}
-
-void ImGui::SetWindowScrollY(ImGuiWindow* window, float new_scroll_y)
-{
- window->DC.CursorMaxPos.y += window->Scroll.y; // SizeContents is generally computed based on CursorMaxPos which is affected by scroll position, so we need to apply our change to it.
- window->Scroll.y = new_scroll_y;
- window->DC.CursorMaxPos.y -= window->Scroll.y;
-}
-
-static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
+void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
@@ -5712,8 +6541,10 @@ static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
// Set
const ImVec2 old_pos = window->Pos;
window->Pos = ImFloor(pos);
- window->DC.CursorPos += (window->Pos - old_pos); // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
- window->DC.CursorMaxPos += (window->Pos - old_pos); // And more importantly we need to adjust this so size calculation doesn't get affected.
+ ImVec2 offset = window->Pos - old_pos;
+ window->DC.CursorPos += offset; // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
+ window->DC.CursorMaxPos += offset; // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
+ window->DC.CursorStartPos += offset;
}
void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
@@ -5734,7 +6565,7 @@ ImVec2 ImGui::GetWindowSize()
return window->Size;
}
-static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
+void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
@@ -5747,7 +6578,7 @@ static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond con
if (size.x > 0.0f)
{
window->AutoFitFramesX = 0;
- window->SizeFull.x = ImFloor(size.x);
+ window->SizeFull.x = IM_FLOOR(size.x);
}
else
{
@@ -5757,7 +6588,7 @@ static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond con
if (size.y > 0.0f)
{
window->AutoFitFramesY = 0;
- window->SizeFull.y = ImFloor(size.y);
+ window->SizeFull.y = IM_FLOOR(size.y);
}
else
{
@@ -5777,7 +6608,7 @@ void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
SetWindowSize(window, size, cond);
}
-static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
+void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
@@ -5833,6 +6664,7 @@ void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pi
{
ImGuiContext& g = *GImGui;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
+ g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
g.NextWindowData.PosVal = pos;
g.NextWindowData.PosPivotVal = pivot;
g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
@@ -5842,6 +6674,7 @@ void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
+ g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
g.NextWindowData.SizeVal = size;
g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
}
@@ -5849,23 +6682,26 @@ void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
{
ImGuiContext& g = *GImGui;
- g.NextWindowData.SizeConstraintCond = ImGuiCond_Always;
+ g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
g.NextWindowData.SizeCallback = custom_callback;
g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
}
+// Content size = inner scrollable rectangle, padded with WindowPadding.
+// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
void ImGui::SetNextWindowContentSize(const ImVec2& size)
{
ImGuiContext& g = *GImGui;
- g.NextWindowData.ContentSizeVal = size; // In Begin() we will add the size of window decorations (title bar, menu etc.) to that to form a SizeContents value.
- g.NextWindowData.ContentSizeCond = ImGuiCond_Always;
+ g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
+ g.NextWindowData.ContentSizeVal = size;
}
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
+ g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
g.NextWindowData.CollapsedVal = collapsed;
g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
}
@@ -5873,54 +6709,61 @@ void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
void ImGui::SetNextWindowFocus()
{
ImGuiContext& g = *GImGui;
- g.NextWindowData.FocusCond = ImGuiCond_Always; // Using a Cond member for consistency (may transition all of them to single flag set for fast Clear() op)
+ g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
}
void ImGui::SetNextWindowBgAlpha(float alpha)
{
ImGuiContext& g = *GImGui;
+ g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
g.NextWindowData.BgAlphaVal = alpha;
- g.NextWindowData.BgAlphaCond = ImGuiCond_Always; // Using a Cond member for consistency (may transition all of them to single flag set for fast Clear() op)
}
-// In window space (not screen space!)
+// FIXME: This is in window space (not screen space!). We should try to obsolete all those functions.
ImVec2 ImGui::GetContentRegionMax()
{
- ImGuiWindow* window = GetCurrentWindowRead();
- ImVec2 mx = window->ContentsRegionRect.Max - window->Pos;
- if (window->DC.ColumnsSet)
- mx.x = GetColumnOffset(window->DC.ColumnsSet->Current + 1) - window->WindowPadding.x;
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ ImVec2 mx = window->ContentRegionRect.Max - window->Pos;
+ if (window->DC.CurrentColumns)
+ mx.x = window->WorkRect.Max.x - window->Pos.x;
return mx;
}
-ImVec2 ImGui::GetContentRegionAvail()
+// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
+ImVec2 ImGui::GetContentRegionMaxAbs()
{
- ImGuiWindow* window = GetCurrentWindowRead();
- return GetContentRegionMax() - (window->DC.CursorPos - window->Pos);
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ ImVec2 mx = window->ContentRegionRect.Max;
+ if (window->DC.CurrentColumns)
+ mx.x = window->WorkRect.Max.x;
+ return mx;
}
-float ImGui::GetContentRegionAvailWidth()
+ImVec2 ImGui::GetContentRegionAvail()
{
- return GetContentRegionAvail().x;
+ ImGuiWindow* window = GImGui->CurrentWindow;
+ return GetContentRegionMaxAbs() - window->DC.CursorPos;
}
// In window space (not screen space!)
ImVec2 ImGui::GetWindowContentRegionMin()
{
- ImGuiWindow* window = GetCurrentWindowRead();
- return window->ContentsRegionRect.Min - window->Pos;
+ ImGuiWindow* window = GImGui->CurrentWindow;
+ return window->ContentRegionRect.Min - window->Pos;
}
ImVec2 ImGui::GetWindowContentRegionMax()
{
- ImGuiWindow* window = GetCurrentWindowRead();
- return window->ContentsRegionRect.Max - window->Pos;
+ ImGuiWindow* window = GImGui->CurrentWindow;
+ return window->ContentRegionRect.Max - window->Pos;
}
float ImGui::GetWindowContentRegionWidth()
{
- ImGuiWindow* window = GetCurrentWindowRead();
- return window->ContentsRegionRect.GetWidth();
+ ImGuiWindow* window = GImGui->CurrentWindow;
+ return window->ContentRegionRect.GetWidth();
}
float ImGui::GetTextLineHeight()
@@ -6029,77 +6872,43 @@ ImVec2 ImGui::GetCursorScreenPos()
return window->DC.CursorPos;
}
-void ImGui::SetCursorScreenPos(const ImVec2& screen_pos)
+void ImGui::SetCursorScreenPos(const ImVec2& pos)
{
ImGuiWindow* window = GetCurrentWindow();
- window->DC.CursorPos = screen_pos;
+ window->DC.CursorPos = pos;
window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
}
-float ImGui::GetScrollX()
-{
- return GImGui->CurrentWindow->Scroll.x;
-}
-
-float ImGui::GetScrollY()
-{
- return GImGui->CurrentWindow->Scroll.y;
-}
-
-float ImGui::GetScrollMaxX()
-{
- return GetWindowScrollMaxX(GImGui->CurrentWindow);
-}
-
-float ImGui::GetScrollMaxY()
-{
- return GetWindowScrollMaxY(GImGui->CurrentWindow);
-}
-
-void ImGui::SetScrollX(float scroll_x)
-{
- ImGuiWindow* window = GetCurrentWindow();
- window->ScrollTarget.x = scroll_x;
- window->ScrollTargetCenterRatio.x = 0.0f;
-}
-
-void ImGui::SetScrollY(float scroll_y)
-{
- ImGuiWindow* window = GetCurrentWindow();
- window->ScrollTarget.y = scroll_y + window->TitleBarHeight() + window->MenuBarHeight(); // title bar height canceled out when using ScrollTargetRelY
- window->ScrollTargetCenterRatio.y = 0.0f;
-}
-
-void ImGui::SetScrollFromPosY(float pos_y, float center_y_ratio)
+void ImGui::ActivateItem(ImGuiID id)
{
- // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size
- ImGuiWindow* window = GetCurrentWindow();
- IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
- window->ScrollTarget.y = (float)(int)(pos_y + window->Scroll.y);
- window->ScrollTargetCenterRatio.y = center_y_ratio;
+ ImGuiContext& g = *GImGui;
+ g.NavNextActivateId = id;
}
-// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
-void ImGui::SetScrollHereY(float center_y_ratio)
+void ImGui::PushFocusScope(ImGuiID id)
{
- ImGuiWindow* window = GetCurrentWindow();
- float target_y = window->DC.CursorPosPrevLine.y - window->Pos.y; // Top of last item, in window space
- target_y += (window->DC.PrevLineSize.y * center_y_ratio) + (GImGui->Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line.
- SetScrollFromPosY(target_y, center_y_ratio);
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ window->IDStack.push_back(window->DC.NavFocusScopeIdCurrent);
+ window->DC.NavFocusScopeIdCurrent = id;
}
-void ImGui::ActivateItem(ImGuiID id)
+void ImGui::PopFocusScope()
{
ImGuiContext& g = *GImGui;
- g.NavNextActivateId = id;
+ ImGuiWindow* window = g.CurrentWindow;
+ window->DC.NavFocusScopeIdCurrent = window->IDStack.back();
+ window->IDStack.pop_back();
}
void ImGui::SetKeyboardFocusHere(int offset)
{
IM_ASSERT(offset >= -1); // -1 is allowed but not below
- ImGuiWindow* window = GetCurrentWindow();
- window->FocusIdxAllRequestNext = window->FocusIdxAllCounter + 1 + offset;
- window->FocusIdxTabRequestNext = INT_MAX;
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ g.FocusRequestNextWindow = window;
+ g.FocusRequestNextCounterRegular = window->DC.FocusCounterRegular + 1 + offset;
+ g.FocusRequestNextCounterTabStop = INT_MAX;
}
void ImGui::SetItemDefaultFocus()
@@ -6121,71 +6930,80 @@ void ImGui::SetItemDefaultFocus()
void ImGui::SetStateStorage(ImGuiStorage* tree)
{
- ImGuiWindow* window = GetCurrentWindow();
+ ImGuiWindow* window = GImGui->CurrentWindow;
window->DC.StateStorage = tree ? tree : &window->StateStorage;
}
ImGuiStorage* ImGui::GetStateStorage()
{
- ImGuiWindow* window = GetCurrentWindowRead();
+ ImGuiWindow* window = GImGui->CurrentWindow;
return window->DC.StateStorage;
}
void ImGui::PushID(const char* str_id)
{
- ImGuiWindow* window = GetCurrentWindowRead();
+ ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.push_back(window->GetIDNoKeepAlive(str_id));
}
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
{
- ImGuiWindow* window = GetCurrentWindowRead();
+ ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.push_back(window->GetIDNoKeepAlive(str_id_begin, str_id_end));
}
void ImGui::PushID(const void* ptr_id)
{
- ImGuiWindow* window = GetCurrentWindowRead();
+ ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.push_back(window->GetIDNoKeepAlive(ptr_id));
}
void ImGui::PushID(int int_id)
{
- const void* ptr_id = (void*)(intptr_t)int_id;
- ImGuiWindow* window = GetCurrentWindowRead();
- window->IDStack.push_back(window->GetIDNoKeepAlive(ptr_id));
+ ImGuiWindow* window = GImGui->CurrentWindow;
+ window->IDStack.push_back(window->GetIDNoKeepAlive(int_id));
+}
+
+// Push a given id value ignoring the ID stack as a seed.
+void ImGui::PushOverrideID(ImGuiID id)
+{
+ ImGuiWindow* window = GImGui->CurrentWindow;
+ window->IDStack.push_back(id);
}
void ImGui::PopID()
{
- ImGuiWindow* window = GetCurrentWindowRead();
+ ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.pop_back();
}
ImGuiID ImGui::GetID(const char* str_id)
{
- return GImGui->CurrentWindow->GetID(str_id);
+ ImGuiWindow* window = GImGui->CurrentWindow;
+ return window->GetID(str_id);
}
ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
{
- return GImGui->CurrentWindow->GetID(str_id_begin, str_id_end);
+ ImGuiWindow* window = GImGui->CurrentWindow;
+ return window->GetID(str_id_begin, str_id_end);
}
ImGuiID ImGui::GetID(const void* ptr_id)
{
- return GImGui->CurrentWindow->GetID(ptr_id);
+ ImGuiWindow* window = GImGui->CurrentWindow;
+ return window->GetID(ptr_id);
}
bool ImGui::IsRectVisible(const ImVec2& size)
{
- ImGuiWindow* window = GetCurrentWindowRead();
+ ImGuiWindow* window = GImGui->CurrentWindow;
return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
}
bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
{
- ImGuiWindow* window = GetCurrentWindowRead();
+ ImGuiWindow* window = GImGui->CurrentWindow;
return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
}
@@ -6201,76 +7019,90 @@ void ImGui::BeginGroup()
group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
group_data.BackupIndent = window->DC.Indent;
group_data.BackupGroupOffset = window->DC.GroupOffset;
- group_data.BackupCurrentLineSize = window->DC.CurrentLineSize;
- group_data.BackupCurrentLineTextBaseOffset = window->DC.CurrentLineTextBaseOffset;
- group_data.BackupLogLinePosY = window->DC.LogLinePosY;
+ group_data.BackupCurrLineSize = window->DC.CurrLineSize;
+ group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
- group_data.AdvanceCursor = true;
+ group_data.EmitItem = true;
window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
window->DC.Indent = window->DC.GroupOffset;
window->DC.CursorMaxPos = window->DC.CursorPos;
- window->DC.CurrentLineSize = ImVec2(0.0f, 0.0f);
- window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; // To enforce Log carriage return
+ window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
+ if (g.LogEnabled)
+ g.LogLinePosY = -FLT_MAX; // To enforce Log carriage return
}
void ImGui::EndGroup()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
- IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls
+ IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls
ImGuiGroupData& group_data = window->DC.GroupStack.back();
- ImRect group_bb(group_data.BackupCursorPos, window->DC.CursorMaxPos);
- group_bb.Max = ImMax(group_bb.Min, group_bb.Max);
+ ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
window->DC.CursorPos = group_data.BackupCursorPos;
window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
window->DC.Indent = group_data.BackupIndent;
window->DC.GroupOffset = group_data.BackupGroupOffset;
- window->DC.CurrentLineSize = group_data.BackupCurrentLineSize;
- window->DC.CurrentLineTextBaseOffset = group_data.BackupCurrentLineTextBaseOffset;
- window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; // To enforce Log carriage return
+ window->DC.CurrLineSize = group_data.BackupCurrLineSize;
+ window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
+ if (g.LogEnabled)
+ g.LogLinePosY = -FLT_MAX; // To enforce Log carriage return
- if (group_data.AdvanceCursor)
+ if (!group_data.EmitItem)
{
- window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrentLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
- ItemSize(group_bb.GetSize(), group_data.BackupCurrentLineTextBaseOffset);
- ItemAdd(group_bb, 0);
+ window->DC.GroupStack.pop_back();
+ return;
}
+ window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
+ ItemSize(group_bb.GetSize());
+ ItemAdd(group_bb, 0);
+
// If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
// It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
- // (and if you grep for LastItemId you'll notice it is only used in that context.
- if ((group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId) // && g.ActiveIdWindow->RootWindow == window->RootWindow)
+ // Also if you grep for LastItemId you'll notice it is only used in that context.
+ // (The tests not symmetrical because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
+ const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
+ const bool group_contains_prev_active_id = !group_data.BackupActiveIdPreviousFrameIsAlive && g.ActiveIdPreviousFrameIsAlive;
+ if (group_contains_curr_active_id)
window->DC.LastItemId = g.ActiveId;
- else if (!group_data.BackupActiveIdPreviousFrameIsAlive && g.ActiveIdPreviousFrameIsAlive) // && g.ActiveIdPreviousFrameWindow->RootWindow == window->RootWindow)
+ else if (group_contains_prev_active_id)
window->DC.LastItemId = g.ActiveIdPreviousFrame;
window->DC.LastItemRect = group_bb;
- window->DC.GroupStack.pop_back();
+ // Forward Edited flag
+ if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
+ window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Edited;
+ // Forward Deactivated flag
+ window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
+ if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
+ window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Deactivated;
+
+ window->DC.GroupStack.pop_back();
//window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug]
}
// Gets back to previous line and continue with horizontal layout
-// pos_x == 0 : follow right after previous item
-// pos_x != 0 : align to specified x position (relative to window/group left)
-// spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0
-// spacing_w >= 0 : enforce spacing amount
-void ImGui::SameLine(float pos_x, float spacing_w)
+// offset_from_start_x == 0 : follow right after previous item
+// offset_from_start_x != 0 : align to specified x position (relative to window/group left)
+// spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0
+// spacing_w >= 0 : enforce spacing amount
+void ImGui::SameLine(float offset_from_start_x, float spacing_w)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
- if (pos_x != 0.0f)
+ if (offset_from_start_x != 0.0f)
{
if (spacing_w < 0.0f) spacing_w = 0.0f;
- window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + pos_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
+ window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
}
else
@@ -6279,8 +7111,8 @@ void ImGui::SameLine(float pos_x, float spacing_w)
window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
}
- window->DC.CurrentLineSize = window->DC.PrevLineSize;
- window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
+ window->DC.CurrLineSize = window->DC.PrevLineSize;
+ window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
}
void ImGui::Indent(float indent_w)
@@ -6299,13 +7131,239 @@ void ImGui::Unindent(float indent_w)
window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
}
+
+//-----------------------------------------------------------------------------
+// [SECTION] ERROR CHECKING
+//-----------------------------------------------------------------------------
+
+static void ImGui::ErrorCheckEndFrame()
+{
+ // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
+ // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
+ ImGuiContext& g = *GImGui;
+ if (g.CurrentWindowStack.Size != 1)
+ {
+ if (g.CurrentWindowStack.Size > 1)
+ {
+ IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
+ while (g.CurrentWindowStack.Size > 1)
+ End();
+ }
+ else
+ {
+ IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
+ }
+ }
+
+}
+
+// Save and compare stack sizes on Begin()/End() to detect usage errors
+// Begin() calls this with write=true
+// End() calls this with write=false
+static void ImGui::ErrorCheckBeginEndCompareStacksSize(ImGuiWindow* window, bool write)
+{
+ ImGuiContext& g = *GImGui;
+ short* p = &window->DC.StackSizesBackup[0];
+
+ // Window stacks
+ // NOT checking: DC.ItemWidth, DC.AllowKeyboardFocus, DC.ButtonRepeat, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
+ { int n = window->IDStack.Size; if (write) *p = (short)n; else IM_ASSERT(*p == n && "PushID/PopID or TreeNode/TreePop Mismatch!"); p++; } // Too few or too many PopID()/TreePop()
+ { int n = window->DC.GroupStack.Size; if (write) *p = (short)n; else IM_ASSERT(*p == n && "BeginGroup/EndGroup Mismatch!"); p++; } // Too few or too many EndGroup()
+
+ // Global stacks
+ // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
+ { int n = g.BeginPopupStack.Size; if (write) *p = (short)n; else IM_ASSERT(*p == n && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch!"); p++; }// Too few or too many EndMenu()/EndPopup()
+ { int n = g.ColorModifiers.Size; if (write) *p = (short)n; else IM_ASSERT(*p >= n && "PushStyleColor/PopStyleColor Mismatch!"); p++; } // Too few or too many PopStyleColor()
+ { int n = g.StyleModifiers.Size; if (write) *p = (short)n; else IM_ASSERT(*p >= n && "PushStyleVar/PopStyleVar Mismatch!"); p++; } // Too few or too many PopStyleVar()
+ { int n = g.FontStack.Size; if (write) *p = (short)n; else IM_ASSERT(*p >= n && "PushFont/PopFont Mismatch!"); p++; } // Too few or too many PopFont()
+ IM_ASSERT(p == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup));
+}
+
+
+//-----------------------------------------------------------------------------
+// [SECTION] SCROLLING
+//-----------------------------------------------------------------------------
+
+static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges)
+{
+ ImGuiContext& g = *GImGui;
+ ImVec2 scroll = window->Scroll;
+ if (window->ScrollTarget.x < FLT_MAX)
+ {
+ float cr_x = window->ScrollTargetCenterRatio.x;
+ float target_x = window->ScrollTarget.x;
+ if (snap_on_edges && cr_x <= 0.0f && target_x <= window->WindowPadding.x)
+ target_x = 0.0f;
+ else if (snap_on_edges && cr_x >= 1.0f && target_x >= window->ContentSize.x + window->WindowPadding.x + g.Style.ItemSpacing.x)
+ target_x = window->ContentSize.x + window->WindowPadding.x * 2.0f;
+ scroll.x = target_x - cr_x * (window->SizeFull.x - window->ScrollbarSizes.x);
+ }
+ if (window->ScrollTarget.y < FLT_MAX)
+ {
+ // 'snap_on_edges' allows for a discontinuity at the edge of scrolling limits to take account of WindowPadding so that scrolling to make the last item visible scroll far enough to see the padding.
+ float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
+ float cr_y = window->ScrollTargetCenterRatio.y;
+ float target_y = window->ScrollTarget.y;
+ if (snap_on_edges && cr_y <= 0.0f && target_y <= window->WindowPadding.y)
+ target_y = 0.0f;
+ if (snap_on_edges && cr_y >= 1.0f && target_y >= window->ContentSize.y + window->WindowPadding.y + g.Style.ItemSpacing.y)
+ target_y = window->ContentSize.y + window->WindowPadding.y * 2.0f;
+ scroll.y = target_y - cr_y * (window->SizeFull.y - window->ScrollbarSizes.y - decoration_up_height);
+ }
+ scroll = ImMax(scroll, ImVec2(0.0f, 0.0f));
+ if (!window->Collapsed && !window->SkipItems)
+ {
+ scroll.x = ImMin(scroll.x, window->ScrollMax.x);
+ scroll.y = ImMin(scroll.y, window->ScrollMax.y);
+ }
+ return scroll;
+}
+
+// Scroll to keep newly navigated item fully into view
+ImVec2 ImGui::ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_rect)
+{
+ ImGuiContext& g = *GImGui;
+ ImRect window_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
+ //GetForegroundDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG]
+
+ ImVec2 delta_scroll;
+ if (!window_rect.Contains(item_rect))
+ {
+ if (window->ScrollbarX && item_rect.Min.x < window_rect.Min.x)
+ SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x + g.Style.ItemSpacing.x, 0.0f);
+ else if (window->ScrollbarX && item_rect.Max.x >= window_rect.Max.x)
+ SetScrollFromPosX(window, item_rect.Max.x - window->Pos.x + g.Style.ItemSpacing.x, 1.0f);
+ if (item_rect.Min.y < window_rect.Min.y)
+ SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y - g.Style.ItemSpacing.y, 0.0f);
+ else if (item_rect.Max.y >= window_rect.Max.y)
+ SetScrollFromPosY(window, item_rect.Max.y - window->Pos.y + g.Style.ItemSpacing.y, 1.0f);
+
+ ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window, false);
+ delta_scroll = next_scroll - window->Scroll;
+ }
+
+ // Also scroll parent window to keep us into view if necessary
+ if (window->Flags & ImGuiWindowFlags_ChildWindow)
+ delta_scroll += ScrollToBringRectIntoView(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll));
+
+ return delta_scroll;
+}
+
+float ImGui::GetScrollX()
+{
+ ImGuiWindow* window = GImGui->CurrentWindow;
+ return window->Scroll.x;
+}
+
+float ImGui::GetScrollY()
+{
+ ImGuiWindow* window = GImGui->CurrentWindow;
+ return window->Scroll.y;
+}
+
+float ImGui::GetScrollMaxX()
+{
+ ImGuiWindow* window = GImGui->CurrentWindow;
+ return window->ScrollMax.x;
+}
+
+float ImGui::GetScrollMaxY()
+{
+ ImGuiWindow* window = GImGui->CurrentWindow;
+ return window->ScrollMax.y;
+}
+
+void ImGui::SetScrollX(float scroll_x)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ window->ScrollTarget.x = scroll_x;
+ window->ScrollTargetCenterRatio.x = 0.0f;
+}
+
+void ImGui::SetScrollY(float scroll_y)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ window->ScrollTarget.y = scroll_y;
+ window->ScrollTargetCenterRatio.y = 0.0f;
+}
+
+void ImGui::SetScrollX(ImGuiWindow* window, float new_scroll_x)
+{
+ window->ScrollTarget.x = new_scroll_x;
+ window->ScrollTargetCenterRatio.x = 0.0f;
+}
+
+void ImGui::SetScrollY(ImGuiWindow* window, float new_scroll_y)
+{
+ window->ScrollTarget.y = new_scroll_y;
+ window->ScrollTargetCenterRatio.y = 0.0f;
+}
+
+
+void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
+{
+ // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size
+ IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
+ window->ScrollTarget.x = IM_FLOOR(local_x + window->Scroll.x);
+ window->ScrollTargetCenterRatio.x = center_x_ratio;
+}
+
+void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
+{
+ // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size
+ IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
+ const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
+ local_y -= decoration_up_height;
+ window->ScrollTarget.y = IM_FLOOR(local_y + window->Scroll.y);
+ window->ScrollTargetCenterRatio.y = center_y_ratio;
+}
+
+void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
+{
+ ImGuiContext& g = *GImGui;
+ SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
+}
+
+void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
+{
+ ImGuiContext& g = *GImGui;
+ SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
+}
+
+// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
+void ImGui::SetScrollHereX(float center_x_ratio)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ float target_x = window->DC.LastItemRect.Min.x - window->Pos.x; // Left of last item, in window space
+ float last_item_width = window->DC.LastItemRect.GetWidth();
+ target_x += (last_item_width * center_x_ratio) + (g.Style.ItemSpacing.x * (center_x_ratio - 0.5f) * 2.0f); // Precisely aim before, in the middle or after the last item.
+ SetScrollFromPosX(target_x, center_x_ratio);
+}
+
+// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
+void ImGui::SetScrollHereY(float center_y_ratio)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ float target_y = window->DC.CursorPosPrevLine.y - window->Pos.y; // Top of last item, in window space
+ target_y += (window->DC.PrevLineSize.y * center_y_ratio) + (g.Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line.
+ SetScrollFromPosY(target_y, center_y_ratio);
+}
+
//-----------------------------------------------------------------------------
// [SECTION] TOOLTIPS
//-----------------------------------------------------------------------------
void ImGui::BeginTooltip()
{
+ BeginTooltipEx(ImGuiWindowFlags_None, ImGuiTooltipFlags_None);
+}
+
+void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, ImGuiTooltipFlags tooltip_flags)
+{
ImGuiContext& g = *GImGui;
+
if (g.DragDropWithinSourceOrTarget)
{
// The default tooltip position is a little offset to give space to see the context menu (it's also clamped within the current viewport/monitor)
@@ -6316,27 +7374,18 @@ void ImGui::BeginTooltip()
SetNextWindowPos(tooltip_pos);
SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
//PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
- BeginTooltipEx(0, true);
- }
- else
- {
- BeginTooltipEx(0, false);
+ tooltip_flags |= ImGuiTooltipFlags_OverridePreviousTooltip;
}
-}
-// Not exposed publicly as BeginTooltip() because bool parameters are evil. Let's see if other needs arise first.
-void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, bool override_previous_tooltip)
-{
- ImGuiContext& g = *GImGui;
char window_name[16];
ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
- if (override_previous_tooltip)
+ if (tooltip_flags & ImGuiTooltipFlags_OverridePreviousTooltip)
if (ImGuiWindow* window = FindWindowByName(window_name))
if (window->Active)
{
// Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
window->Hidden = true;
- window->HiddenFramesRegular = 1;
+ window->HiddenFramesCanSkipItems = 1;
ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
}
ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoInputs|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize;
@@ -6351,11 +7400,7 @@ void ImGui::EndTooltip()
void ImGui::SetTooltipV(const char* fmt, va_list args)
{
- ImGuiContext& g = *GImGui;
- if (g.DragDropWithinSourceOrTarget)
- BeginTooltip();
- else
- BeginTooltipEx(0, true);
+ BeginTooltipEx(0, ImGuiTooltipFlags_OverridePreviousTooltip);
TextV(fmt, args);
EndTooltip();
}
@@ -6375,16 +7420,16 @@ void ImGui::SetTooltip(const char* fmt, ...)
bool ImGui::IsPopupOpen(ImGuiID id)
{
ImGuiContext& g = *GImGui;
- return g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].PopupId == id;
+ return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
}
bool ImGui::IsPopupOpen(const char* str_id)
{
ImGuiContext& g = *GImGui;
- return g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].PopupId == g.CurrentWindow->GetID(str_id);
+ return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == g.CurrentWindow->GetID(str_id);
}
-ImGuiWindow* ImGui::GetFrontMostPopupModal()
+ImGuiWindow* ImGui::GetTopMostPopupModal()
{
ImGuiContext& g = *GImGui;
for (int n = g.OpenPopupStack.Size-1; n >= 0; n--)
@@ -6408,17 +7453,17 @@ void ImGui::OpenPopupEx(ImGuiID id)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* parent_window = g.CurrentWindow;
- int current_stack_size = g.CurrentPopupStack.Size;
- ImGuiPopupRef popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
+ int current_stack_size = g.BeginPopupStack.Size;
+ ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
popup_ref.PopupId = id;
popup_ref.Window = NULL;
- popup_ref.ParentWindow = parent_window;
+ popup_ref.SourceWindow = g.NavWindow;
popup_ref.OpenFrameCount = g.FrameCount;
popup_ref.OpenParentId = parent_window->IDStack.back();
- popup_ref.OpenMousePos = g.IO.MousePos;
popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
+ popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
- //printf("[%05d] OpenPopupEx(0x%08X)\n", g.FrameCount, id);
+ //IMGUI_DEBUG_LOG("OpenPopupEx(0x%08X)\n", g.FrameCount, id);
if (g.OpenPopupStack.Size < current_stack_size + 1)
{
g.OpenPopupStack.push_back(popup_ref);
@@ -6446,20 +7491,7 @@ void ImGui::OpenPopupEx(ImGuiID id)
}
}
-bool ImGui::OpenPopupOnItemClick(const char* str_id, int mouse_button)
-{
- ImGuiWindow* window = GImGui->CurrentWindow;
- if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
- {
- ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
- IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
- OpenPopupEx(id);
- return true;
- }
- return false;
-}
-
-void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window)
+void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
{
ImGuiContext& g = *GImGui;
if (g.OpenPopupStack.empty())
@@ -6467,78 +7499,108 @@ void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window)
// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
// Don't close our own child popup windows.
- int n = 0;
+ int popup_count_to_keep = 0;
if (ref_window)
{
- for (n = 0; n < g.OpenPopupStack.Size; n++)
+ // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
+ for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
{
- ImGuiPopupRef& popup = g.OpenPopupStack[n];
+ ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
if (!popup.Window)
continue;
IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
continue;
- // Trim the stack if popups are not direct descendant of the reference window (which is often the NavWindow)
- bool has_focus = false;
- for (int m = n; m < g.OpenPopupStack.Size && !has_focus; m++)
- has_focus = (g.OpenPopupStack[m].Window && g.OpenPopupStack[m].Window->RootWindow == ref_window->RootWindow);
- if (!has_focus)
+ // Trim the stack when popups are not direct descendant of the reference window (the reference window is often the NavWindow)
+ bool popup_or_descendent_is_ref_window = false;
+ for (int m = popup_count_to_keep; m < g.OpenPopupStack.Size && !popup_or_descendent_is_ref_window; m++)
+ if (ImGuiWindow* popup_window = g.OpenPopupStack[m].Window)
+ if (popup_window->RootWindow == ref_window->RootWindow)
+ popup_or_descendent_is_ref_window = true;
+ if (!popup_or_descendent_is_ref_window)
break;
}
}
- if (n < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the block below
- ClosePopupToLevel(n);
+ if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
+ {
+ //IMGUI_DEBUG_LOG("ClosePopupsOverWindow(%s) -> ClosePopupToLevel(%d)\n", ref_window->Name, popup_count_to_keep);
+ ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
+ }
}
-void ImGui::ClosePopupToLevel(int remaining)
+void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
{
- IM_ASSERT(remaining >= 0);
ImGuiContext& g = *GImGui;
- ImGuiWindow* focus_window = (remaining > 0) ? g.OpenPopupStack[remaining-1].Window : g.OpenPopupStack[0].ParentWindow;
- if (g.NavLayer == 0)
- focus_window = NavRestoreLastChildNavWindow(focus_window);
- FocusWindow(focus_window);
- focus_window->DC.NavHideHighlightOneFrame = true;
+ IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
+ ImGuiWindow* focus_window = g.OpenPopupStack[remaining].SourceWindow;
+ ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window;
g.OpenPopupStack.resize(remaining);
-}
-void ImGui::ClosePopup(ImGuiID id)
-{
- if (!IsPopupOpen(id))
- return;
- ImGuiContext& g = *GImGui;
- ClosePopupToLevel(g.OpenPopupStack.Size - 1);
+ if (restore_focus_to_window_under_popup)
+ {
+ if (focus_window && !focus_window->WasActive && popup_window)
+ {
+ // Fallback
+ FocusTopMostWindowUnderOne(popup_window, NULL);
+ }
+ else
+ {
+ if (g.NavLayer == 0 && focus_window)
+ focus_window = NavRestoreLastChildNavWindow(focus_window);
+ FocusWindow(focus_window);
+ }
+ }
}
// Close the popup we have begin-ed into.
void ImGui::CloseCurrentPopup()
{
ImGuiContext& g = *GImGui;
- int popup_idx = g.CurrentPopupStack.Size - 1;
- if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.CurrentPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
+ int popup_idx = g.BeginPopupStack.Size - 1;
+ if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
return;
- while (popup_idx > 0 && g.OpenPopupStack[popup_idx].Window && (g.OpenPopupStack[popup_idx].Window->Flags & ImGuiWindowFlags_ChildMenu))
+
+ // Closing a menu closes its top-most parent popup (unless a modal)
+ while (popup_idx > 0)
+ {
+ ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
+ ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
+ bool close_parent = false;
+ if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
+ if (parent_popup_window == NULL || !(parent_popup_window->Flags & ImGuiWindowFlags_Modal))
+ close_parent = true;
+ if (!close_parent)
+ break;
popup_idx--;
- ClosePopupToLevel(popup_idx);
+ }
+ //IMGUI_DEBUG_LOG("CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
+ ClosePopupToLevel(popup_idx, true);
+
+ // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
+ // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
+ // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
+ if (ImGuiWindow* window = g.NavWindow)
+ window->DC.NavHideHighlightOneFrame = true;
}
-bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags)
+bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
if (!IsPopupOpen(id))
{
- g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values
+ g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
return false;
}
char name[20];
- if (extra_flags & ImGuiWindowFlags_ChildMenu)
- ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.CurrentPopupStack.Size); // Recycle windows based on depth
+ if (flags & ImGuiWindowFlags_ChildMenu)
+ ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginPopupStack.Size); // Recycle windows based on depth
else
ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
- bool is_open = Begin(name, NULL, extra_flags | ImGuiWindowFlags_Popup);
+ flags |= ImGuiWindowFlags_Popup;
+ bool is_open = Begin(name, NULL, flags);
if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
EndPopup();
@@ -6548,14 +7610,17 @@ bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags)
bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
- if (g.OpenPopupStack.Size <= g.CurrentPopupStack.Size) // Early out for performance
+ if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
{
- g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values
+ g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
return false;
}
- return BeginPopupEx(g.CurrentWindow->GetID(str_id), flags|ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
+ flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
+ return BeginPopupEx(g.CurrentWindow->GetID(str_id), flags);
}
+// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
+// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup) so the actual value of *p_open is meaningless here.
bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
@@ -6563,21 +7628,22 @@ bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags fla
const ImGuiID id = window->GetID(name);
if (!IsPopupOpen(id))
{
- g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values
+ g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
return false;
}
// Center modal windows by default
// FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
- if (g.NextWindowData.PosCond == 0)
+ if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
- bool is_open = Begin(name, p_open, flags | ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings);
+ flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings;
+ const bool is_open = Begin(name, p_open, flags);
if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
{
EndPopup();
if (is_open)
- ClosePopup(id);
+ ClosePopupToLevel(g.BeginPopupStack.Size, true);
return false;
}
return is_open;
@@ -6585,22 +7651,43 @@ bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags fla
void ImGui::EndPopup()
{
- ImGuiContext& g = *GImGui; (void)g;
- IM_ASSERT(g.CurrentWindow->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
- IM_ASSERT(g.CurrentPopupStack.Size > 0);
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
+ IM_ASSERT(g.BeginPopupStack.Size > 0);
// Make all menus and popups wrap around for now, may need to expose that policy.
- NavMoveRequestTryWrapping(g.CurrentWindow, ImGuiNavMoveFlags_LoopY);
+ NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
+ // Child-popups don't need to be layed out
+ IM_ASSERT(g.WithinEndChild == false);
+ if (window->Flags & ImGuiWindowFlags_ChildWindow)
+ g.WithinEndChild = true;
End();
+ g.WithinEndChild = false;
+}
+
+bool ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiMouseButton mouse_button)
+{
+ ImGuiWindow* window = GImGui->CurrentWindow;
+ if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
+ {
+ ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
+ IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
+ OpenPopupEx(id);
+ return true;
+ }
+ return false;
}
// This is a helper to handle the simplest case of associating one named popup to one given widget.
// You may want to handle this on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
// You can pass a NULL str_id to use the identifier of the last item.
-bool ImGui::BeginPopupContextItem(const char* str_id, int mouse_button)
+bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiMouseButton mouse_button)
{
ImGuiWindow* window = GImGui->CurrentWindow;
+ if (window->SkipItems)
+ return false;
ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
@@ -6608,7 +7695,7 @@ bool ImGui::BeginPopupContextItem(const char* str_id, int mouse_button)
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
-bool ImGui::BeginPopupContextWindow(const char* str_id, int mouse_button, bool also_over_items)
+bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiMouseButton mouse_button, bool also_over_items)
{
if (!str_id)
str_id = "window_context";
@@ -6619,7 +7706,7 @@ bool ImGui::BeginPopupContextWindow(const char* str_id, int mouse_button, bool a
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
-bool ImGui::BeginPopupContextVoid(const char* str_id, int mouse_button)
+bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiMouseButton mouse_button)
{
if (!str_id)
str_id = "void_context";
@@ -6629,21 +7716,13 @@ bool ImGui::BeginPopupContextVoid(const char* str_id, int mouse_button)
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
-ImRect ImGui::GetWindowAllowedExtentRect(ImGuiWindow*)
-{
- ImVec2 padding = GImGui->Style.DisplaySafeAreaPadding;
- ImRect r_screen = GetViewportRect();
- r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
- return r_screen;
-}
-
// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
{
ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
- //GImGui->OverlayDrawList.AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
- //GImGui->OverlayDrawList.AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
+ //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
+ //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
// Combo Box policy (we want a connecting edge)
if (policy == ImGuiPopupPositionPolicy_ComboBox)
@@ -6692,6 +7771,15 @@ ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& s
return pos;
}
+ImRect ImGui::GetWindowAllowedExtentRect(ImGuiWindow* window)
+{
+ IM_UNUSED(window);
+ ImVec2 padding = GImGui->Style.DisplaySafeAreaPadding;
+ ImRect r_screen = GetViewportRect();
+ r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
+ return r_screen;
+}
+
ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
@@ -6699,11 +7787,11 @@ ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
ImRect r_outer = GetWindowAllowedExtentRect(window);
if (window->Flags & ImGuiWindowFlags_ChildMenu)
{
- // Child menus typically request _any_ position within the parent menu item, and then our FindBestWindowPosForPopup() function will move the new menu outside the parent bounds.
+ // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
// This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
IM_ASSERT(g.CurrentWindow == window);
ImGuiWindow* parent_window = g.CurrentWindowStack[g.CurrentWindowStack.Size - 2];
- float horizontal_overlap = g.Style.ItemSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
+ float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
ImRect r_avoid;
if (parent_window->DC.MenuBarAppending)
r_avoid = ImRect(-FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight(), FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight() + parent_window->MenuBarHeight());
@@ -6735,10 +7823,57 @@ ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
return window->Pos;
}
+
//-----------------------------------------------------------------------------
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
//-----------------------------------------------------------------------------
+// FIXME-NAV: The existence of SetNavID vs SetNavIDWithRectRel vs SetFocusID is incredibly messy and confusing,
+// and needs some explanation or serious refactoring.
+void ImGui::SetNavID(ImGuiID id, int nav_layer, ImGuiID focus_scope_id)
+{
+ ImGuiContext& g = *GImGui;
+ IM_ASSERT(g.NavWindow);
+ IM_ASSERT(nav_layer == 0 || nav_layer == 1);
+ g.NavId = id;
+ g.NavFocusScopeId = focus_scope_id;
+ g.NavWindow->NavLastIds[nav_layer] = id;
+}
+
+void ImGui::SetNavIDWithRectRel(ImGuiID id, int nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
+{
+ ImGuiContext& g = *GImGui;
+ SetNavID(id, nav_layer, focus_scope_id);
+ g.NavWindow->NavRectRel[nav_layer] = rect_rel;
+ g.NavMousePosDirty = true;
+ g.NavDisableHighlight = false;
+ g.NavDisableMouseHover = true;
+}
+
+void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
+{
+ ImGuiContext& g = *GImGui;
+ IM_ASSERT(id != 0);
+
+ // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and window->DC.NavFocusScopeIdCurrent are valid.
+ // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
+ const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
+ if (g.NavWindow != window)
+ g.NavInitRequest = false;
+ g.NavWindow = window;
+ g.NavId = id;
+ g.NavLayer = nav_layer;
+ g.NavFocusScopeId = window->DC.NavFocusScopeIdCurrent;
+ window->NavLastIds[nav_layer] = id;
+ if (window->DC.LastItemId == id)
+ window->NavRectRel[nav_layer] = ImRect(window->DC.LastItemRect.Min - window->Pos, window->DC.LastItemRect.Max - window->Pos);
+
+ if (g.ActiveIdSource == ImGuiInputSource_Nav)
+ g.NavDisableMouseHover = true;
+ else
+ g.NavDisableHighlight = true;
+}
+
ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
{
if (ImFabs(dx) > ImFabs(dy))
@@ -6770,7 +7905,7 @@ static void inline NavClampRectToVisibleAreaForMoveDir(ImGuiDir move_dir, ImRect
}
// Scoring function for directional navigation. Based on https://gist.github.com/rygorous/6981057
-static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand)
+static bool ImGui::NavScoreItem(ImGuiNavMoveResult* result, ImRect cand)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
@@ -6784,7 +7919,7 @@ static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand)
if (window->ParentWindow == g.NavWindow)
{
IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
- if (!window->ClipRect.Contains(cand))
+ if (!window->ClipRect.Overlaps(cand))
return false;
cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
}
@@ -6833,13 +7968,13 @@ static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand)
#if IMGUI_DEBUG_NAV_SCORING
char buf[128];
- if (ImGui::IsMouseHoveringRect(cand.Min, cand.Max))
+ if (IsMouseHoveringRect(cand.Min, cand.Max))
{
ImFormatString(buf, IM_ARRAYSIZE(buf), "dbox (%.2f,%.2f->%.4f)\ndcen (%.2f,%.2f->%.4f)\nd (%.2f,%.2f->%.4f)\nnav %c, quadrant %c", dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "WENS"[g.NavMoveDir], "WENS"[quadrant]);
- ImDrawList* draw_list = ImGui::GetOverlayDrawList();
+ ImDrawList* draw_list = GetForegroundDrawList(window);
draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255,200,0,100));
draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200));
- draw_list->AddRectFilled(cand.Max-ImVec2(4,4), cand.Max+ImGui::CalcTextSize(buf)+ImVec2(4,4), IM_COL32(40,0,0,150));
+ draw_list->AddRectFilled(cand.Max - ImVec2(4,4), cand.Max + CalcTextSize(buf) + ImVec2(4,4), IM_COL32(40,0,0,150));
draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Max, ~0U, buf);
}
else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate.
@@ -6848,7 +7983,7 @@ static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand)
if (quadrant == g.NavMoveDir)
{
ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
- ImDrawList* draw_list = ImGui::GetOverlayDrawList();
+ ImDrawList* draw_list = GetForegroundDrawList(window);
draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 200));
draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Min, IM_COL32(255, 255, 255, 255), buf);
}
@@ -6929,7 +8064,7 @@ static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, con
// Process Move Request (scoring for navigation)
// FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRectScreen + scoring from a rect wrapped according to current wrapping policy)
- if ((g.NavId != id || (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & ImGuiItemFlags_NoNav))
+ if ((g.NavId != id || (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & (ImGuiItemFlags_Disabled|ImGuiItemFlags_NoNav)))
{
ImGuiNavMoveResult* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
#if IMGUI_DEBUG_NAV_SCORING
@@ -6942,19 +8077,22 @@ static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, con
#endif
if (new_best)
{
- result->ID = id;
result->Window = window;
+ result->ID = id;
+ result->FocusScopeId = window->DC.NavFocusScopeIdCurrent;
result->RectRel = nav_bb_rel;
}
+ // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
const float VISIBLE_RATIO = 0.70f;
if ((g.NavMoveRequestFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
if (NavScoreItem(&g.NavMoveResultLocalVisibleSet, nav_bb))
{
result = &g.NavMoveResultLocalVisibleSet;
- result->ID = id;
result->Window = window;
+ result->ID = id;
+ result->FocusScopeId = window->DC.NavFocusScopeIdCurrent;
result->RectRel = nav_bb_rel;
}
}
@@ -6964,8 +8102,9 @@ static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, con
{
g.NavWindow = window; // Always refresh g.NavWindow, because some operations such as FocusItem() don't have a window.
g.NavLayer = window->DC.NavLayerCurrent;
+ g.NavFocusScopeId = window->DC.NavFocusScopeIdCurrent;
g.NavIdIsAlive = true;
- g.NavIdTabCounter = window->FocusIdxTabCounter;
+ g.NavIdTabCounter = window->DC.FocusCounterTabStop;
window->NavRectRel[window->DC.NavLayerCurrent] = nav_bb_rel; // Store item bounding box (relative to window position)
}
}
@@ -6987,7 +8126,7 @@ void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, const Im
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_None);
- ImGui::NavMoveRequestCancel();
+ NavMoveRequestCancel();
g.NavMoveDir = move_dir;
g.NavMoveClipDir = clip_dir;
g.NavMoveRequestForward = ImGuiNavForward_ForwardQueued;
@@ -7006,7 +8145,7 @@ void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags mov
ImGuiDir clip_dir = g.NavMoveDir;
if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
{
- bb_rel.Min.x = bb_rel.Max.x = ImMax(window->SizeFull.x, window->SizeContents.x) - window->Scroll.x;
+ bb_rel.Min.x = bb_rel.Max.x = ImMax(window->SizeFull.x, window->ContentSize.x + window->WindowPadding.x * 2.0f) - window->Scroll.x;
if (move_flags & ImGuiNavMoveFlags_WrapX) { bb_rel.TranslateY(-bb_rel.GetHeight()); clip_dir = ImGuiDir_Up; }
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
@@ -7018,7 +8157,7 @@ void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags mov
}
if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
{
- bb_rel.Min.y = bb_rel.Max.y = ImMax(window->SizeFull.y, window->SizeContents.y) - window->Scroll.y;
+ bb_rel.Min.y = bb_rel.Max.y = ImMax(window->SizeFull.y, window->ContentSize.y + window->WindowPadding.y * 2.0f) - window->Scroll.y;
if (move_flags & ImGuiNavMoveFlags_WrapY) { bb_rel.TranslateX(-bb_rel.GetWidth()); clip_dir = ImGuiDir_Left; }
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
@@ -7030,7 +8169,9 @@ void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags mov
}
}
-static void ImGui::NavSaveLastChildNavWindow(ImGuiWindow* nav_window)
+// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
+// This way we could find the last focused window among our children. It would be much less confusing this way?
+static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
{
ImGuiWindow* parent_window = nav_window;
while (parent_window && (parent_window->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (parent_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
@@ -7039,22 +8180,24 @@ static void ImGui::NavSaveLastChildNavWindow(ImGuiWindow* nav_window)
parent_window->NavLastChildNavWindow = nav_window;
}
-// Call when we are expected to land on Layer 0 after FocusWindow()
+// Restore the last focused child.
+// Call when we are expected to land on the Main Layer (0) after FocusWindow()
static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
{
return window->NavLastChildNavWindow ? window->NavLastChildNavWindow : window;
}
-static void NavRestoreLayer(int layer)
+static void NavRestoreLayer(ImGuiNavLayer layer)
{
ImGuiContext& g = *GImGui;
g.NavLayer = layer;
if (layer == 0)
g.NavWindow = ImGui::NavRestoreLastChildNavWindow(g.NavWindow);
- if (layer == 0 && g.NavWindow->NavLastIds[0] != 0)
- ImGui::SetNavIDWithRectRel(g.NavWindow->NavLastIds[0], layer, g.NavWindow->NavRectRel[0]);
+ ImGuiWindow* window = g.NavWindow;
+ if (layer == 0 && window->NavLastIds[0] != 0)
+ ImGui::SetNavIDWithRectRel(window->NavLastIds[0], layer, 0, window->NavRectRel[0]);
else
- ImGui::NavInitWindow(g.NavWindow, true);
+ ImGui::NavInitWindow(window, true);
}
static inline void ImGui::NavUpdateAnyRequestFlag()
@@ -7074,9 +8217,10 @@ void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
if (!(window->Flags & ImGuiWindowFlags_NoNavInputs))
if (!(window->Flags & ImGuiWindowFlags_ChildWindow) || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
init_for_nav = true;
+ //IMGUI_DEBUG_LOG("[Nav] NavInitWindow() init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
if (init_for_nav)
{
- SetNavID(0, g.NavLayer);
+ SetNavID(0, g.NavLayer, 0);
g.NavInitRequest = true;
g.NavInitRequestFromMove = false;
g.NavInitResultId = 0;
@@ -7086,6 +8230,7 @@ void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
else
{
g.NavId = window->NavLastIds[0];
+ g.NavFocusScopeId = 0;
}
}
@@ -7093,13 +8238,20 @@ static ImVec2 ImGui::NavCalcPreferredRefPos()
{
ImGuiContext& g = *GImGui;
if (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow)
- return ImFloor(g.IO.MousePos);
-
- // When navigation is active and mouse is disabled, decide on an arbitrary position around the bottom left of the currently navigated item
- const ImRect& rect_rel = g.NavWindow->NavRectRel[g.NavLayer];
- ImVec2 pos = g.NavWindow->Pos + ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x*4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight()));
- ImRect visible_rect = GetViewportRect();
- return ImFloor(ImClamp(pos, visible_rect.Min, visible_rect.Max)); // ImFloor() is important because non-integer mouse position application in back-end might be lossy and result in undesirable non-zero delta.
+ {
+ // Mouse (we need a fallback in case the mouse becomes invalid after being used)
+ if (IsMousePosValid(&g.IO.MousePos))
+ return g.IO.MousePos;
+ return g.LastValidMousePos;
+ }
+ else
+ {
+ // When navigation is active and mouse is disabled, decide on an arbitrary position around the bottom left of the currently navigated item.
+ const ImRect& rect_rel = g.NavWindow->NavRectRel[g.NavLayer];
+ ImVec2 pos = g.NavWindow->Pos + ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight()));
+ ImRect visible_rect = GetViewportRect();
+ return ImFloor(ImClamp(pos, visible_rect.Min, visible_rect.Max)); // ImFloor() is important because non-integer mouse position application in back-end might be lossy and result in undesirable non-zero delta.
+ }
}
float ImGui::GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode)
@@ -7116,11 +8268,11 @@ float ImGui::GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode)
if (mode == ImGuiInputReadMode_Pressed) // Return 1.0f when just pressed, no repeat, ignore analog input.
return (t == 0.0f) ? 1.0f : 0.0f;
if (mode == ImGuiInputReadMode_Repeat)
- return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 0.80f, g.IO.KeyRepeatRate * 0.80f);
+ return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 0.72f, g.IO.KeyRepeatRate * 0.80f);
if (mode == ImGuiInputReadMode_RepeatSlow)
- return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 1.00f, g.IO.KeyRepeatRate * 2.00f);
+ return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 1.25f, g.IO.KeyRepeatRate * 2.00f);
if (mode == ImGuiInputReadMode_RepeatFast)
- return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 0.80f, g.IO.KeyRepeatRate * 0.30f);
+ return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 0.72f, g.IO.KeyRepeatRate * 0.30f);
return 0.0f;
}
@@ -7140,47 +8292,16 @@ ImVec2 ImGui::GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInput
return delta;
}
-// Scroll to keep newly navigated item fully into view
-// NB: We modify rect_rel by the amount we scrolled for, so it is immediately updated.
-static void NavScrollToBringItemIntoView(ImGuiWindow* window, const ImRect& item_rect)
-{
- ImRect window_rect(window->InnerMainRect.Min - ImVec2(1, 1), window->InnerMainRect.Max + ImVec2(1, 1));
- //g.OverlayDrawList.AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG]
- if (window_rect.Contains(item_rect))
- return;
-
- ImGuiContext& g = *GImGui;
- if (window->ScrollbarX && item_rect.Min.x < window_rect.Min.x)
- {
- window->ScrollTarget.x = item_rect.Min.x - window->Pos.x + window->Scroll.x - g.Style.ItemSpacing.x;
- window->ScrollTargetCenterRatio.x = 0.0f;
- }
- else if (window->ScrollbarX && item_rect.Max.x >= window_rect.Max.x)
- {
- window->ScrollTarget.x = item_rect.Max.x - window->Pos.x + window->Scroll.x + g.Style.ItemSpacing.x;
- window->ScrollTargetCenterRatio.x = 1.0f;
- }
- if (item_rect.Min.y < window_rect.Min.y)
- {
- window->ScrollTarget.y = item_rect.Min.y - window->Pos.y + window->Scroll.y - g.Style.ItemSpacing.y;
- window->ScrollTargetCenterRatio.y = 0.0f;
- }
- else if (item_rect.Max.y >= window_rect.Max.y)
- {
- window->ScrollTarget.y = item_rect.Max.y - window->Pos.y + window->Scroll.y + g.Style.ItemSpacing.y;
- window->ScrollTargetCenterRatio.y = 1.0f;
- }
-}
-
static void ImGui::NavUpdate()
{
ImGuiContext& g = *GImGui;
g.IO.WantSetMousePos = false;
#if 0
- if (g.NavScoringCount > 0) printf("[%05d] NavScoringCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.FrameCount, g.NavScoringCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
+ if (g.NavScoringCount > 0) IMGUI_DEBUG_LOG("NavScoringCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.FrameCount, g.NavScoringCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
#endif
- // Set input source as Gamepad when buttons are pressed before we map Keyboard (some features differs when used with Gamepad vs Keyboard)
+ // Set input source as Gamepad when buttons are pressed (as some features differs when used with Gamepad vs Keyboard)
+ // (do it before we map Keyboard input!)
bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
if (nav_gamepad_active)
@@ -7190,7 +8311,7 @@ static void ImGui::NavUpdate()
// Update Keyboard->Nav inputs mapping
if (nav_keyboard_active)
{
- #define NAV_MAP_KEY(_KEY, _NAV_INPUT) if (IsKeyDown(g.IO.KeyMap[_KEY])) { g.IO.NavInputs[_NAV_INPUT] = 1.0f; g.NavInputSource = ImGuiInputSource_NavKeyboard; }
+ #define NAV_MAP_KEY(_KEY, _NAV_INPUT) do { if (IsKeyDown(g.IO.KeyMap[_KEY])) { g.IO.NavInputs[_NAV_INPUT] = 1.0f; g.NavInputSource = ImGuiInputSource_NavKeyboard; } } while (0)
NAV_MAP_KEY(ImGuiKey_Space, ImGuiNavInput_Activate );
NAV_MAP_KEY(ImGuiKey_Enter, ImGuiNavInput_Input );
NAV_MAP_KEY(ImGuiKey_Escape, ImGuiNavInput_Cancel );
@@ -7198,9 +8319,12 @@ static void ImGui::NavUpdate()
NAV_MAP_KEY(ImGuiKey_RightArrow,ImGuiNavInput_KeyRight_);
NAV_MAP_KEY(ImGuiKey_UpArrow, ImGuiNavInput_KeyUp_ );
NAV_MAP_KEY(ImGuiKey_DownArrow, ImGuiNavInput_KeyDown_ );
- if (g.IO.KeyCtrl) g.IO.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f;
- if (g.IO.KeyShift) g.IO.NavInputs[ImGuiNavInput_TweakFast] = 1.0f;
- if (g.IO.KeyAlt) g.IO.NavInputs[ImGuiNavInput_KeyMenu_] = 1.0f;
+ if (g.IO.KeyCtrl)
+ g.IO.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f;
+ if (g.IO.KeyShift)
+ g.IO.NavInputs[ImGuiNavInput_TweakFast] = 1.0f;
+ if (g.IO.KeyAlt && !g.IO.KeyCtrl) // AltGR is Alt+Ctrl, also even on keyboards without AltGR we don't want Alt+Ctrl to open menu.
+ g.IO.NavInputs[ImGuiNavInput_KeyMenu_] = 1.0f;
#undef NAV_MAP_KEY
}
memcpy(g.IO.NavInputsDownDurationPrev, g.IO.NavInputsDownDuration, sizeof(g.IO.NavInputsDownDuration));
@@ -7208,14 +8332,15 @@ static void ImGui::NavUpdate()
g.IO.NavInputsDownDuration[i] = (g.IO.NavInputs[i] > 0.0f) ? (g.IO.NavInputsDownDuration[i] < 0.0f ? 0.0f : g.IO.NavInputsDownDuration[i] + g.IO.DeltaTime) : -1.0f;
// Process navigation init request (select first/default focus)
- if (g.NavInitResultId != 0 && (!g.NavDisableHighlight || g.NavInitRequestFromMove))
+ // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
+ if (g.NavInitResultId != 0 && (!g.NavDisableHighlight || g.NavInitRequestFromMove) && g.NavWindow)
{
// Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
- IM_ASSERT(g.NavWindow);
+ //IMGUI_DEBUG_LOG("[Nav] Apply NavInitRequest result: 0x%08X Layer %d in \"%s\"\n", g.NavInitResultId, g.NavLayer, g.NavWindow->Name);
if (g.NavInitRequestFromMove)
- SetNavIDWithRectRel(g.NavInitResultId, g.NavLayer, g.NavInitResultRectRel);
+ SetNavIDWithRectRel(g.NavInitResultId, g.NavLayer, 0, g.NavInitResultRectRel);
else
- SetNavID(g.NavInitResultId, g.NavLayer);
+ SetNavID(g.NavInitResultId, g.NavLayer, 0);
g.NavWindow->NavRectRel[g.NavLayer] = g.NavInitResultRectRel;
}
g.NavInitRequest = false;
@@ -7224,7 +8349,7 @@ static void ImGui::NavUpdate()
g.NavJustMovedToId = 0;
// Process navigation move request
- if (g.NavMoveRequest && (g.NavMoveResultLocal.ID != 0 || g.NavMoveResultOther.ID != 0))
+ if (g.NavMoveRequest)
NavUpdateMoveResult();
// When a forwarded move request failed, we restore the highlight that we disabled during the forward frame
@@ -7256,7 +8381,7 @@ static void ImGui::NavUpdate()
// Store our return window (for returning from Layer 1 to Layer 0) and clear it as soon as we step back in our own Layer 0
if (g.NavWindow)
- NavSaveLastChildNavWindow(g.NavWindow);
+ NavSaveLastChildNavWindowIntoParent(g.NavWindow);
if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == 0)
g.NavWindow->NavLastChildNavWindow = NULL;
@@ -7265,14 +8390,15 @@ static void ImGui::NavUpdate()
// Set output flags for user application
g.IO.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
- g.IO.NavVisible = (g.IO.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL) || g.NavInitRequest;
+ g.IO.NavVisible = (g.IO.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
// Process NavCancel input (to close a popup, get back to parent, clear focus)
- if (IsNavInputPressed(ImGuiNavInput_Cancel, ImGuiInputReadMode_Pressed))
+ if (IsNavInputTest(ImGuiNavInput_Cancel, ImGuiInputReadMode_Pressed))
{
if (g.ActiveId != 0)
{
- ClearActiveID();
+ if (!IsActiveIdUsingNavInput(ImGuiNavInput_Cancel))
+ ClearActiveID();
}
else if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow) && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow)
{
@@ -7281,8 +8407,9 @@ static void ImGui::NavUpdate()
ImGuiWindow* parent_window = g.NavWindow->ParentWindow;
IM_ASSERT(child_window->ChildId != 0);
FocusWindow(parent_window);
- SetNavID(child_window->ChildId, 0);
- g.NavIdIsAlive = false;
+ SetNavID(child_window->ChildId, 0, 0);
+ // Reassigning with same value, we're being explicit here.
+ g.NavIdIsAlive = false; // -V1048
if (g.NavDisableMouseHover)
g.NavMousePosDirty = true;
}
@@ -7290,19 +8417,19 @@ static void ImGui::NavUpdate()
{
// Close open popup/menu
if (!(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
- ClosePopupToLevel(g.OpenPopupStack.Size - 1);
+ ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
}
else if (g.NavLayer != 0)
{
// Leave the "menu" layer
- NavRestoreLayer(0);
+ NavRestoreLayer(ImGuiNavLayer_Main);
}
else
{
// Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
g.NavWindow->NavLastIds[0] = 0;
- g.NavId = 0;
+ g.NavId = g.NavFocusScopeId = 0;
}
}
@@ -7311,14 +8438,14 @@ static void ImGui::NavUpdate()
if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
{
bool activate_down = IsNavInputDown(ImGuiNavInput_Activate);
- bool activate_pressed = activate_down && IsNavInputPressed(ImGuiNavInput_Activate, ImGuiInputReadMode_Pressed);
+ bool activate_pressed = activate_down && IsNavInputTest(ImGuiNavInput_Activate, ImGuiInputReadMode_Pressed);
if (g.ActiveId == 0 && activate_pressed)
g.NavActivateId = g.NavId;
if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_down)
g.NavActivateDownId = g.NavId;
if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_pressed)
g.NavActivatePressedId = g.NavId;
- if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && IsNavInputPressed(ImGuiNavInput_Input, ImGuiInputReadMode_Pressed))
+ if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && IsNavInputTest(ImGuiNavInput_Input, ImGuiInputReadMode_Pressed))
g.NavInputId = g.NavId;
}
if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
@@ -7333,17 +8460,17 @@ static void ImGui::NavUpdate()
g.NavNextActivateId = 0;
// Initiate directional inputs request
- const int allowed_dir_flags = (g.ActiveId == 0) ? ~0 : g.ActiveIdAllowNavDirFlags;
if (g.NavMoveRequestForward == ImGuiNavForward_None)
{
g.NavMoveDir = ImGuiDir_None;
- g.NavMoveRequestFlags = 0;
- if (g.NavWindow && !g.NavWindowingTarget && allowed_dir_flags && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
+ g.NavMoveRequestFlags = ImGuiNavMoveFlags_None;
+ if (g.NavWindow && !g.NavWindowingTarget && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
{
- if ((allowed_dir_flags & (1<<ImGuiDir_Left)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadLeft, ImGuiNavInput_KeyLeft_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Left;
- if ((allowed_dir_flags & (1<<ImGuiDir_Right)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadRight,ImGuiNavInput_KeyRight_,ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Right;
- if ((allowed_dir_flags & (1<<ImGuiDir_Up)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadUp, ImGuiNavInput_KeyUp_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Up;
- if ((allowed_dir_flags & (1<<ImGuiDir_Down)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadDown, ImGuiNavInput_KeyDown_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Down;
+ const ImGuiInputReadMode read_mode = ImGuiInputReadMode_Repeat;
+ if (!IsActiveIdUsingNavDir(ImGuiDir_Left) && (IsNavInputTest(ImGuiNavInput_DpadLeft, read_mode) || IsNavInputTest(ImGuiNavInput_KeyLeft_, read_mode))) { g.NavMoveDir = ImGuiDir_Left; }
+ if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && (IsNavInputTest(ImGuiNavInput_DpadRight, read_mode) || IsNavInputTest(ImGuiNavInput_KeyRight_, read_mode))) { g.NavMoveDir = ImGuiDir_Right; }
+ if (!IsActiveIdUsingNavDir(ImGuiDir_Up) && (IsNavInputTest(ImGuiNavInput_DpadUp, read_mode) || IsNavInputTest(ImGuiNavInput_KeyUp_, read_mode))) { g.NavMoveDir = ImGuiDir_Up; }
+ if (!IsActiveIdUsingNavDir(ImGuiDir_Down) && (IsNavInputTest(ImGuiNavInput_DpadDown, read_mode) || IsNavInputTest(ImGuiNavInput_KeyDown_, read_mode))) { g.NavMoveDir = ImGuiDir_Down; }
}
g.NavMoveClipDir = g.NavMoveDir;
}
@@ -7356,10 +8483,11 @@ static void ImGui::NavUpdate()
g.NavMoveRequestForward = ImGuiNavForward_ForwardActive;
}
- // Update PageUp/PageDown scroll
+ // Update PageUp/PageDown/Home/End scroll
+ // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
float nav_scoring_rect_offset_y = 0.0f;
if (nav_keyboard_active)
- nav_scoring_rect_offset_y = NavUpdatePageUpPageDown(allowed_dir_flags);
+ nav_scoring_rect_offset_y = NavUpdatePageUpPageDown();
// If we initiate a movement request and have no current NavId, we initiate a InitDefautRequest that will be used as a fallback if the direction fails to find a match
if (g.NavMoveDir != ImGuiDir_None)
@@ -7369,8 +8497,10 @@ static void ImGui::NavUpdate()
}
if (g.NavMoveRequest && g.NavId == 0)
{
+ //IMGUI_DEBUG_LOG("[Nav] NavInitRequest from move, window \"%s\", layer=%d\n", g.NavWindow->Name, g.NavLayer);
g.NavInitRequest = g.NavInitRequestFromMove = true;
- g.NavInitResultId = 0;
+ // Reassigning with same value, we're being explicit here.
+ g.NavInitResultId = 0; // -V1048
g.NavDisableHighlight = false;
}
NavUpdateAnyRequestFlag();
@@ -7380,13 +8510,13 @@ static void ImGui::NavUpdate()
{
// *Fallback* manual-scroll with Nav directional keys when window has no navigable item
ImGuiWindow* window = g.NavWindow;
- const float scroll_speed = ImFloor(window->CalcFontSize() * 100 * g.IO.DeltaTime + 0.5f); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
+ const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * g.IO.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll && g.NavMoveRequest)
{
if (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right)
- SetWindowScrollX(window, ImFloor(window->Scroll.x + ((g.NavMoveDir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
+ SetScrollX(window, ImFloor(window->Scroll.x + ((g.NavMoveDir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
if (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down)
- SetWindowScrollY(window, ImFloor(window->Scroll.y + ((g.NavMoveDir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
+ SetScrollY(window, ImFloor(window->Scroll.y + ((g.NavMoveDir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
}
// *Normal* Manual scroll with NavScrollXXX keys
@@ -7394,12 +8524,12 @@ static void ImGui::NavUpdate()
ImVec2 scroll_dir = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down, 1.0f/10.0f, 10.0f);
if (scroll_dir.x != 0.0f && window->ScrollbarX)
{
- SetWindowScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed));
+ SetScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed));
g.NavMoveFromClampedRefRect = true;
}
if (scroll_dir.y != 0.0f)
{
- SetWindowScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed));
+ SetScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed));
g.NavMoveFromClampedRefRect = true;
}
}
@@ -7413,13 +8543,13 @@ static void ImGui::NavUpdate()
if (g.NavMoveRequest && g.NavMoveFromClampedRefRect && g.NavLayer == 0)
{
ImGuiWindow* window = g.NavWindow;
- ImRect window_rect_rel(window->InnerMainRect.Min - window->Pos - ImVec2(1,1), window->InnerMainRect.Max - window->Pos + ImVec2(1,1));
+ ImRect window_rect_rel(window->InnerRect.Min - window->Pos - ImVec2(1,1), window->InnerRect.Max - window->Pos + ImVec2(1,1));
if (!window_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
{
float pad = window->CalcFontSize() * 0.5f;
window_rect_rel.Expand(ImVec2(-ImMin(window_rect_rel.GetWidth(), pad), -ImMin(window_rect_rel.GetHeight(), pad))); // Terrible approximation for the intent of starting navigation from first fully visible item
window->NavRectRel[g.NavLayer].ClipWith(window_rect_rel);
- g.NavId = 0;
+ g.NavId = g.NavFocusScopeId = 0;
}
g.NavMoveFromClampedRefRect = false;
}
@@ -7431,18 +8561,34 @@ static void ImGui::NavUpdate()
g.NavScoringRectScreen.Min.x = ImMin(g.NavScoringRectScreen.Min.x + 1.0f, g.NavScoringRectScreen.Max.x);
g.NavScoringRectScreen.Max.x = g.NavScoringRectScreen.Min.x;
IM_ASSERT(!g.NavScoringRectScreen.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allows us to remove extraneous ImFabs() calls in NavScoreItem().
- //g.OverlayDrawList.AddRect(g.NavScoringRectScreen.Min, g.NavScoringRectScreen.Max, IM_COL32(255,200,0,255)); // [DEBUG]
+ //GetForegroundDrawList()->AddRect(g.NavScoringRectScreen.Min, g.NavScoringRectScreen.Max, IM_COL32(255,200,0,255)); // [DEBUG]
g.NavScoringCount = 0;
#if IMGUI_DEBUG_NAV_RECTS
- if (g.NavWindow) { for (int layer = 0; layer < 2; layer++) GetOverlayDrawList()->AddRect(g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Min, g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Max, IM_COL32(255,200,0,255)); } // [DEBUG]
- if (g.NavWindow) { ImU32 col = (g.NavWindow->HiddenFrames == 0) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); g.OverlayDrawList.AddCircleFilled(p, 3.0f, col); g.OverlayDrawList.AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
+ if (g.NavWindow)
+ {
+ ImDrawList* draw_list = GetForegroundDrawList(g.NavWindow);
+ if (1) { for (int layer = 0; layer < 2; layer++) draw_list->AddRect(g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Min, g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Max, IM_COL32(255,200,0,255)); } // [DEBUG]
+ if (1) { ImU32 col = (!g.NavWindow->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
+ }
#endif
}
+// Apply result from previous frame navigation directional move request
static void ImGui::NavUpdateMoveResult()
{
- // Select which result to use
ImGuiContext& g = *GImGui;
+ if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0)
+ {
+ // In a situation when there is no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
+ if (g.NavId != 0)
+ {
+ g.NavDisableHighlight = false;
+ g.NavDisableMouseHover = true;
+ }
+ return;
+ }
+
+ // Select which result to use
ImGuiNavMoveResult* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
// PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
@@ -7459,72 +8605,110 @@ static void ImGui::NavUpdateMoveResult()
// Scroll to keep newly navigated item fully into view.
if (g.NavLayer == 0)
{
- ImRect rect_abs = ImRect(result->RectRel.Min + result->Window->Pos, result->RectRel.Max + result->Window->Pos);
- NavScrollToBringItemIntoView(result->Window, rect_abs);
-
- // Estimate upcoming scroll so we can offset our result position so mouse position can be applied immediately after in NavUpdate()
- ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(result->Window, false);
- ImVec2 delta_scroll = result->Window->Scroll - next_scroll;
- result->RectRel.Translate(delta_scroll);
+ ImVec2 delta_scroll;
+ if (g.NavMoveRequestFlags & ImGuiNavMoveFlags_ScrollToEdge)
+ {
+ float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
+ delta_scroll.y = result->Window->Scroll.y - scroll_target;
+ SetScrollY(result->Window, scroll_target);
+ }
+ else
+ {
+ ImRect rect_abs = ImRect(result->RectRel.Min + result->Window->Pos, result->RectRel.Max + result->Window->Pos);
+ delta_scroll = ScrollToBringRectIntoView(result->Window, rect_abs);
+ }
- // Also scroll parent window to keep us into view if necessary (we could/should technically recurse back the whole the parent hierarchy).
- if (result->Window->Flags & ImGuiWindowFlags_ChildWindow)
- NavScrollToBringItemIntoView(result->Window->ParentWindow, ImRect(rect_abs.Min + delta_scroll, rect_abs.Max + delta_scroll));
+ // Offset our result position so mouse position can be applied immediately after in NavUpdate()
+ result->RectRel.TranslateX(-delta_scroll.x);
+ result->RectRel.TranslateY(-delta_scroll.y);
}
- // Apply result from previous frame navigation directional move request
ClearActiveID();
g.NavWindow = result->Window;
- SetNavIDWithRectRel(result->ID, g.NavLayer, result->RectRel);
- g.NavJustMovedToId = result->ID;
+ if (g.NavId != result->ID)
+ {
+ // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
+ g.NavJustMovedToId = result->ID;
+ g.NavJustMovedToFocusScopeId = result->FocusScopeId;
+
+ }
+ SetNavIDWithRectRel(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
g.NavMoveFromClampedRefRect = false;
}
-static float ImGui::NavUpdatePageUpPageDown(int allowed_dir_flags)
+// Handle PageUp/PageDown/Home/End keys
+static float ImGui::NavUpdatePageUpPageDown()
{
ImGuiContext& g = *GImGui;
- if (g.NavMoveDir == ImGuiDir_None && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget && g.NavLayer == 0)
+ if (g.NavMoveDir != ImGuiDir_None || g.NavWindow == NULL)
+ return 0.0f;
+ if ((g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL || g.NavLayer != 0)
+ return 0.0f;
+
+ ImGuiWindow* window = g.NavWindow;
+ const bool page_up_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageUp]) && !IsActiveIdUsingKey(ImGuiKey_PageUp);
+ const bool page_down_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageDown]) && !IsActiveIdUsingKey(ImGuiKey_PageDown);
+ const bool home_pressed = IsKeyPressed(g.IO.KeyMap[ImGuiKey_Home]) && !IsActiveIdUsingKey(ImGuiKey_Home);
+ const bool end_pressed = IsKeyPressed(g.IO.KeyMap[ImGuiKey_End]) && !IsActiveIdUsingKey(ImGuiKey_End);
+ if (page_up_held != page_down_held || home_pressed != end_pressed) // If either (not both) are pressed
{
- ImGuiWindow* window = g.NavWindow;
- bool page_up_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageUp]) && (allowed_dir_flags & (1 << ImGuiDir_Up));
- bool page_down_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageDown]) && (allowed_dir_flags & (1 << ImGuiDir_Down));
- if ((page_up_held && !page_down_held) || (page_down_held && !page_up_held))
+ if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll)
+ {
+ // Fallback manual-scroll when window has no navigable item
+ if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true))
+ SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
+ else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true))
+ SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
+ else if (home_pressed)
+ SetScrollY(window, 0.0f);
+ else if (end_pressed)
+ SetScrollY(window, window->ScrollMax.y);
+ }
+ else
{
- if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll)
+ ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
+ const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
+ float nav_scoring_rect_offset_y = 0.0f;
+ if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true))
{
- // Fallback manual-scroll when window has no navigable item
- if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true))
- SetWindowScrollY(window, window->Scroll.y - window->InnerClipRect.GetHeight());
- else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true))
- SetWindowScrollY(window, window->Scroll.y + window->InnerClipRect.GetHeight());
+ nav_scoring_rect_offset_y = -page_offset_y;
+ g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)
+ g.NavMoveClipDir = ImGuiDir_Up;
+ g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
}
- else
+ else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true))
{
- const ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
- const float page_offset_y = ImMax(0.0f, window->InnerClipRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
- float nav_scoring_rect_offset_y = 0.0f;
- if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true))
- {
- nav_scoring_rect_offset_y = -page_offset_y;
- g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset, we intentionally request the opposite direction (so we can always land on the last item)
- g.NavMoveClipDir = ImGuiDir_Up;
- g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
- }
- else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true))
- {
- nav_scoring_rect_offset_y = +page_offset_y;
- g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset, we intentionally request the opposite direction (so we can always land on the last item)
- g.NavMoveClipDir = ImGuiDir_Down;
- g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
- }
- return nav_scoring_rect_offset_y;
+ nav_scoring_rect_offset_y = +page_offset_y;
+ g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)
+ g.NavMoveClipDir = ImGuiDir_Down;
+ g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
+ }
+ else if (home_pressed)
+ {
+ // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
+ // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdge flag, we don't scroll immediately to avoid scrolling happening before nav result.
+ // Preserve current horizontal position if we have any.
+ nav_rect_rel.Min.y = nav_rect_rel.Max.y = -window->Scroll.y;
+ if (nav_rect_rel.IsInverted())
+ nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
+ g.NavMoveDir = ImGuiDir_Down;
+ g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdge;
+ }
+ else if (end_pressed)
+ {
+ nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ScrollMax.y + window->SizeFull.y - window->Scroll.y;
+ if (nav_rect_rel.IsInverted())
+ nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
+ g.NavMoveDir = ImGuiDir_Up;
+ g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdge;
}
+ return nav_scoring_rect_offset_y;
}
}
return 0.0f;
}
-static int FindWindowFocusIndex(ImGuiWindow* window) // FIXME-OPT O(N)
+static int ImGui::FindWindowFocusIndex(ImGuiWindow* window) // FIXME-OPT O(N)
{
ImGuiContext& g = *GImGui;
for (int i = g.WindowsFocusOrder.Size-1; i >= 0; i--)
@@ -7549,7 +8733,7 @@ static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
return;
- const int i_current = FindWindowFocusIndex(g.NavWindowingTarget);
+ const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
if (!window_target)
window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
@@ -7558,14 +8742,16 @@ static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
g.NavWindowingToggleLayer = false;
}
-// Window management mode (hold to: change focus/move/resize, tap to: toggle menu layer)
+// Windowing management mode
+// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
+// Gamepad: Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
static void ImGui::NavUpdateWindowing()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* apply_focus_window = NULL;
bool apply_toggle_layer = false;
- ImGuiWindow* modal_window = GetFrontMostPopupModal();
+ ImGuiWindow* modal_window = GetTopMostPopupModal();
if (modal_window != NULL)
{
g.NavWindowingTarget = NULL;
@@ -7581,12 +8767,12 @@ static void ImGui::NavUpdateWindowing()
}
// Start CTRL-TAB or Square+L/R window selection
- bool start_windowing_with_gamepad = !g.NavWindowingTarget && IsNavInputPressed(ImGuiNavInput_Menu, ImGuiInputReadMode_Pressed);
+ bool start_windowing_with_gamepad = !g.NavWindowingTarget && IsNavInputTest(ImGuiNavInput_Menu, ImGuiInputReadMode_Pressed);
bool start_windowing_with_keyboard = !g.NavWindowingTarget && g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab) && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard);
if (start_windowing_with_gamepad || start_windowing_with_keyboard)
if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
{
- g.NavWindowingTarget = g.NavWindowingTargetAnim = window;
+ g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow; // FIXME-DOCK: Will need to use RootWindowDockStop
g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
g.NavWindowingToggleLayer = start_windowing_with_keyboard ? false : true;
g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_NavKeyboard : ImGuiInputSource_NavGamepad;
@@ -7600,14 +8786,14 @@ static void ImGui::NavUpdateWindowing()
g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
// Select window to focus
- const int focus_change_dir = (int)IsNavInputPressed(ImGuiNavInput_FocusPrev, ImGuiInputReadMode_RepeatSlow) - (int)IsNavInputPressed(ImGuiNavInput_FocusNext, ImGuiInputReadMode_RepeatSlow);
+ const int focus_change_dir = (int)IsNavInputTest(ImGuiNavInput_FocusPrev, ImGuiInputReadMode_RepeatSlow) - (int)IsNavInputTest(ImGuiNavInput_FocusNext, ImGuiInputReadMode_RepeatSlow);
if (focus_change_dir != 0)
{
NavUpdateWindowingHighlightWindow(focus_change_dir);
g.NavWindowingHighlightAlpha = 1.0f;
}
- // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered front-most)
+ // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
if (!IsNavInputDown(ImGuiNavInput_Menu))
{
g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
@@ -7632,7 +8818,9 @@ static void ImGui::NavUpdateWindowing()
// Keyboard: Press and Release ALT to toggle menu layer
// FIXME: We lack an explicit IO variable for "is the imgui window focused", so compare mouse validity to detect the common case of back-end clearing releases all keys on ALT-TAB
- if ((g.ActiveId == 0 || g.ActiveIdAllowOverlap) && IsNavInputPressed(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Released))
+ if (IsNavInputTest(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Pressed))
+ g.NavWindowingToggleLayer = true;
+ if ((g.ActiveId == 0 || g.ActiveIdAllowOverlap) && g.NavWindowingToggleLayer && IsNavInputTest(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Released))
if (IsMousePosValid(&g.IO.MousePos) == IsMousePosValid(&g.IO.MousePosPrev))
apply_toggle_layer = true;
@@ -7648,7 +8836,7 @@ static void ImGui::NavUpdateWindowing()
{
const float NAV_MOVE_SPEED = 800.0f;
const float move_speed = ImFloor(NAV_MOVE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); // FIXME: Doesn't code variable framerate very well
- g.NavWindowingTarget->RootWindow->Pos += move_delta * move_speed;
+ SetWindowPos(g.NavWindowingTarget->RootWindow, g.NavWindowingTarget->RootWindow->Pos + move_delta * move_speed, ImGuiCond_Always);
g.NavDisableMouseHover = true;
MarkIniSettingsDirty(g.NavWindowingTarget);
}
@@ -7657,17 +8845,18 @@ static void ImGui::NavUpdateWindowing()
// Apply final focus
if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
{
+ ClearActiveID();
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window);
- ClosePopupsOverWindow(apply_focus_window);
+ ClosePopupsOverWindow(apply_focus_window, false);
FocusWindow(apply_focus_window);
if (apply_focus_window->NavLastIds[0] == 0)
NavInitWindow(apply_focus_window, false);
// If the window only has a menu layer, select it directly
- if (apply_focus_window->DC.NavLayerActiveMask == (1 << 1))
- g.NavLayer = 1;
+ if (apply_focus_window->DC.NavLayerActiveMask == (1 << ImGuiNavLayer_Menu))
+ g.NavLayer = ImGuiNavLayer_Menu;
}
if (apply_focus_window)
g.NavWindowingTarget = NULL;
@@ -7677,7 +8866,10 @@ static void ImGui::NavUpdateWindowing()
{
// Move to parent menu if necessary
ImGuiWindow* new_nav_window = g.NavWindow;
- while ((new_nav_window->DC.NavLayerActiveMask & (1 << 1)) == 0 && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
+ while (new_nav_window->ParentWindow
+ && (new_nav_window->DC.NavLayerActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
+ && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
+ && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
new_nav_window = new_nav_window->ParentWindow;
if (new_nav_window != g.NavWindow)
{
@@ -7687,7 +8879,10 @@ static void ImGui::NavUpdateWindowing()
}
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
- NavRestoreLayer((g.NavWindow->DC.NavLayerActiveMask & (1 << 1)) ? (g.NavLayer ^ 1) : 0);
+
+ // When entering a regular menu bar with the Alt key, we always reinitialize the navigation ID.
+ const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayerActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
+ NavRestoreLayer(new_nav_layer);
}
}
@@ -7702,7 +8897,7 @@ static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
}
// Overlay displayed when using CTRL+TAB. Called by EndFrame().
-void ImGui::NavUpdateWindowingList()
+void ImGui::NavUpdateWindowingOverlay()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavWindowingTarget != NULL);
@@ -7730,328 +8925,6 @@ void ImGui::NavUpdateWindowingList()
PopStyleVar();
}
-//-----------------------------------------------------------------------------
-// [SECTION] COLUMNS
-// In the current version, Columns are very weak. Needs to be replaced with a more full-featured system.
-//-----------------------------------------------------------------------------
-
-void ImGui::NextColumn()
-{
- ImGuiWindow* window = GetCurrentWindow();
- if (window->SkipItems || window->DC.ColumnsSet == NULL)
- return;
-
- ImGuiContext& g = *GImGui;
- PopItemWidth();
- PopClipRect();
-
- ImGuiColumnsSet* columns = window->DC.ColumnsSet;
- columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);
- if (++columns->Current < columns->Count)
- {
- // Columns 1+ cancel out IndentX
- window->DC.ColumnsOffset.x = GetColumnOffset(columns->Current) - window->DC.Indent.x + g.Style.ItemSpacing.x;
- window->DrawList->ChannelsSetCurrent(columns->Current);
- }
- else
- {
- window->DC.ColumnsOffset.x = 0.0f;
- window->DrawList->ChannelsSetCurrent(0);
- columns->Current = 0;
- columns->LineMinY = columns->LineMaxY;
- }
- window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
- window->DC.CursorPos.y = columns->LineMinY;
- window->DC.CurrentLineSize = ImVec2(0.0f, 0.0f);
- window->DC.CurrentLineTextBaseOffset = 0.0f;
-
- PushColumnClipRect();
- PushItemWidth(GetColumnWidth() * 0.65f); // FIXME: Move on columns setup
-}
-
-int ImGui::GetColumnIndex()
-{
- ImGuiWindow* window = GetCurrentWindowRead();
- return window->DC.ColumnsSet ? window->DC.ColumnsSet->Current : 0;
-}
-
-int ImGui::GetColumnsCount()
-{
- ImGuiWindow* window = GetCurrentWindowRead();
- return window->DC.ColumnsSet ? window->DC.ColumnsSet->Count : 1;
-}
-
-static float OffsetNormToPixels(const ImGuiColumnsSet* columns, float offset_norm)
-{
- return offset_norm * (columns->MaxX - columns->MinX);
-}
-
-static float PixelsToOffsetNorm(const ImGuiColumnsSet* columns, float offset)
-{
- return offset / (columns->MaxX - columns->MinX);
-}
-
-static inline float GetColumnsRectHalfWidth() { return 4.0f; }
-
-static float GetDraggedColumnOffset(ImGuiColumnsSet* columns, int column_index)
-{
- // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing
- // window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning.
- ImGuiContext& g = *GImGui;
- ImGuiWindow* window = g.CurrentWindow;
- IM_ASSERT(column_index > 0); // We are not supposed to drag column 0.
- IM_ASSERT(g.ActiveId == columns->ID + ImGuiID(column_index));
-
- float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x + GetColumnsRectHalfWidth() - window->Pos.x;
- x = ImMax(x, ImGui::GetColumnOffset(column_index - 1) + g.Style.ColumnsMinSpacing);
- if ((columns->Flags & ImGuiColumnsFlags_NoPreserveWidths))
- x = ImMin(x, ImGui::GetColumnOffset(column_index + 1) - g.Style.ColumnsMinSpacing);
-
- return x;
-}
-
-float ImGui::GetColumnOffset(int column_index)
-{
- ImGuiWindow* window = GetCurrentWindowRead();
- ImGuiColumnsSet* columns = window->DC.ColumnsSet;
- IM_ASSERT(columns != NULL);
-
- if (column_index < 0)
- column_index = columns->Current;
- IM_ASSERT(column_index < columns->Columns.Size);
-
- const float t = columns->Columns[column_index].OffsetNorm;
- const float x_offset = ImLerp(columns->MinX, columns->MaxX, t);
- return x_offset;
-}
-
-static float GetColumnWidthEx(ImGuiColumnsSet* columns, int column_index, bool before_resize = false)
-{
- if (column_index < 0)
- column_index = columns->Current;
-
- float offset_norm;
- if (before_resize)
- offset_norm = columns->Columns[column_index + 1].OffsetNormBeforeResize - columns->Columns[column_index].OffsetNormBeforeResize;
- else
- offset_norm = columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm;
- return OffsetNormToPixels(columns, offset_norm);
-}
-
-float ImGui::GetColumnWidth(int column_index)
-{
- ImGuiWindow* window = GetCurrentWindowRead();
- ImGuiColumnsSet* columns = window->DC.ColumnsSet;
- IM_ASSERT(columns != NULL);
-
- if (column_index < 0)
- column_index = columns->Current;
- return OffsetNormToPixels(columns, columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm);
-}
-
-void ImGui::SetColumnOffset(int column_index, float offset)
-{
- ImGuiContext& g = *GImGui;
- ImGuiWindow* window = g.CurrentWindow;
- ImGuiColumnsSet* columns = window->DC.ColumnsSet;
- IM_ASSERT(columns != NULL);
-
- if (column_index < 0)
- column_index = columns->Current;
- IM_ASSERT(column_index < columns->Columns.Size);
-
- const bool preserve_width = !(columns->Flags & ImGuiColumnsFlags_NoPreserveWidths) && (column_index < columns->Count-1);
- const float width = preserve_width ? GetColumnWidthEx(columns, column_index, columns->IsBeingResized) : 0.0f;
-
- if (!(columns->Flags & ImGuiColumnsFlags_NoForceWithinWindow))
- offset = ImMin(offset, columns->MaxX - g.Style.ColumnsMinSpacing * (columns->Count - column_index));
- columns->Columns[column_index].OffsetNorm = PixelsToOffsetNorm(columns, offset - columns->MinX);
-
- if (preserve_width)
- SetColumnOffset(column_index + 1, offset + ImMax(g.Style.ColumnsMinSpacing, width));
-}
-
-void ImGui::SetColumnWidth(int column_index, float width)
-{
- ImGuiWindow* window = GetCurrentWindowRead();
- ImGuiColumnsSet* columns = window->DC.ColumnsSet;
- IM_ASSERT(columns != NULL);
-
- if (column_index < 0)
- column_index = columns->Current;
- SetColumnOffset(column_index + 1, GetColumnOffset(column_index) + width);
-}
-
-void ImGui::PushColumnClipRect(int column_index)
-{
- ImGuiWindow* window = GetCurrentWindowRead();
- ImGuiColumnsSet* columns = window->DC.ColumnsSet;
- if (column_index < 0)
- column_index = columns->Current;
-
- PushClipRect(columns->Columns[column_index].ClipRect.Min, columns->Columns[column_index].ClipRect.Max, false);
-}
-
-static ImGuiColumnsSet* FindOrAddColumnsSet(ImGuiWindow* window, ImGuiID id)
-{
- for (int n = 0; n < window->ColumnsStorage.Size; n++)
- if (window->ColumnsStorage[n].ID == id)
- return &window->ColumnsStorage[n];
-
- window->ColumnsStorage.push_back(ImGuiColumnsSet());
- ImGuiColumnsSet* columns = &window->ColumnsStorage.back();
- columns->ID = id;
- return columns;
-}
-
-void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlags flags)
-{
- ImGuiContext& g = *GImGui;
- ImGuiWindow* window = GetCurrentWindow();
-
- IM_ASSERT(columns_count > 1);
- IM_ASSERT(window->DC.ColumnsSet == NULL); // Nested columns are currently not supported
-
- // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget.
- // In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer.
- PushID(0x11223347 + (str_id ? 0 : columns_count));
- ImGuiID id = window->GetID(str_id ? str_id : "columns");
- PopID();
-
- // Acquire storage for the columns set
- ImGuiColumnsSet* columns = FindOrAddColumnsSet(window, id);
- IM_ASSERT(columns->ID == id);
- columns->Current = 0;
- columns->Count = columns_count;
- columns->Flags = flags;
- window->DC.ColumnsSet = columns;
-
- // Set state for first column
- const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? (window->SizeContentsExplicit.x) : (window->InnerClipRect.Max.x - window->Pos.x);
- columns->MinX = window->DC.Indent.x - g.Style.ItemSpacing.x; // Lock our horizontal range
- columns->MaxX = ImMax(content_region_width - window->Scroll.x, columns->MinX + 1.0f);
- columns->StartPosY = window->DC.CursorPos.y;
- columns->StartMaxPosX = window->DC.CursorMaxPos.x;
- columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y;
- window->DC.ColumnsOffset.x = 0.0f;
- window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
-
- // Clear data if columns count changed
- if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1)
- columns->Columns.resize(0);
-
- // Initialize defaults
- columns->IsFirstFrame = (columns->Columns.Size == 0);
- if (columns->Columns.Size == 0)
- {
- columns->Columns.reserve(columns_count + 1);
- for (int n = 0; n < columns_count + 1; n++)
- {
- ImGuiColumnData column;
- column.OffsetNorm = n / (float)columns_count;
- columns->Columns.push_back(column);
- }
- }
-
- for (int n = 0; n < columns_count; n++)
- {
- // Compute clipping rectangle
- ImGuiColumnData* column = &columns->Columns[n];
- float clip_x1 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n) - 1.0f);
- float clip_x2 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n + 1) - 1.0f);
- column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX);
- column->ClipRect.ClipWith(window->ClipRect);
- }
-
- window->DrawList->ChannelsSplit(columns->Count);
- PushColumnClipRect();
- PushItemWidth(GetColumnWidth() * 0.65f);
-}
-
-void ImGui::EndColumns()
-{
- ImGuiContext& g = *GImGui;
- ImGuiWindow* window = GetCurrentWindow();
- ImGuiColumnsSet* columns = window->DC.ColumnsSet;
- IM_ASSERT(columns != NULL);
-
- PopItemWidth();
- PopClipRect();
- window->DrawList->ChannelsMerge();
-
- columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);
- window->DC.CursorPos.y = columns->LineMaxY;
- if (!(columns->Flags & ImGuiColumnsFlags_GrowParentContentsSize))
- window->DC.CursorMaxPos.x = columns->StartMaxPosX; // Restore cursor max pos, as columns don't grow parent
-
- // Draw columns borders and handle resize
- bool is_being_resized = false;
- if (!(columns->Flags & ImGuiColumnsFlags_NoBorder) && !window->SkipItems)
- {
- const float y1 = columns->StartPosY;
- const float y2 = window->DC.CursorPos.y;
- int dragging_column = -1;
- for (int n = 1; n < columns->Count; n++)
- {
- float x = window->Pos.x + GetColumnOffset(n);
- const ImGuiID column_id = columns->ID + ImGuiID(n);
- const float column_hw = GetColumnsRectHalfWidth(); // Half-width for interaction
- const ImRect column_rect(ImVec2(x - column_hw, y1), ImVec2(x + column_hw, y2));
- KeepAliveID(column_id);
- if (IsClippedEx(column_rect, column_id, false))
- continue;
-
- bool hovered = false, held = false;
- if (!(columns->Flags & ImGuiColumnsFlags_NoResize))
- {
- ButtonBehavior(column_rect, column_id, &hovered, &held);
- if (hovered || held)
- g.MouseCursor = ImGuiMouseCursor_ResizeEW;
- if (held && !(columns->Columns[n].Flags & ImGuiColumnsFlags_NoResize))
- dragging_column = n;
- }
-
- // Draw column (we clip the Y boundaries CPU side because very long triangles are mishandled by some GPU drivers.)
- const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator);
- const float xi = (float)(int)x;
- window->DrawList->AddLine(ImVec2(xi, ImMax(y1 + 1.0f, window->ClipRect.Min.y)), ImVec2(xi, ImMin(y2, window->ClipRect.Max.y)), col);
- }
-
- // Apply dragging after drawing the column lines, so our rendered lines are in sync with how items were displayed during the frame.
- if (dragging_column != -1)
- {
- if (!columns->IsBeingResized)
- for (int n = 0; n < columns->Count + 1; n++)
- columns->Columns[n].OffsetNormBeforeResize = columns->Columns[n].OffsetNorm;
- columns->IsBeingResized = is_being_resized = true;
- float x = GetDraggedColumnOffset(columns, dragging_column);
- SetColumnOffset(dragging_column, x);
- }
- }
- columns->IsBeingResized = is_being_resized;
-
- window->DC.ColumnsSet = NULL;
- window->DC.ColumnsOffset.x = 0.0f;
- window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
-}
-
-// [2018-03: This is currently the only public API, while we are working on making BeginColumns/EndColumns user-facing]
-void ImGui::Columns(int columns_count, const char* id, bool border)
-{
- ImGuiWindow* window = GetCurrentWindow();
- IM_ASSERT(columns_count >= 1);
-
- ImGuiColumnsFlags flags = (border ? 0 : ImGuiColumnsFlags_NoBorder);
- //flags |= ImGuiColumnsFlags_NoPreserveWidths; // NB: Legacy behavior
- if (window->DC.ColumnsSet != NULL && window->DC.ColumnsSet->Count == columns_count && window->DC.ColumnsSet->Flags == flags)
- return;
-
- if (window->DC.ColumnsSet != NULL)
- EndColumns();
-
- if (columns_count != 1)
- BeginColumns(id, columns_count, flags);
-}
//-----------------------------------------------------------------------------
// [SECTION] DRAG AND DROP
@@ -8062,7 +8935,7 @@ void ImGui::ClearDragDrop()
ImGuiContext& g = *GImGui;
g.DragDropActive = false;
g.DragDropPayload.Clear();
- g.DragDropAcceptFlags = 0;
+ g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
g.DragDropAcceptFrameCount = -1;
@@ -8081,7 +8954,7 @@ bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
bool source_drag_active = false;
ImGuiID source_id = 0;
ImGuiID source_parent_id = 0;
- int mouse_button = 0;
+ ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
if (!(flags & ImGuiDragDropFlags_SourceExtern))
{
source_id = window->DC.LastItemId;
@@ -8100,16 +8973,16 @@ bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
return false;
}
+ // Early out
+ if ((window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
+ return false;
+
// Magic fallback (=somehow reprehensible) to handle items with no assigned ID, e.g. Text(), Image()
// We build a throwaway ID based on current ID stack + relative AABB of items in window.
// THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
// We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
- bool is_hovered = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) != 0;
- if (!is_hovered && (g.ActiveId == 0 || g.ActiveIdWindow != window))
- return false;
source_id = window->DC.LastItemId = window->GetIDFromRectangle(window->DC.LastItemRect);
- if (is_hovered)
- SetHoveredID(source_id);
+ bool is_hovered = ItemHoverable(window->DC.LastItemRect, source_id);
if (is_hovered && g.IO.MouseClicked[mouse_button])
{
SetActiveID(source_id, window);
@@ -8130,7 +9003,7 @@ bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
else
{
window = NULL;
- source_id = ImHash("#SourceExtern", 0);
+ source_id = ImHashStr("#SourceExtern");
source_drag_active = true;
}
@@ -8153,13 +9026,13 @@ bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
{
// Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
- // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
+ // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
BeginTooltip();
- if (g.DragDropActive && g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
+ if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
{
ImGuiWindow* tooltip_window = g.CurrentWindow;
tooltip_window->SkipItems = true;
- tooltip_window->HiddenFramesRegular = 1;
+ tooltip_window->HiddenFramesCanSkipItems = 1;
}
}
@@ -8346,9 +9219,13 @@ void ImGui::EndDragDropTarget()
g.DragDropWithinSourceOrTarget = false;
}
+
//-----------------------------------------------------------------------------
// [SECTION] LOGGING/CAPTURING
//-----------------------------------------------------------------------------
+// All text output from the interface can be captured into tty/file/clipboard.
+// By default, tree nodes are automatically opened during logging.
+//-----------------------------------------------------------------------------
// Pass text data straight to log (without being displayed)
void ImGui::LogText(const char* fmt, ...)
@@ -8360,9 +9237,15 @@ void ImGui::LogText(const char* fmt, ...)
va_list args;
va_start(args, fmt);
if (g.LogFile)
- vfprintf(g.LogFile, fmt, args);
+ {
+ g.LogBuffer.Buf.resize(0);
+ g.LogBuffer.appendfv(fmt, args);
+ ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
+ }
else
- g.LogClipboard.appendfv(fmt, args);
+ {
+ g.LogBuffer.appendfv(fmt, args);
+ }
va_end(args);
}
@@ -8376,17 +9259,20 @@ void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char*
if (!text_end)
text_end = FindRenderedTextEnd(text, text_end);
- const bool log_new_line = ref_pos && (ref_pos->y > window->DC.LogLinePosY + 1);
+ const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + 1);
if (ref_pos)
- window->DC.LogLinePosY = ref_pos->y;
+ g.LogLinePosY = ref_pos->y;
+ if (log_new_line)
+ g.LogLineFirstItem = true;
const char* text_remaining = text;
- if (g.LogStartDepth > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth
- g.LogStartDepth = window->DC.TreeDepth;
- const int tree_depth = (window->DC.TreeDepth - g.LogStartDepth);
+ if (g.LogDepthRef > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth
+ g.LogDepthRef = window->DC.TreeDepth;
+ const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
for (;;)
{
// Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry.
+ // We don't add a trailing \n to allow a subsequent item on the same line to be captured.
const char* line_start = text_remaining;
const char* line_end = ImStreolRange(line_start, text_end);
const bool is_first_line = (line_start == text);
@@ -8395,9 +9281,18 @@ void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char*
{
const int char_count = (int)(line_end - line_start);
if (log_new_line || !is_first_line)
- LogText(IM_NEWLINE "%*s%.*s", tree_depth*4, "", char_count, line_start);
+ LogText(IM_NEWLINE "%*s%.*s", tree_depth * 4, "", char_count, line_start);
+ else if (g.LogLineFirstItem)
+ LogText("%*s%.*s", tree_depth * 4, "", char_count, line_start);
else
LogText(" %.*s", char_count, line_start);
+ g.LogLineFirstItem = false;
+ }
+ else if (log_new_line)
+ {
+ // An empty "" string at a different Y position should output a carriage return.
+ LogText(IM_NEWLINE);
+ break;
}
if (is_last_line)
@@ -8406,64 +9301,74 @@ void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char*
}
}
-// Start logging ImGui output to TTY
-void ImGui::LogToTTY(int max_depth)
+// Start logging/capturing text output
+void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
{
ImGuiContext& g = *GImGui;
- if (g.LogEnabled)
- return;
ImGuiWindow* window = g.CurrentWindow;
-
+ IM_ASSERT(g.LogEnabled == false);
IM_ASSERT(g.LogFile == NULL);
- g.LogFile = stdout;
+ IM_ASSERT(g.LogBuffer.empty());
g.LogEnabled = true;
- g.LogStartDepth = window->DC.TreeDepth;
- if (max_depth >= 0)
- g.LogAutoExpandMaxDepth = max_depth;
+ g.LogType = type;
+ g.LogDepthRef = window->DC.TreeDepth;
+ g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
+ g.LogLinePosY = FLT_MAX;
+ g.LogLineFirstItem = true;
}
-// Start logging ImGui output to given file
-void ImGui::LogToFile(int max_depth, const char* filename)
+void ImGui::LogToTTY(int auto_open_depth)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
- ImGuiWindow* window = g.CurrentWindow;
+ IM_UNUSED(auto_open_depth);
+#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
+ LogBegin(ImGuiLogType_TTY, auto_open_depth);
+ g.LogFile = stdout;
+#endif
+}
+// Start logging/capturing text output to given file
+void ImGui::LogToFile(int auto_open_depth, const char* filename)
+{
+ ImGuiContext& g = *GImGui;
+ if (g.LogEnabled)
+ return;
+
+ // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
+ // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
+ // By opening the file in binary mode "ab" we have consistent output everywhere.
if (!filename)
- {
filename = g.IO.LogFilename;
- if (!filename)
- return;
- }
-
- IM_ASSERT(g.LogFile == NULL);
- g.LogFile = ImFileOpen(filename, "ab");
- if (!g.LogFile)
+ if (!filename || !filename[0])
+ return;
+ ImFileHandle f = ImFileOpen(filename, "ab");
+ if (!f)
{
- IM_ASSERT(g.LogFile != NULL); // Consider this an error
+ IM_ASSERT(0);
return;
}
- g.LogEnabled = true;
- g.LogStartDepth = window->DC.TreeDepth;
- if (max_depth >= 0)
- g.LogAutoExpandMaxDepth = max_depth;
+
+ LogBegin(ImGuiLogType_File, auto_open_depth);
+ g.LogFile = f;
}
-// Start logging ImGui output to clipboard
-void ImGui::LogToClipboard(int max_depth)
+// Start logging/capturing text output to clipboard
+void ImGui::LogToClipboard(int auto_open_depth)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
- ImGuiWindow* window = g.CurrentWindow;
+ LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
+}
- IM_ASSERT(g.LogFile == NULL);
- g.LogFile = NULL;
- g.LogEnabled = true;
- g.LogStartDepth = window->DC.TreeDepth;
- if (max_depth >= 0)
- g.LogAutoExpandMaxDepth = max_depth;
+void ImGui::LogToBuffer(int auto_open_depth)
+{
+ ImGuiContext& g = *GImGui;
+ if (g.LogEnabled)
+ return;
+ LogBegin(ImGuiLogType_Buffer, auto_open_depth);
}
void ImGui::LogFinish()
@@ -8473,45 +9378,60 @@ void ImGui::LogFinish()
return;
LogText(IM_NEWLINE);
- if (g.LogFile != NULL)
+ switch (g.LogType)
{
- if (g.LogFile == stdout)
- fflush(g.LogFile);
- else
- fclose(g.LogFile);
- g.LogFile = NULL;
- }
- if (g.LogClipboard.size() > 1)
- {
- SetClipboardText(g.LogClipboard.begin());
- g.LogClipboard.clear();
+ case ImGuiLogType_TTY:
+#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
+ fflush(g.LogFile);
+#endif
+ break;
+ case ImGuiLogType_File:
+ ImFileClose(g.LogFile);
+ break;
+ case ImGuiLogType_Buffer:
+ break;
+ case ImGuiLogType_Clipboard:
+ if (!g.LogBuffer.empty())
+ SetClipboardText(g.LogBuffer.begin());
+ break;
+ case ImGuiLogType_None:
+ IM_ASSERT(0);
+ break;
}
+
g.LogEnabled = false;
+ g.LogType = ImGuiLogType_None;
+ g.LogFile = NULL;
+ g.LogBuffer.clear();
}
// Helper to display logging buttons
+// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
void ImGui::LogButtons()
{
ImGuiContext& g = *GImGui;
PushID("LogButtons");
+#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
const bool log_to_tty = Button("Log To TTY"); SameLine();
+#else
+ const bool log_to_tty = false;
+#endif
const bool log_to_file = Button("Log To File"); SameLine();
const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
- PushItemWidth(80.0f);
PushAllowKeyboardFocus(false);
- SliderInt("Depth", &g.LogAutoExpandMaxDepth, 0, 9, NULL);
+ SetNextItemWidth(80.0f);
+ SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
PopAllowKeyboardFocus();
- PopItemWidth();
PopID();
// Start logging at the end of the function so that the buttons don't appear in the log
if (log_to_tty)
- LogToTTY(g.LogAutoExpandMaxDepth);
+ LogToTTY();
if (log_to_file)
- LogToFile(g.LogAutoExpandMaxDepth, g.IO.LogFilename);
+ LogToFile();
if (log_to_clipboard)
- LogToClipboard(g.LogAutoExpandMaxDepth);
+ LogToClipboard();
}
//-----------------------------------------------------------------------------
@@ -8536,22 +9456,41 @@ void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
{
ImGuiContext& g = *GImGui;
- g.SettingsWindows.push_back(ImGuiWindowSettings());
- ImGuiWindowSettings* settings = &g.SettingsWindows.back();
- settings->Name = ImStrdup(name);
- settings->ID = ImHash(name, 0);
+
+#if !IMGUI_DEBUG_INI_SETTINGS
+ // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
+ // Preserve the full string when IMGUI_DEBUG_INI_SETTINGS is set to make .ini inspection easier.
+ if (const char* p = strstr(name, "###"))
+ name = p;
+#endif
+ const size_t name_len = strlen(name);
+
+ // Allocate chunk
+ const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
+ ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
+ IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
+ settings->ID = ImHashStr(name, name_len);
+ memcpy(settings->GetName(), name, name_len + 1); // Store with zero terminator
+
return settings;
}
ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id)
{
ImGuiContext& g = *GImGui;
- for (int i = 0; i != g.SettingsWindows.Size; i++)
- if (g.SettingsWindows[i].ID == id)
- return &g.SettingsWindows[i];
+ for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
+ if (settings->ID == id)
+ return settings;
return NULL;
}
+ImGuiWindowSettings* ImGui::FindOrCreateWindowSettings(const char* name)
+{
+ if (ImGuiWindowSettings* settings = FindWindowSettings(ImHashStr(name)))
+ return settings;
+ return CreateNewWindowSettings(name);
+}
+
void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
{
size_t file_data_size = 0;
@@ -8559,13 +9498,13 @@ void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
if (!file_data)
return;
LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
- ImGui::MemFree(file_data);
+ IM_FREE(file_data);
}
ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
{
ImGuiContext& g = *GImGui;
- const ImGuiID type_hash = ImHash(type_name, 0, 0);
+ const ImGuiID type_hash = ImHashStr(type_name);
for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
if (g.SettingsHandlers[handler_n].TypeHash == type_hash)
return &g.SettingsHandlers[handler_n];
@@ -8583,7 +9522,7 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
// For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
if (ini_size == 0)
ini_size = strlen(ini_data);
- char* buf = (char*)ImGui::MemAlloc(ini_size + 1);
+ char* buf = (char*)IM_ALLOC(ini_size + 1);
char* buf_end = buf + ini_size;
memcpy(buf, ini_data, ini_size);
buf[ini_size] = 0;
@@ -8609,18 +9548,12 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
line_end[-1] = 0;
const char* name_end = line_end - 1;
const char* type_start = line + 1;
- char* type_end = (char*)(intptr_t)ImStrchrRange(type_start, name_end, ']');
+ char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
if (!type_end || !name_start)
- {
- name_start = type_start; // Import legacy entries that have no type
- type_start = "Window";
- }
- else
- {
- *type_end = 0; // Overwrite first ']'
- name_start++; // Skip second '['
- }
+ continue;
+ *type_end = 0; // Overwrite first ']'
+ name_start++; // Skip second '['
entry_handler = FindSettingsHandler(type_start);
entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
}
@@ -8630,7 +9563,7 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
}
}
- ImGui::MemFree(buf);
+ IM_FREE(buf);
g.SettingsLoaded = true;
}
@@ -8643,11 +9576,11 @@ void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
size_t ini_data_size = 0;
const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
- FILE* f = ImFileOpen(ini_filename, "wt");
+ ImFileHandle f = ImFileOpen(ini_filename, "wt");
if (!f)
return;
- fwrite(ini_data, sizeof(char), ini_data_size, f);
- fclose(f);
+ ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
+ ImFileClose(f);
}
// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
@@ -8667,70 +9600,80 @@ const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
return g.SettingsIniData.c_str();
}
-static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
+static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
{
- ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHash(name, 0));
+ ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHashStr(name));
if (!settings)
settings = ImGui::CreateNewWindowSettings(name);
return (void*)settings;
}
-static void SettingsHandlerWindow_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
+static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
{
ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
- float x, y;
+ int x, y;
int i;
- if (sscanf(line, "Pos=%f,%f", &x, &y) == 2) settings->Pos = ImVec2(x, y);
- else if (sscanf(line, "Size=%f,%f", &x, &y) == 2) settings->Size = ImMax(ImVec2(x, y), GImGui->Style.WindowMinSize);
+ if (sscanf(line, "Pos=%i,%i", &x, &y) == 2) settings->Pos = ImVec2ih((short)x, (short)y);
+ else if (sscanf(line, "Size=%i,%i", &x, &y) == 2) settings->Size = ImVec2ih((short)x, (short)y);
else if (sscanf(line, "Collapsed=%d", &i) == 1) settings->Collapsed = (i != 0);
}
-static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
+static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
{
// Gather data from windows that were active during this session
// (if a window wasn't opened in this session we preserve its settings)
- ImGuiContext& g = *imgui_ctx;
+ ImGuiContext& g = *ctx;
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
continue;
- ImGuiWindowSettings* settings = (window->SettingsIdx != -1) ? &g.SettingsWindows[window->SettingsIdx] : ImGui::FindWindowSettings(window->ID);
+ ImGuiWindowSettings* settings = (window->SettingsOffset != -1) ? g.SettingsWindows.ptr_from_offset(window->SettingsOffset) : ImGui::FindWindowSettings(window->ID);
if (!settings)
{
settings = ImGui::CreateNewWindowSettings(window->Name);
- window->SettingsIdx = g.SettingsWindows.index_from_pointer(settings);
+ window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
}
IM_ASSERT(settings->ID == window->ID);
- settings->Pos = window->Pos;
- settings->Size = window->SizeFull;
+ settings->Pos = ImVec2ih((short)window->Pos.x, (short)window->Pos.y);
+ settings->Size = ImVec2ih((short)window->SizeFull.x, (short)window->SizeFull.y);
settings->Collapsed = window->Collapsed;
}
// Write to text buffer
- buf->reserve(buf->size() + g.SettingsWindows.Size * 96); // ballpark reserve
- for (int i = 0; i != g.SettingsWindows.Size; i++)
+ buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
+ for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
{
- const ImGuiWindowSettings* settings = &g.SettingsWindows[i];
- if (settings->Pos.x == FLT_MAX)
- continue;
- const char* name = settings->Name;
- if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
- name = p;
- buf->appendf("[%s][%s]\n", handler->TypeName, name);
- buf->appendf("Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y);
- buf->appendf("Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y);
+ const char* settings_name = settings->GetName();
+ buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
+ buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
+ buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
buf->appendf("Collapsed=%d\n", settings->Collapsed);
- buf->appendf("\n");
+ buf->append("\n");
}
}
+
+//-----------------------------------------------------------------------------
+// [SECTION] VIEWPORTS, PLATFORM WINDOWS
+//-----------------------------------------------------------------------------
+
+// (this section is filled in the 'docking' branch)
+
+
+//-----------------------------------------------------------------------------
+// [SECTION] DOCKING
+//-----------------------------------------------------------------------------
+
+// (this section is filled in the 'docking' branch)
+
+
//-----------------------------------------------------------------------------
// [SECTION] PLATFORM DEPENDENT HELPERS
//-----------------------------------------------------------------------------
-#if defined(_WIN32) && !defined(_WINDOWS_) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS))
+#if defined(_WIN32) && !defined(_WINDOWS_) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS))
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
@@ -8739,15 +9682,21 @@ static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSetting
#else
#include <windows.h>
#endif
+#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have Win32 functions
+#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
+#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
+#endif
+#elif defined(__APPLE__)
+#include <TargetConditionals.h>
#endif
-// Win32 API clipboard implementation
-#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
+#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
#ifdef _MSC_VER
#pragma comment(lib, "user32")
#endif
+// Win32 clipboard implementation
static const char* GetClipboardTextFn_DefaultImpl(void*)
{
static ImVector<char> buf_local;
@@ -8791,16 +9740,67 @@ static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
::CloseClipboard();
}
+#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
+
+#include <Carbon/Carbon.h> // Use old API to avoid need for separate .mm file
+static PasteboardRef main_clipboard = 0;
+
+// OSX clipboard implementation
+// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
+static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
+{
+ if (!main_clipboard)
+ PasteboardCreate(kPasteboardClipboard, &main_clipboard);
+ PasteboardClear(main_clipboard);
+ CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
+ if (cf_data)
+ {
+ PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
+ CFRelease(cf_data);
+ }
+}
+
+static const char* GetClipboardTextFn_DefaultImpl(void*)
+{
+ if (!main_clipboard)
+ PasteboardCreate(kPasteboardClipboard, &main_clipboard);
+ PasteboardSynchronize(main_clipboard);
+
+ ItemCount item_count = 0;
+ PasteboardGetItemCount(main_clipboard, &item_count);
+ for (ItemCount i = 0; i < item_count; i++)
+ {
+ PasteboardItemID item_id = 0;
+ PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
+ CFArrayRef flavor_type_array = 0;
+ PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
+ for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
+ {
+ CFDataRef cf_data;
+ if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
+ {
+ static ImVector<char> clipboard_text;
+ int length = (int)CFDataGetLength(cf_data);
+ clipboard_text.resize(length + 1);
+ CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)clipboard_text.Data);
+ clipboard_text[length] = 0;
+ CFRelease(cf_data);
+ return clipboard_text.Data;
+ }
+ }
+ }
+ return NULL;
+}
+
#else
-// Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers
+// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
static const char* GetClipboardTextFn_DefaultImpl(void*)
{
ImGuiContext& g = *GImGui;
return g.PrivateClipboard.empty() ? NULL : g.PrivateClipboard.begin();
}
-// Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
{
ImGuiContext& g = *GImGui;
@@ -8814,7 +9814,7 @@ static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
#endif
// Win32 API IME support (for Asian languages, etc.)
-#if defined(_WIN32) && !defined(__GNUC__) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
+#if defined(_WIN32) && !defined(__GNUC__) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
#include <imm.h>
#ifdef _MSC_VER
@@ -8824,7 +9824,8 @@ static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y)
{
// Notify OS Input Method Editor of text input position
- if (HWND hwnd = (HWND)GImGui->IO.ImeWindowHandle)
+ ImGuiIO& io = ImGui::GetIO();
+ if (HWND hwnd = (HWND)io.ImeWindowHandle)
if (HIMC himc = ::ImmGetContext(hwnd))
{
COMPOSITIONFORM cf;
@@ -8846,46 +9847,96 @@ static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {}
// [SECTION] METRICS/DEBUG WINDOW
//-----------------------------------------------------------------------------
+#ifndef IMGUI_DISABLE_METRICS_WINDOW
+// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
+static void MetricsHelpMarker(const char* desc)
+{
+ ImGui::TextDisabled("(?)");
+ if (ImGui::IsItemHovered())
+ {
+ ImGui::BeginTooltip();
+ ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
+ ImGui::TextUnformatted(desc);
+ ImGui::PopTextWrapPos();
+ ImGui::EndTooltip();
+ }
+}
+
void ImGui::ShowMetricsWindow(bool* p_open)
{
- if (!ImGui::Begin("ImGui Metrics", p_open))
+ if (!ImGui::Begin("Dear ImGui Metrics", p_open))
{
ImGui::End();
return;
}
- static bool show_draw_cmd_clip_rects = true;
- static bool show_window_begin_order = false;
+
+ // Debugging enums
+ enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
+ const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentRegionRect" };
+ enum { TRT_OuterRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersDesired, TRT_ColumnsContentRowsFrozen, TRT_ColumnsContentRowsUnfrozen, TRT_Count }; // Tables Rect Type
+ const char* trt_rects_names[TRT_Count] = { "OuterRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersDesired", "ColumnsContentRowsFrozen", "ColumnsContentRowsUnfrozen" };
+
+ // State
+ static bool show_windows_rects = false;
+ static int show_windows_rect_type = WRT_WorkRect;
+ static bool show_windows_begin_order = false;
+ static bool show_tables_rects = false;
+ static int show_tables_rect_type = TRT_WorkRect;
+ static bool show_drawcmd_details = true;
+
+ // Basic info
+ ImGuiContext& g = *GImGui;
ImGuiIO& io = ImGui::GetIO();
ImGui::Text("Dear ImGui %s", ImGui::GetVersion());
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
ImGui::Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
ImGui::Text("%d active windows (%d visible)", io.MetricsActiveWindows, io.MetricsRenderWindows);
- ImGui::Text("%d allocations", io.MetricsActiveAllocations);
- ImGui::Checkbox("Show clipping rectangles when hovering draw commands", &show_draw_cmd_clip_rects);
- ImGui::Checkbox("Ctrl shows window begin order", &show_window_begin_order);
-
+ ImGui::Text("%d active allocations", io.MetricsActiveAllocations);
ImGui::Separator();
+ // Helper functions to display common structures:
+ // - NodeDrawList()
+ // - NodeColumns()
+ // - NodeWindow()
+ // - NodeWindows()
+ // - NodeTabBar()
+ // - NodeStorage()
struct Funcs
{
+ static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
+ {
+ if (rect_type == WRT_OuterRect) { return window->Rect(); }
+ else if (rect_type == WRT_OuterRectClipped) { return window->OuterRectClipped; }
+ else if (rect_type == WRT_InnerRect) { return window->InnerRect; }
+ else if (rect_type == WRT_InnerClipRect) { return window->InnerClipRect; }
+ else if (rect_type == WRT_WorkRect) { return window->WorkRect; }
+ else if (rect_type == WRT_Content) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
+ else if (rect_type == WRT_ContentRegionRect) { return window->ContentRegionRect; }
+ IM_ASSERT(0);
+ return ImRect();
+ }
+
static void NodeDrawList(ImGuiWindow* window, ImDrawList* draw_list, const char* label)
{
bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, draw_list->CmdBuffer.Size);
if (draw_list == ImGui::GetWindowDrawList())
{
ImGui::SameLine();
- ImGui::TextColored(ImColor(255,100,100), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
+ ImGui::TextColored(ImVec4(1.0f,0.4f,0.4f,1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
if (node_open) ImGui::TreePop();
return;
}
- ImDrawList* overlay_draw_list = GetOverlayDrawList(); // Render additional visuals into the top-most draw list
+ ImDrawList* fg_draw_list = GetForegroundDrawList(window); // Render additional visuals into the top-most draw list
if (window && IsItemHovered())
- overlay_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
+ fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
if (!node_open)
return;
- int elem_offset = 0;
+ if (window && !window->WasActive)
+ ImGui::TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
+
+ unsigned int elem_offset = 0;
for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.begin(); pcmd < draw_list->CmdBuffer.end(); elem_offset += pcmd->ElemCount, pcmd++)
{
if (pcmd->UserCallback == NULL && pcmd->ElemCount == 0)
@@ -8895,41 +9946,78 @@ void ImGui::ShowMetricsWindow(bool* p_open)
ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
continue;
}
+
ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
- bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "Draw %4d %s vtx, tex 0x%p, clip_rect (%4.0f,%4.0f)-(%4.0f,%4.0f)", pcmd->ElemCount, draw_list->IdxBuffer.Size > 0 ? "indexed" : "non-indexed", pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
- if (show_draw_cmd_clip_rects && ImGui::IsItemHovered())
+ char buf[300];
+ ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd: %4d triangles, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
+ pcmd->ElemCount/3, (void*)(intptr_t)pcmd->TextureId,
+ pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
+ bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
+ if (show_drawcmd_details && fg_draw_list && ImGui::IsItemHovered())
{
ImRect clip_rect = pcmd->ClipRect;
- ImRect vtxs_rect;
- for (int i = elem_offset; i < elem_offset + (int)pcmd->ElemCount; i++)
+ ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
+ for (unsigned int i = elem_offset; i < elem_offset + (int)pcmd->ElemCount; i++)
vtxs_rect.Add(draw_list->VtxBuffer[idx_buffer ? idx_buffer[i] : i].pos);
- clip_rect.Floor(); overlay_draw_list->AddRect(clip_rect.Min, clip_rect.Max, IM_COL32(255,255,0,255));
- vtxs_rect.Floor(); overlay_draw_list->AddRect(vtxs_rect.Min, vtxs_rect.Max, IM_COL32(255,0,255,255));
+ fg_draw_list->AddRect(ImFloor(clip_rect.Min), ImFloor(clip_rect.Max), IM_COL32(255,0,255,255));
+ fg_draw_list->AddRect(ImFloor(vtxs_rect.Min), ImFloor(vtxs_rect.Max), IM_COL32(255,255,0,255));
}
if (!pcmd_node_open)
continue;
+ // Calculate approximate coverage area (touched pixel count)
+ // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
+ float total_area = 0.0f;
+ for (unsigned int base_idx = elem_offset; base_idx < (elem_offset + pcmd->ElemCount); base_idx += 3)
+ {
+ ImVec2 triangle[3];
+ for (int n = 0; n < 3; n++)
+ triangle[n] = draw_list->VtxBuffer[idx_buffer ? idx_buffer[base_idx + n] : (base_idx + n)].pos;
+ total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
+ }
+
+ // Display vertex information summary. Hover to get all triangles drawn in wire-frame
+ ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
+ ImGui::Selectable(buf);
+ if (fg_draw_list && ImGui::IsItemHovered() && show_drawcmd_details)
+ {
+ // Draw wire-frame version of everything
+ ImDrawListFlags backup_flags = fg_draw_list->Flags;
+ fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
+ ImRect clip_rect = pcmd->ClipRect;
+ fg_draw_list->AddRect(ImFloor(clip_rect.Min), ImFloor(clip_rect.Max), IM_COL32(255, 0, 255, 255));
+ for (unsigned int base_idx = elem_offset; base_idx < (elem_offset + pcmd->ElemCount); base_idx += 3)
+ {
+ ImVec2 triangle[3];
+ for (int n = 0; n < 3; n++)
+ triangle[n] = draw_list->VtxBuffer[idx_buffer ? idx_buffer[base_idx + n] : (base_idx + n)].pos;
+ fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), true, 1.0f);
+ }
+ fg_draw_list->Flags = backup_flags;
+ }
+
// Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
ImGuiListClipper clipper(pcmd->ElemCount/3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
while (clipper.Step())
- for (int prim = clipper.DisplayStart, vtx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++)
+ for (int prim = clipper.DisplayStart, idx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++)
{
- char buf[300];
char *buf_p = buf, *buf_end = buf + IM_ARRAYSIZE(buf);
- ImVec2 triangles_pos[3];
- for (int n = 0; n < 3; n++, vtx_i++)
+ ImVec2 triangle[3];
+ for (int n = 0; n < 3; n++, idx_i++)
{
- ImDrawVert& v = draw_list->VtxBuffer[idx_buffer ? idx_buffer[vtx_i] : vtx_i];
- triangles_pos[n] = v.pos;
- buf_p += ImFormatString(buf_p, (int)(buf_end - buf_p), "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n", (n == 0) ? "vtx" : " ", vtx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
+ ImDrawVert& v = draw_list->VtxBuffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
+ triangle[n] = v.pos;
+ buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
+ (n == 0) ? "Vert:" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
}
+
ImGui::Selectable(buf, false);
- if (ImGui::IsItemHovered())
+ if (fg_draw_list && ImGui::IsItemHovered())
{
- ImDrawListFlags backup_flags = overlay_draw_list->Flags;
- overlay_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines at is more readable for very large and thin triangles.
- overlay_draw_list->AddPolyline(triangles_pos, 3, IM_COL32(255,255,0,255), true, 1.0f);
- overlay_draw_list->Flags = backup_flags;
+ ImDrawListFlags backup_flags = fg_draw_list->Flags;
+ fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
+ fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255,255,0,255), true, 1.0f);
+ fg_draw_list->Flags = backup_flags;
}
}
ImGui::TreePop();
@@ -8937,29 +10025,51 @@ void ImGui::ShowMetricsWindow(bool* p_open)
ImGui::TreePop();
}
+ static void NodeColumns(const ImGuiColumns* columns)
+ {
+ if (!ImGui::TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
+ return;
+ ImGui::BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
+ for (int column_n = 0; column_n < columns->Columns.Size; column_n++)
+ ImGui::BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, GetColumnOffsetFromNorm(columns, columns->Columns[column_n].OffsetNorm));
+ ImGui::TreePop();
+ }
+
static void NodeWindows(ImVector<ImGuiWindow*>& windows, const char* label)
{
if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size))
return;
for (int i = 0; i < windows.Size; i++)
+ {
+ ImGui::PushID(windows[i]);
Funcs::NodeWindow(windows[i], "Window");
+ ImGui::PopID();
+ }
ImGui::TreePop();
}
static void NodeWindow(ImGuiWindow* window, const char* label)
{
- if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, window->Active || window->WasActive, window))
+ if (window == NULL)
+ {
+ ImGui::BulletText("%s: NULL", label);
+ return;
+ }
+ bool open = ImGui::TreeNode(label, "%s '%s', %d @ 0x%p", label, window->Name, (window->Active || window->WasActive), window);
+ if (ImGui::IsItemHovered() && window->WasActive)
+ ImGui::GetForegroundDrawList()->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
+ if (!open)
return;
ImGuiWindowFlags flags = window->Flags;
NodeDrawList(window, window->DrawList, "DrawList");
- ImGui::BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), SizeContents (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->SizeContents.x, window->SizeContents.y);
+ ImGui::BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y);
ImGui::BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
(flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
(flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
(flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
- ImGui::BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f)", window->Scroll.x, GetWindowScrollMaxX(window), window->Scroll.y, GetWindowScrollMaxY(window));
+ ImGui::BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
ImGui::BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
- ImGui::BulletText("Appearing: %d, Hidden: %d (Reg %d Resize %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesRegular, window->HiddenFramesForResize, window->SkipItems);
+ ImGui::BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
ImGui::BulletText("NavLastIds: 0x%08X,0x%08X, NavLayerActiveMask: %X", window->NavLastIds[0], window->NavLastIds[1], window->DC.NavLayerActiveMask);
ImGui::BulletText("NavLastChildNavWindow: %s", window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
if (!window->NavRectRel[0].IsInverted())
@@ -8972,32 +10082,58 @@ void ImGui::ShowMetricsWindow(bool* p_open)
if (window->ColumnsStorage.Size > 0 && ImGui::TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
{
for (int n = 0; n < window->ColumnsStorage.Size; n++)
+ NodeColumns(&window->ColumnsStorage[n]);
+ ImGui::TreePop();
+ }
+ NodeStorage(&window->StateStorage, "Storage");
+ ImGui::TreePop();
+ }
+
+ static void NodeTabBar(ImGuiTabBar* tab_bar)
+ {
+ // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
+ char buf[256];
+ char* p = buf;
+ const char* buf_end = buf + IM_ARRAYSIZE(buf);
+ p += ImFormatString(p, buf_end - p, "TabBar (%d tabs)%s", tab_bar->Tabs.Size, (tab_bar->PrevFrameVisible < ImGui::GetFrameCount() - 2) ? " *Inactive*" : "");
+ if (ImGui::TreeNode(tab_bar, "%s", buf))
+ {
+ for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
{
- const ImGuiColumnsSet* columns = &window->ColumnsStorage[n];
- if (ImGui::TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
- {
- ImGui::BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->MaxX - columns->MinX, columns->MinX, columns->MaxX);
- for (int column_n = 0; column_n < columns->Columns.Size; column_n++)
- ImGui::BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, OffsetNormToPixels(columns, columns->Columns[column_n].OffsetNorm));
- ImGui::TreePop();
- }
+ const ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
+ ImGui::PushID(tab);
+ if (ImGui::SmallButton("<")) { TabBarQueueChangeTabOrder(tab_bar, tab, -1); } ImGui::SameLine(0, 2);
+ if (ImGui::SmallButton(">")) { TabBarQueueChangeTabOrder(tab_bar, tab, +1); } ImGui::SameLine();
+ ImGui::Text("%02d%c Tab 0x%08X '%s'", tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, (tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "");
+ ImGui::PopID();
}
ImGui::TreePop();
}
- ImGui::BulletText("Storage: %d bytes", window->StateStorage.Data.Size * (int)sizeof(ImGuiStorage::Pair));
+ }
+
+ static void NodeStorage(ImGuiStorage* storage, const char* label)
+ {
+ if (!ImGui::TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
+ return;
+ for (int n = 0; n < storage->Data.Size; n++)
+ {
+ const ImGuiStorage::ImGuiStoragePair& p = storage->Data[n];
+ ImGui::BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
+ }
ImGui::TreePop();
}
};
- // Access private state, we are going to display the draw lists from last frame
- ImGuiContext& g = *GImGui;
Funcs::NodeWindows(g.Windows, "Windows");
- if (ImGui::TreeNode("DrawList", "Active DrawLists (%d)", g.DrawDataBuilder.Layers[0].Size))
+ //Funcs::NodeWindows(g.WindowsFocusOrder, "WindowsFocusOrder");
+ if (ImGui::TreeNode("DrawLists", "Active DrawLists (%d)", g.DrawDataBuilder.Layers[0].Size))
{
for (int i = 0; i < g.DrawDataBuilder.Layers[0].Size; i++)
Funcs::NodeDrawList(NULL, g.DrawDataBuilder.Layers[0][i], "DrawList");
ImGui::TreePop();
}
+
+ // Details for Popups
if (ImGui::TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
{
for (int i = 0; i < g.OpenPopupStack.Size; i++)
@@ -9007,6 +10143,37 @@ void ImGui::ShowMetricsWindow(bool* p_open)
}
ImGui::TreePop();
}
+
+ // Details for TabBars
+ if (ImGui::TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetSize()))
+ {
+ for (int n = 0; n < g.TabBars.GetSize(); n++)
+ Funcs::NodeTabBar(g.TabBars.GetByIndex(n));
+ ImGui::TreePop();
+ }
+
+ // Details for Tables
+ IM_UNUSED(trt_rects_names);
+ IM_UNUSED(show_tables_rects);
+ IM_UNUSED(show_tables_rect_type);
+#ifdef IMGUI_HAS_TABLE
+ if (ImGui::TreeNode("Tables", "Tables (%d)", g.Tables.GetSize()))
+ {
+ for (int n = 0; n < g.Tables.GetSize(); n++)
+ Funcs::NodeTable(g.Tables.GetByIndex(n));
+ ImGui::TreePop();
+ }
+#endif // #define IMGUI_HAS_TABLE
+
+ // Details for Docking
+#ifdef IMGUI_HAS_DOCK
+ if (ImGui::TreeNode("Docking"))
+ {
+ ImGui::TreePop();
+ }
+#endif // #define IMGUI_HAS_DOCK
+
+ // Misc Details
if (ImGui::TreeNode("Internal state"))
{
const char* input_source_names[] = { "None", "Mouse", "Nav", "NavKeyboard", "NavGamepad" }; IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT);
@@ -9027,25 +10194,87 @@ void ImGui::ShowMetricsWindow(bool* p_open)
ImGui::TreePop();
}
+ // Tools
+ if (ImGui::TreeNode("Tools"))
+ {
+ // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
+ if (ImGui::Button("Item Picker.."))
+ ImGui::DebugStartItemPicker();
+ ImGui::SameLine();
+ MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
+
+ ImGui::Checkbox("Show windows begin order", &show_windows_begin_order);
+ ImGui::Checkbox("Show windows rectangles", &show_windows_rects);
+ ImGui::SameLine();
+ ImGui::SetNextItemWidth(ImGui::GetFontSize() * 12);
+ show_windows_rects |= ImGui::Combo("##show_windows_rect_type", &show_windows_rect_type, wrt_rects_names, WRT_Count, WRT_Count);
+ if (show_windows_rects && g.NavWindow)
+ {
+ ImGui::BulletText("'%s':", g.NavWindow->Name);
+ ImGui::Indent();
+ for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
+ {
+ ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
+ ImGui::Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
+ }
+ ImGui::Unindent();
+ }
+ ImGui::Checkbox("Show details when hovering ImDrawCmd node", &show_drawcmd_details);
+ ImGui::TreePop();
+ }
- if (g.IO.KeyCtrl && show_window_begin_order)
+ // Overlay: Display windows Rectangles and Begin Order
+ if (show_windows_rects || show_windows_begin_order)
{
for (int n = 0; n < g.Windows.Size; n++)
{
ImGuiWindow* window = g.Windows[n];
- if ((window->Flags & ImGuiWindowFlags_ChildWindow) || !window->WasActive)
+ if (!window->WasActive)
continue;
- char buf[32];
- ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
- float font_size = ImGui::GetFontSize() * 2;
- ImDrawList* overlay_draw_list = GetOverlayDrawList();
- overlay_draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
- overlay_draw_list->AddText(NULL, font_size, window->Pos, IM_COL32(255, 255, 255, 255), buf);
+ ImDrawList* draw_list = GetForegroundDrawList(window);
+ if (show_windows_rects)
+ {
+ ImRect r = Funcs::GetWindowRect(window, show_windows_rect_type);
+ draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
+ }
+ if (show_windows_begin_order && !(window->Flags & ImGuiWindowFlags_ChildWindow))
+ {
+ char buf[32];
+ ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
+ float font_size = ImGui::GetFontSize();
+ draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
+ draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
+ }
+ }
+ }
+
+#ifdef IMGUI_HAS_TABLE
+ // Overlay: Display Tables Rectangles
+ if (show_tables_rects)
+ {
+ for (int table_n = 0; table_n < g.Tables.GetSize(); table_n++)
+ {
+ ImGuiTable* table = g.Tables.GetByIndex(table_n);
}
}
+#endif // #define IMGUI_HAS_TABLE
+
+#ifdef IMGUI_HAS_DOCK
+ // Overlay: Display Docking info
+ if (show_docking_nodes && g.IO.KeyCtrl)
+ {
+ }
+#endif // #define IMGUI_HAS_DOCK
+
ImGui::End();
}
+#else
+
+void ImGui::ShowMetricsWindow(bool*) { }
+
+#endif
+
//-----------------------------------------------------------------------------
// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
@@ -9055,3 +10284,5 @@ void ImGui::ShowMetricsWindow(bool* p_open)
#endif
//-----------------------------------------------------------------------------
+
+#endif // #ifndef IMGUI_DISABLE