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

github.com/wolfpld/tracy.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
Diffstat (limited to 'imgui/imgui.cpp')
-rw-r--r--imgui/imgui.cpp1247
1 files changed, 816 insertions, 431 deletions
diff --git a/imgui/imgui.cpp b/imgui/imgui.cpp
index e6a9bc1a..9bdd8eed 100644
--- a/imgui/imgui.cpp
+++ b/imgui/imgui.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.65
+// dear imgui, v1.67
// (main code and documentation)
// Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code.
@@ -7,9 +7,12 @@
// 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
+
// 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 maintenance and development via support contracts or sponsoring, see docs/README.
+// Individuals: you can support continued maintenance and development via donations or Patreon https://www.patreon.com/imgui.
// 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
@@ -26,23 +29,25 @@ 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
+ - 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.
- 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 have multiple widgets with the same label or with an empty 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 interact with standard C++ types (such as std::string and std::vector)?
- How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
+ - How can I use Dear ImGui on a platform that doesn't have a mouse or a keyboard? (input share, remoting, gamepad)
- 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?
@@ -83,19 +88,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
@@ -125,43 +130,58 @@ CODE
PROGRAMMER GUIDE
================
- READ FIRST
+ READ FIRST:
- Read the FAQ below this section!
- 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 data retention on your side, less state duplication, less state synchronization, less bugs.
+ 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
-
- HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
+ - 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.
If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
likely be a comment about it. Please report any issue to the GitHub page!
- Try to keep your copy of dear imgui reasonably up to date.
- GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
+ GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE:
- - Run and study the examples and demo to get acquainted with the library.
+ - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
- Add the Dear ImGui source files to your projects or using your preferred build system.
- It is recommended you build the .cpp files as part of your project and not as a library.
- - You can later customize the imconfig.h file to tweak some compilation time behavior, such as integrating imgui types with your own maths types.
- - You may be able to grab and copy a ready made imgui_impl_*** file from the examples/ folder.
+ 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.
- 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().
- 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.
- THIS IS HOW A SIMPLE APPLICATION MAY LOOK LIKE
- EXHIBIT 1: USING THE EXAMPLE BINDINGS (imgui_impl_XXX.cpp 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).
// Application init: create a dear imgui context, setup some options, load fonts
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
- // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls
+ // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
// TODO: Fill optional fields of the io structure later.
// TODO: Load TTF/OTF fonts if you don't want to use the default font.
@@ -191,13 +211,13 @@ CODE
ImGui_ImplWin32_Shutdown();
ImGui::DestroyContext();
- THIS IS HOW A SIMPLE APPLICATION MAY LOOK LIKE
- EXHIBIT 2: IMPLEMENTING CUSTOM BINDING / CUSTOM ENGINE
+ 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
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
- // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls
+ // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
// TODO: Fill optional fields of the io structure later.
// TODO: Load TTF/OTF fonts if you don't want to use the default font.
@@ -246,16 +266,17 @@ CODE
// Shutdown
ImGui::DestroyContext();
- THIS HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
+ 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 ImDrawList* cmd_list = draw_data->CmdLists[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
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
@@ -268,22 +289,22 @@ CODE
else
{
// The texture for the draw call is specified by pcmd->TextureId.
- // The vast majority of draw calls with use the imgui texture atlas, which value you have set yourself during initialization.
- MyEngineBindTexture(pcmd->TextureId);
+ // The vast majority of draw calls will use the 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.
// - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
- // (some elements visible outside their bounds) but you can fix that once everywhere else works!
+ // (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, always subtract draw_data->DisplayPos from
- // clipping bounds to convert them to your viewport space.
+ // 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 if your engine doesn't support 16-bits indices.
+ // 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.
MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer, vtx_buffer);
}
idx_buffer += pcmd->ElemCount;
@@ -291,15 +312,16 @@ CODE
}
}
- - The examples/ folders contains many functional implementation of the pseudo-code above.
+ - 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 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 both cases you need to pass on the inputs to imgui. Read the FAQ below for more information about those flags.
- - Please read the FAQ above. Amusingly, it is called a FAQ because people frequently have 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 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!
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!
- 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.
- Gamepad:
@@ -342,6 +364,12 @@ 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.
+ - 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. Keep 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.
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)
@@ -351,10 +379,13 @@ 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 binding will still work as is, however prefer using the separated bindings as they will be updated to be multi-viewport conformant.
+ when adopting new bindings follow the main.cpp code of your preferred examples/ folder to know which functions to call.
- 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/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.
@@ -403,6 +434,7 @@ CODE
removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
- 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. Keep 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)!
@@ -460,7 +492,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.
@@ -493,9 +525,9 @@ CODE
- 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.
+ 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 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.
(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)
@@ -522,7 +554,7 @@ CODE
- 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 windows.
+ 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
@@ -534,7 +566,7 @@ CODE
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.
+ - 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.
@@ -593,6 +625,8 @@ CODE
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);
@@ -615,7 +649,7 @@ CODE
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: How can I have multiple widgets with the same label or with an empty label?
Q: I have multiple widgets with the same label, and only the first one works. Why is that?
A: A primer on labels and the ID Stack...
@@ -637,6 +671,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:
@@ -659,64 +696,65 @@ CODE
- If you want to completely hide the label, but still need an ID:
- Checkbox("##On", &b); // Label = "", ID = hash of (..., "##On") // No visible label!
+ Checkbox("##On", &b); // Label = "", ID = hash of (..., "##On") // No visible label, just a checkbox!
- Occasionally/rarely you might want change a label while preserving a constant ID. This allows
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 label, ID = hash of "MyGame"
+ Begin(buf); // Variable title, ID = hash of "MyGame"
- Solving ID conflict in a more general manner:
Use PushID() / PopID() to create scopes and manipulate the ID stack, as to avoid ID conflicts
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();
}
@@ -736,7 +774,9 @@ CODE
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)
+ Default is ProggyClean.ttf, monospace, rendered at size 13, embedded in dear imgui's source code.
+ (Tip: monospace fonts are convenient because they allow to facilitate horizontal alignment directly at the string level.)
+ (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 "\\":
@@ -746,12 +786,13 @@ CODE
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 'How can I load multiple fonts?'
- and the file 'misc/fonts/README.txt' for instructions and useful header files.
+ main font. Then you can refer to icons within your strings.
+ You may want to see ImFontConfig::GlyphMinAdvanceX to make your icon look monospace to facilitate alignment.
+ (Read the 'misc/fonts/README.txt' file for more details about icons font loading.)
Q: How can I load multiple fonts?
A: Use the font atlas to pack them into a single texture:
- (Read misc/fonts/README.txt and the code in ImFontAtlas for more details.)
+ (Read the 'misc/fonts/README.txt' file and the code in ImFontAtlas for more details.)
ImGuiIO& io = ImGui::GetIO();
ImFont* font0 = io.Fonts->AddFontDefault();
@@ -767,15 +808,15 @@ CODE
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);
+ io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_pixels, &config);
// Combine multiple fonts into one (e.g. for icon fonts)
- ImWchar ranges[] = { 0xf000, 0xf3ff, 0 };
+ 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
+ io.Fonts->AddFontFromFileTTF("fontawesome-webfont.ttf", 16.0f, &config, ranges); // Merge icon font
+ io.Fonts->AddFontFromFileTTF("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.
@@ -785,7 +826,7 @@ CODE
// 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;
+ ImFontGlyphRangesBuilder 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
@@ -804,11 +845,50 @@ CODE
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 interact with standard C++ types (such as std::string and std::vector)?
+ A: - Being highly portable (bindings for several languages, frameworks, programming style, obscure or older platforms/compilers),
+ and aiming for compatibility & performance suitable for every modern real-time game engines, dear imgui does not use
+ any of std C++ types. We use raw types (e.g. char* instead of std::string) because they adapt to more use cases.
+ - To use ImGui::InputText() with a std::string or any resizable string class, see misc/cpp/imgui_stdlib.h.
+ - To use combo boxes and list boxes with std::vector or any other data structure: the BeginCombo()/EndCombo() API
+ lets you iterate and submit items yourself, so does the ListBoxHeader()/ListBoxFooter() API.
+ Prefer using them over the old and awkward Combo()/ListBox() api.
+ - Generally for most high-level types you should be able to access the underlying data type.
+ You may write your own one-liner wrappers to facilitate user code (tip: add new functions in ImGui:: namespace from your code).
+ - Dear ImGui applications often need to make intensive use of strings. It is expected that many of the strings you will pass
+ to the API are raw literals (free in C/C++) or allocated in a manner that won't incur a large cost on your application.
+ Please bear in mind that using std::string on applications with large amount of UI may incur unsatisfactory performances.
+ Modern implementations of std::string often include small-string optimization (which is often a local buffer) but those
+ are not configurable and not the same across implementations.
+ - If you are finding your UI traversal cost to be too large, make sure your string usage is not leading to excessive amount
+ of heap allocations. Consider using literals, statically sized buffers and your own helper functions. A common pattern
+ is that you will need to build lots of strings on the fly, and their maximum length can be easily be scoped ahead.
+ One possible implementation of a helper to facilitate printf-style building of strings: https://github.com/ocornut/Str
+ This is a small helper where you can instance strings with configurable local buffers length. Many game engines will
+ provide similar or better string helpers.
+
Q: How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
- A: - You can create a dummy window. Call SetNextWindowBgAlpha(0.0f), call Begin() with NoTitleBar|NoResize|NoMove|NoScrollbar|NoSavedSettings|NoInputs flags.
+ 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.
+ - 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.
+
+ Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display)
+ A: - You can control Dear ImGui with a gamepad. Read about navigation in "Using gamepad/keyboard navigation controls".
+ (short version: map gamepad inputs into the io.NavInputs[] array + set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad)
+ - You can share your computer mouse seamlessly with your console/tablet/phone using Synergy (https://symless.com/synergy)
+ This is the preferred solution for developer productivity.
+ In particular, the "micro-synergy-client" repository (https://github.com/symless/micro-synergy-client) has simple
+ and portable source code (uSynergy.c/.h) for a small embeddable client that you can use on any platform to connect
+ to your host computer, based on the Synergy 1.x protocol. Make sure you download the Synergy 1 server on your computer.
+ Console SDK also sometimes provide equivalent tooling or wrapper for Synergy-like protocols.
+ - You may also use a third party solution such as Remote ImGui (https://github.com/JordiRos/remoteimgui) which sends
+ the vertices to render over the local network, allowing you to use Dear ImGui even on a screen-less machine.
+ - For touch inputs, you can increase the hit box of widgets (via the style.TouchPadding setting) to accommodate
+ for the lack of precision of touch inputs, but it is recommended you use a mouse or gamepad to allow optimizing
+ for screen real-estate and precision.
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).
@@ -819,10 +899,12 @@ CODE
Rectangles provided by ImGui are defined as (x1=left,y1=top,x2=right,y2=bottom) and NOT as (x1,y1,width,height).
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 fund development time! Individual users: you can also become a Patron (patreon.com/imgui) or donate on PayPal! See README.
+ A: - 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!
+ - Businesses: convince your company to fund development via support contracts/sponsoring! This is among the most useful thing you can do for dear imgui.
+ - Individuals: you can also become a Patron (http://www.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.
+ You may post screenshot or links in the gallery threads (github.com/ocornut/imgui/issues/1902). 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).
@@ -854,13 +936,14 @@ CODE
#include <stdint.h> // intptr_t
#endif
+// Debug options
#define IMGUI_DEBUG_NAV_SCORING 0
#define IMGUI_DEBUG_NAV_RECTS 0
// 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
+#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
#endif
// Clang/GCC warnings with -Weverything
@@ -873,7 +956,11 @@ CODE
#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 "-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'
+#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning : zero as null pointer constant // some standard header variations use #define NULL 0
+#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__)
#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
@@ -888,8 +975,12 @@ CODE
#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
+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.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.
//-------------------------------------------------------------------------
// [SECTION] FORWARD DECLARATIONS
@@ -906,7 +997,7 @@ static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* wind
static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list);
static void AddWindowToDrawData(ImVector<ImDrawList*>* out_list, ImGuiWindow* window);
-static void AddWindowToSortedBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
+static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
static ImRect GetViewportRect();
@@ -946,7 +1037,7 @@ static void UpdateManualResize(ImGuiWindow* window, const ImVec2& si
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
//-----------------------------------------------------------------------------
-// Current context pointer. Implicitly used by all ImGui functions. Always assumed to be != NULL.
+// 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:
@@ -999,8 +1090,10 @@ ImGuiStyle::ImGuiStyle()
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.
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.
+ DisplayWindowPadding = ImVec2(19,19); // Window position are clamped to be visible within the display area 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.
@@ -1022,6 +1115,7 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor)
PopupRounding = ImFloor(PopupRounding * scale_factor);
FramePadding = ImFloor(FramePadding * scale_factor);
FrameRounding = ImFloor(FrameRounding * scale_factor);
+ TabRounding = ImFloor(TabRounding * scale_factor);
ItemSpacing = ImFloor(ItemSpacing * scale_factor);
ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor);
TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor);
@@ -1042,8 +1136,8 @@ ImGuiIO::ImGuiIO()
memset(this, 0, sizeof(*this));
// 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;
@@ -1071,9 +1165,12 @@ ImGuiIO::ImGuiIO()
ConfigMacOSXBehaviors = false;
#endif
ConfigInputTextCursorBlink = true;
- ConfigResizeWindowsFromEdges = false;
+ ConfigWindowsResizeFromEdges = true;
+ ConfigWindowsMoveFromTitleBarOnly = false;
- // Settings (User Functions)
+ // Platform Functions
+ BackendPlatformName = BackendRendererName = NULL;
+ BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
ClipboardUserData = NULL;
@@ -1084,7 +1181,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;
@@ -1098,22 +1195,23 @@ ImGuiIO::ImGuiIO()
// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
void ImGuiIO::AddInputCharacter(ImWchar c)
{
- const int n = ImStrlenW(InputCharacters);
- if (n + 1 < IM_ARRAYSIZE(InputCharacters))
+ InputQueueCharacters.push_back(c);
+}
+
+void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
+{
+ 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 <= 0xFFFF)
+ 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);
}
//-----------------------------------------------------------------------------
@@ -1189,28 +1287,48 @@ void ImStrncpy(char* dst, const char* src, size_t count)
dst[count-1] = 0;
}
-char* ImStrdup(const char *str)
+char* ImStrdup(const char* str)
{
- size_t len = strlen(str) + 1;
- void* buf = ImGui::MemAlloc(len);
- return (char*)memcpy(buf, (const void*)str, len);
+ size_t len = strlen(str);
+ void* buf = ImGui::MemAlloc(len + 1);
+ return (char*)memcpy(buf, (const void*)str, len + 1);
+}
+
+char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
+{
+ 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)
+ {
+ ImGui::MemFree(dst);
+ dst = (char*)ImGui::MemAlloc(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)
{
- for ( ; str < str_end; str++)
- if (*str == c)
- return str;
- return NULL;
+ const char* p = (const char*)memchr(str, (int)c, str_end - str);
+ return p;
}
int ImStrlenW(const ImWchar* str)
{
+ //return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bits
int n = 0;
while (*str++) n++;
return n;
}
+// Find end-of-line. Return pointer will point to either first \n, either str_end.
+const char* ImStreolRange(const char* str, const char* str_end)
+{
+ const char* p = (const char*)memchr(str, '\n', str_end - str);
+ return p ? p : str_end;
+}
+
const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
{
while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
@@ -1261,6 +1379,12 @@ void ImStrTrimBlanks(char* buf)
// B) When buf==NULL vsnprintf() will return the output size.
#ifndef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS
+//#define IMGUI_USE_STB_SPRINTF
+#ifdef IMGUI_USE_STB_SPRINTF
+#define STB_SPRINTF_IMPLEMENTATION
+#include "imstb_sprintf.h"
+#endif
+
#if defined(_MSC_VER) && !defined(vsnprintf)
#define vsnprintf _vsnprintf
#endif
@@ -1269,7 +1393,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;
@@ -1281,7 +1409,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)
@@ -1291,7 +1423,9 @@ int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
}
#endif // #ifdef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS
-// Pass data_size==0 for zero-terminated strings
+// Pass data_size == 0 for zero-terminated strings, data_size > 0 for non-string data.
+// Pay attention that data_size==0 will yield different results than passing strlen(data) because the zero-terminated codepath handles ###.
+// This should technically be split into two distinct functions (ImHashData/ImHashStr), perhaps once we remove the silly static variable.
// 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)
{
@@ -1690,15 +1824,15 @@ ImU32 ImGui::GetColorU32(ImU32 col)
//-----------------------------------------------------------------------------
// std::lower_bound but without the bullshit
-static ImVector<ImGuiStorage::Pair>::iterator LowerBound(ImVector<ImGuiStorage::Pair>& data, ImGuiID key)
+static ImGuiStorage::Pair* LowerBound(ImVector<ImGuiStorage::Pair>& data, ImGuiID key)
{
- ImVector<ImGuiStorage::Pair>::iterator first = data.begin();
- ImVector<ImGuiStorage::Pair>::iterator last = data.end();
+ ImGuiStorage::Pair* first = data.Data;
+ ImGuiStorage::Pair* 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::Pair* mid = first + count2;
if (mid->key < key)
{
first = ++mid;
@@ -1731,7 +1865,7 @@ void ImGuiStorage::BuildSortByKey()
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
{
- ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
+ ImGuiStorage::Pair* it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
if (it == Data.end() || it->key != key)
return default_val;
return it->val_i;
@@ -1744,7 +1878,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);
+ ImGuiStorage::Pair* it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
if (it == Data.end() || it->key != key)
return default_val;
return it->val_f;
@@ -1752,7 +1886,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);
+ ImGuiStorage::Pair* it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
if (it == Data.end() || it->key != key)
return NULL;
return it->val_p;
@@ -1761,7 +1895,7 @@ 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);
+ ImGuiStorage::Pair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, Pair(key, default_val));
return &it->val_i;
@@ -1774,7 +1908,7 @@ bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
{
- ImVector<Pair>::iterator it = LowerBound(Data, key);
+ ImGuiStorage::Pair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, Pair(key, default_val));
return &it->val_f;
@@ -1782,7 +1916,7 @@ float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
{
- ImVector<Pair>::iterator it = LowerBound(Data, key);
+ ImGuiStorage::Pair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, Pair(key, default_val));
return &it->val_p;
@@ -1791,7 +1925,7 @@ void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
// 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);
+ ImGuiStorage::Pair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, Pair(key, val));
@@ -1807,7 +1941,7 @@ void ImGuiStorage::SetBool(ImGuiID key, bool val)
void ImGuiStorage::SetFloat(ImGuiID key, float val)
{
- ImVector<Pair>::iterator it = LowerBound(Data, key);
+ ImGuiStorage::Pair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, Pair(key, val));
@@ -1818,7 +1952,7 @@ void ImGuiStorage::SetFloat(ImGuiID key, float val)
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
{
- ImVector<Pair>::iterator it = LowerBound(Data, key);
+ ImGuiStorage::Pair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, Pair(key, val));
@@ -1951,6 +2085,8 @@ bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
#endif
#endif
+char ImGuiTextBuffer::EmptyString[1] = { 0 };
+
// Helper: Text buffer for logging/accumulating text
void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
{
@@ -1964,7 +2100,8 @@ void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
return;
}
- const int write_off = Buf.Size;
+ // 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)
{
@@ -1992,12 +2129,12 @@ void ImGuiTextBuffer::appendf(const char* fmt, ...)
static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height)
{
- // Set cursor position and a few other things so that SetScrollHere() and Columns() can work when seeking cursor.
+ // 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 SetScrollHere() can properly function after the end of our clipper usage.
+ 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
@@ -2133,17 +2270,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);
@@ -2162,14 +2290,27 @@ 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
{
- window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
+ 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, text, text_display_end);
+ LogRenderedText(&pos_min, text, text_display_end);
}
// Render a rectangle shaped with optional rounding and borders
@@ -2265,7 +2406,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;
@@ -2301,13 +2442,14 @@ ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name)
Name = ImStrdup(name);
ID = ImHash(name, 0);
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);
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);
@@ -2454,13 +2596,14 @@ void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
}
}
+// FIXME-NAV: The existence of SetNavID/SetNavIDWithRectRel/SetFocusID is incredibly messy and confusing and needs some explanation or refactoring.
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;
+ const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
if (g.NavWindow != window)
g.NavInitRequest = false;
g.NavId = id;
@@ -2487,7 +2630,7 @@ void ImGui::SetHoveredID(ImGuiID id)
g.HoveredId = id;
g.HoveredIdAllowOverlap = false;
if (id != 0 && g.HoveredIdPreviousFrame != id)
- g.HoveredIdTimer = 0.0f;
+ g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
}
ImGuiID ImGui::GetHoveredID()
@@ -2550,7 +2693,8 @@ void ImGui::ItemSize(const ImVec2& size, float text_offset_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.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
+ window->DC.CursorPos.y = (float)(int)(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y);
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]
@@ -2593,7 +2737,12 @@ bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg)
window->DC.LastItemId = id;
window->DC.LastItemRect = bb;
- window->DC.LastItemStatusFlags = 0;
+ window->DC.LastItemStatusFlags = ImGuiItemStatusFlags_None;
+
+#ifdef IMGUI_ENABLE_TEST_ENGINE
+ if (id != 0)
+ ImGuiTestEngineHook_ItemAdd(&g, bb, id);
+#endif
// Clipping test
const bool is_clipped = IsClippedEx(bb, id, false);
@@ -2687,19 +2836,19 @@ bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id, bool tab_stop
{
ImGuiContext& g = *GImGui;
- const bool allow_keyboard_focus = (window->DC.ItemFlags & (ImGuiItemFlags_AllowKeyboardFocus | ImGuiItemFlags_Disabled)) == ImGuiItemFlags_AllowKeyboardFocus;
+ const bool is_tab_stop = (window->DC.ItemFlags & (ImGuiItemFlags_NoTabStop | ImGuiItemFlags_Disabled)) == 0;
window->FocusIdxAllCounter++;
- if (allow_keyboard_focus)
+ if (is_tab_stop)
window->FocusIdxTabCounter++;
// 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 ? (allow_keyboard_focus ? -1 : 0) : +1); // Modulo on index will be applied at the end of frame once we've got the total counter of items.
+ 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.
if (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent)
return true;
- if (allow_keyboard_focus && window->FocusIdxTabCounter == window->FocusIdxTabRequestCurrent)
+ if (is_tab_stop && window->FocusIdxTabCounter == window->FocusIdxTabRequestCurrent)
{
g.NavJustTabbedId = id;
return true;
@@ -2857,6 +3006,12 @@ int ImGui::GetFrameCount()
return GImGui->FrameCount;
}
+static ImDrawList* GetOverlayDrawList(ImGuiWindow*)
+{
+ // This seemingly unnecessary wrapper simplifies compatibility between the 'master' and 'viewport' branches.
+ return &GImGui->OverlayDrawList;
+}
+
ImDrawList* ImGui::GetOverlayDrawList()
{
return &GImGui->OverlayDrawList;
@@ -2870,6 +3025,8 @@ 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 stuck from moving.
ImGuiContext& g = *GImGui;
FocusWindow(window);
SetActiveID(window->MoveId, window);
@@ -2881,7 +3038,7 @@ void ImGui::StartMouseMovingWindow(ImGuiWindow* 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)
@@ -2919,6 +3076,56 @@ void ImGui::UpdateMouseMovingWindow()
}
}
+// Initiate moving window, handle left-click and right-click focus
+void ImGui::UpdateMouseMovingWindowEndFrame()
+{
+ // Initiate moving window
+ 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 && GetFrontMostPopupModal() == NULL)
+ {
+ FocusWindow(NULL); // Clicking on void disable focus
+ }
+ }
+
+ // 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);
+ }
+}
+
static bool IsWindowActiveAndVisible(ImGuiWindow* window)
{
return (window->Active) && (!window->Hidden);
@@ -2928,6 +3135,10 @@ static void ImGui::UpdateMouseInputs()
{
ImGuiContext& g = *GImGui;
+ // 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 = 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))
g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev;
@@ -2985,9 +3196,9 @@ void ImGui::UpdateMouseWheel()
// 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_NoInputs) && scroll_window->ParentWindow)
+ 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_NoInputs);
+ const bool scroll_allowed = !(scroll_window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(scroll_window->Flags & ImGuiWindowFlags_NoMouseInputs);
if (g.IO.MouseWheel != 0.0f)
{
@@ -3083,6 +3294,10 @@ void ImGui::NewFrame()
IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
ImGuiContext& g = *GImGui;
+#ifdef IMGUI_ENABLE_TEST_ENGINE
+ ImGuiTestEngineHook_PreNewFrame(&g);
+#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);
@@ -3100,9 +3315,9 @@ 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;
// Load settings on first frame (if not explicitly loaded manually before)
if (!g.SettingsLoaded)
@@ -3155,8 +3370,12 @@ void ImGui::NewFrame()
// Clear reference to active widget if the widget isn't alive anymore
if (!g.HoveredIdPreviousFrame)
g.HoveredIdTimer = 0.0f;
+ if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
+ g.HoveredIdNotActiveTimer = 0.0f;
if (g.HoveredId)
g.HoveredIdTimer += g.IO.DeltaTime;
+ if (g.HoveredId && g.ActiveId != g.HoveredId)
+ g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
g.HoveredIdPreviousFrame = g.HoveredId;
g.HoveredId = 0;
g.HoveredIdAllowOverlap = false;
@@ -3198,7 +3417,7 @@ void ImGui::NewFrame()
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();
+ UpdateMouseMovingWindowNewFrame();
UpdateHoveredWindowAndCaptureFlags();
// Background darkening/whitening
@@ -3225,6 +3444,7 @@ void ImGui::NewFrame()
g.NavIdTabCounter = INT_MAX;
// Mark all windows as not visible
+ IM_ASSERT(g.WindowsFocusOrder.Size == g.Windows.Size);
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
@@ -3235,18 +3455,24 @@ void ImGui::NewFrame()
// Closing the focused window restore focus to the first active root window in descending z-order
if (g.NavWindow && !g.NavWindow->WasActive)
- FocusFrontMostActiveWindowIgnoringOne(NULL);
+ FocusPreviousWindowIgnoringOne(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);
+ g.BeginPopupStack.resize(0);
ClosePopupsOverWindow(g.NavWindow);
- // Create implicit window - we will only render it if the user has added something to it.
+ // 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.
SetNextWindowSize(ImVec2(400,400), ImGuiCond_FirstUseEver);
Begin("Debug##Default");
+ g.FrameScopePushedImplicitWindow = true;
+
+#ifdef IMGUI_ENABLE_TEST_ENGINE
+ ImGuiTestEngineHook_PostNewFrame(&g);
+#endif
}
void ImGui::Initialize(ImGuiContext* context)
@@ -3272,7 +3498,10 @@ void ImGui::Shutdown(ImGuiContext* context)
// The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
ImGuiContext& g = *context;
if (g.IO.Fonts && g.FontAtlasOwnedByContext)
+ {
+ g.IO.Fonts->Locked = false;
IM_DELETE(g.IO.Fonts);
+ }
g.IO.Fonts = NULL;
// Cleanup of other data are conditional on actually having initialized ImGui.
@@ -3281,12 +3510,18 @@ void ImGui::Shutdown(ImGuiContext* context)
// Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
if (g.SettingsLoaded && g.IO.IniFilename != NULL)
+ {
+ ImGuiContext* backup_context = GImGui;
+ SetCurrentContext(context);
SaveIniSettingsToDisk(g.IO.IniFilename);
+ SetCurrentContext(backup_context);
+ }
// Clear everything else
for (int i = 0; i < g.Windows.Size; i++)
IM_DELETE(g.Windows[i]);
g.Windows.clear();
+ g.WindowsFocusOrder.clear();
g.WindowsSortBuffer.clear();
g.CurrentWindow = NULL;
g.CurrentWindowStack.clear();
@@ -3300,7 +3535,7 @@ void ImGui::Shutdown(ImGuiContext* context)
g.StyleModifiers.clear();
g.FontStack.clear();
g.OpenPopupStack.clear();
- g.CurrentPopupStack.clear();
+ g.BeginPopupStack.clear();
g.DrawDataBuilder.ClearFreeMemory();
g.OverlayDrawList.ClearFreeMemory();
g.PrivateClipboard.clear();
@@ -3335,7 +3570,7 @@ static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
}
-static void AddWindowToSortedBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
+static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
{
out_sorted_windows->push_back(window);
if (window->Active)
@@ -3347,7 +3582,7 @@ static void AddWindowToSortedBuffer(ImVector<ImGuiWindow*>* out_sorted_windows,
{
ImGuiWindow* child = window->DC.ChildWindows[i];
if (child->Active)
- AddWindowToSortedBuffer(out_sorted_windows, child);
+ AddWindowToSortBuffer(out_sorted_windows, child);
}
}
}
@@ -3463,7 +3698,7 @@ 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.FrameScopeActive && "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)
@@ -3472,13 +3707,29 @@ void ImGui::EndFrame()
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?
+ // 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).
+ if (g.CurrentWindowStack.Size != 1)
+ {
+ if (g.CurrentWindowStack.Size > 1)
+ {
+ IM_ASSERT(g.CurrentWindowStack.Size == 1 && "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
+ while (g.CurrentWindowStack.Size > 1) // FIXME-ERRORHANDLING
+ End();
+ }
+ else
+ {
+ IM_ASSERT(g.CurrentWindowStack.Size == 1 && "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
+ }
+ }
+
+ // Hide implicit/fallback "Debug" window if it hasn't been used
+ g.FrameScopePushedImplicitWindow = false;
if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
g.CurrentWindow->Active = false;
End();
- // Show CTRL+TAB list
+ // Show CTRL+TAB list window
if (g.NavWindowingTarget)
NavUpdateWindowingList();
@@ -3499,42 +3750,12 @@ 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.FrameScopeActive = 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
@@ -3545,7 +3766,7 @@ void ImGui::EndFrame()
ImGuiWindow* window = g.Windows[i];
if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
continue;
- AddWindowToSortedBuffer(&g.WindowsSortBuffer, window);
+ AddWindowToSortBuffer(&g.WindowsSortBuffer, window);
}
IM_ASSERT(g.Windows.Size == g.WindowsSortBuffer.Size); // we done something wrong
@@ -3557,11 +3778,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()
@@ -3570,7 +3788,7 @@ 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)
@@ -3602,7 +3820,7 @@ void ImGui::Render()
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);
@@ -3687,26 +3905,33 @@ static void FindHoveredWindow()
ImGuiContext& g = *GImGui;
ImGuiWindow* hovered_window = NULL;
- if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoInputs))
+ if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
hovered_window = g.MovingWindow;
- for (int i = g.Windows.Size - 1; i >= 0 && hovered_window == NULL; i--)
+ ImVec2 padding_regular = g.Style.TouchExtraPadding;
+ 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)
continue;
- if (window->Flags & ImGuiWindowFlags_NoInputs)
+ if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
continue;
// Using the clipped AABB, a child window will typically be clipped by its parent (not always)
- ImRect bb(window->OuterRectClipped.Min - g.Style.TouchExtraPadding, window->OuterRectClipped.Max + g.Style.TouchExtraPadding);
- if (bb.Contains(g.IO.MousePos))
- {
- if (hovered_window == NULL)
- hovered_window = window;
- if (hovered_window)
- break;
- }
+ ImRect bb(window->OuterRectClipped);
+ if ((window->Flags & ImGuiWindowFlags_ChildWindow) || (window->Flags & ImGuiWindowFlags_NoResize))
+ bb.Expand(padding_regular);
+ else
+ bb.Expand(padding_for_resize_from_edges);
+ if (!bb.Contains(g.IO.MousePos))
+ continue;
+
+ // Those seemingly unnecessary extra tests are because the code here is a little different in viewport/docking branches.
+ if (hovered_window == NULL)
+ hovered_window = window;
+ if (hovered_window)
+ break;
}
g.HoveredWindow = hovered_window;
@@ -3855,8 +4080,8 @@ ImVec2 ImGui::GetMousePos()
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;
}
@@ -3869,6 +4094,8 @@ bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
return mouse_pos->x >= MOUSE_INVALID && mouse_pos->y >= MOUSE_INVALID;
}
+// Return the delta from the initial clicking position.
+// 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)
{
@@ -3937,7 +4164,8 @@ bool ImGui::IsItemDeactivatedAfterEdit()
bool ImGui::IsItemFocused()
{
ImGuiContext& g = *GImGui;
- return g.NavId && !g.NavDisableHighlight && g.NavId == g.CurrentWindow->DC.LastItemId;
+ ImGuiWindow* window = g.CurrentWindow;
+ return g.NavId && !g.NavDisableHighlight && g.NavId == window->DC.LastItemId;
}
bool ImGui::IsItemClicked(int mouse_button)
@@ -4029,10 +4257,10 @@ static bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size
size.y = ImMax(content_avail.y + size.y, 4.0f);
SetNextWindowSize(size);
- // Name
+ // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
char title[256];
if (name)
- ImFormatString(title, IM_ARRAYSIZE(title), "%s/%s", parent_window->Name, name);
+ ImFormatString(title, IM_ARRAYSIZE(title), "%s/%s_%08X", parent_window->Name, name, id);
else
ImFormatString(title, IM_ARRAYSIZE(title), "%s/%08X", parent_window->Name, id);
@@ -4046,6 +4274,11 @@ static bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size
child_window->ChildId = id;
child_window->AutoFitChildAxises = 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))
{
@@ -4133,14 +4366,14 @@ 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()
+ short* p_backup = &window->DC.StackSizesBackup[0];
+ { int current = window->IDStack.Size; if (write) *p_backup = (short)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 = (short)current; else IM_ASSERT(*p_backup == current && "BeginGroup/EndGroup Mismatch!"); p_backup++; } // Too few or too many EndGroup()
+ { int current = g.BeginPopupStack.Size; if (write) *p_backup = (short)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()
+ { int current = g.ColorModifiers.Size; if (write) *p_backup = (short)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 = (short)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 = (short)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));
}
@@ -4151,13 +4384,18 @@ 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 = ImHash(name, 0);
+ return FindWindowByID(id);
+}
+
static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
@@ -4175,14 +4413,14 @@ 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->SettingsIdx = g.SettingsWindows.index_from_ptr(settings);
SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
window->Pos = ImFloor(settings->Pos);
window->Collapsed = settings->Collapsed;
if (ImLengthSqr(settings->Size) > 0.00001f)
size = ImFloor(settings->Size);
}
- window->Size = window->SizeFull = window->SizeFullAtLastBegin = size;
+ window->Size = window->SizeFull = window->SizeFullAtLastBegin = ImFloor(size);
window->DC.CursorMaxPos = window->Pos; // So first call to CalcSizeContents() doesn't return crazy values
if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
@@ -4199,8 +4437,9 @@ static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFl
window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
}
+ g.WindowsFocusOrder.push_back(window);
if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
- g.Windows.insert(g.Windows.begin(), window); // Quite slow but rare and only once
+ g.Windows.push_front(window); // Quite slow but rare and only once
else
g.Windows.push_back(window);
return window;
@@ -4238,6 +4477,11 @@ static ImVec2 CalcSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size)
static ImVec2 CalcSizeContents(ImGuiWindow* window)
{
+ if (window->Collapsed)
+ return window->SizeContents;
+ if (window->Hidden && window->HiddenFramesForResize == 0 && window->HiddenFramesRegular > 0)
+ return window->SizeContents;
+
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));
@@ -4277,12 +4521,12 @@ ImVec2 ImGui::CalcWindowExpectedSize(ImGuiWindow* window)
return CalcSizeAfterConstraint(window, CalcSizeAutoFit(window, size_contents));
}
-static float GetScrollMaxX(ImGuiWindow* window)
+float ImGui::GetWindowScrollMaxX(ImGuiWindow* window)
{
return ImMax(0.0f, window->SizeContents.x - (window->SizeFull.x - window->ScrollbarSizes.x));
}
-static float GetScrollMaxY(ImGuiWindow* window)
+float ImGui::GetWindowScrollMaxY(ImGuiWindow* window)
{
return ImMax(0.0f, window->SizeContents.y - (window->SizeFull.y - window->ScrollbarSizes.y));
}
@@ -4310,8 +4554,8 @@ static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool s
scroll = ImMax(scroll, ImVec2(0.0f, 0.0f));
if (!window->Collapsed && !window->SkipItems)
{
- scroll.x = ImMin(scroll.x, GetScrollMaxX(window));
- scroll.y = ImMin(scroll.y, GetScrollMaxY(window));
+ scroll.x = ImMin(scroll.x, ImGui::GetWindowScrollMaxX(window));
+ scroll.y = ImMin(scroll.y, ImGui::GetWindowScrollMaxY(window));
}
return scroll;
}
@@ -4358,10 +4602,10 @@ static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_
{
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, 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, 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);
- if (border_n == 3) return ImRect(rect.Min.x, 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);
+ 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);
IM_ASSERT(0);
return ImRect();
}
@@ -4373,10 +4617,13 @@ static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au
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/fallback Debug window.
+ return;
- const int resize_border_count = g.IO.ConfigResizeWindowsFromEdges ? 4 : 0;
+ const int resize_border_count = g.IO.ConfigWindowsResizeFromEdges ? 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_size = (float)(int)(grip_draw_size * 0.75f);
+ const float grip_hover_inner_size = (float)(int)(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);
@@ -4389,11 +4636,12 @@ static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au
const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPos);
// Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
- ImRect resize_rect(corner, corner + grip.InnerDir * grip_hover_size);
+ 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(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;
@@ -4407,7 +4655,7 @@ static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au
{
// 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 + resize_rect.GetSize() * grip.CornerPos; // Corner of the window corresponding to our corner grip
+ 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);
}
if (resize_grip_n == 0 || held || hovered)
@@ -4415,12 +4663,11 @@ static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au
}
for (int border_n = 0; border_n < resize_border_count; border_n++)
{
- const float BORDER_SIZE = 5.0f; // FIXME: Only works _inside_ window because of HoveredWindow check.
- const float BORDER_APPEAR_TIMER = 0.05f; // Reduce visual noise
bool hovered, held;
- ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_size, BORDER_SIZE);
+ ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS);
ButtonBehavior(border_rect, window->GetID((void*)(intptr_t)(border_n + 4)), &hovered, &held, ImGuiButtonFlags_FlattenChildren);
- if ((hovered && g.HoveredIdTimer > BORDER_APPEAR_TIMER) || held)
+ //GetOverlayDrawList(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;
@@ -4429,10 +4676,10 @@ static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au
{
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); }
- if (border_n == 1) { border_posn = ImVec2(1, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + BORDER_SIZE); }
- if (border_n == 2) { border_posn = ImVec2(0, 1); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + BORDER_SIZE); }
- if (border_n == 3) { border_posn = ImVec2(0, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x); }
+ 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); }
+ 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); }
+ 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); }
+ 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); }
CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target);
}
}
@@ -4496,7 +4743,7 @@ 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(name != NULL && name[0] != '\0'); // Window name required
IM_ASSERT(g.FrameScopeActive); // 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
@@ -4510,7 +4757,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
}
// Automatically disable manual moving/resizing when NoInputs is set
- if (flags & ImGuiWindowFlags_NoInputs)
+ if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
if (flags & ImGuiWindowFlags_NavFlattened)
@@ -4518,6 +4765,8 @@ 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);
+
+ // Update Flags, LastFrameActive, BeginOrderXXX fields
if (first_begin_of_the_frame)
window->Flags = (ImGuiWindowFlags)flags;
else
@@ -4534,7 +4783,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesForResize > 0);
if (flags & ImGuiWindowFlags_Popup)
{
- ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.CurrentPopupStack.Size];
+ ImGuiPopupRef& 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);
}
@@ -4548,9 +4797,9 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
CheckStacksSize(window, true);
if (flags & ImGuiWindowFlags_Popup)
{
- ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.CurrentPopupStack.Size];
+ ImGuiPopupRef& 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;
}
@@ -4609,12 +4858,24 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
window->Active = true;
window->BeginOrderWithinParent = 0;
- window->BeginOrderWithinContext = g.WindowsActiveCount++;
+ window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
window->BeginCount = 0;
window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX);
window->LastFrameActive = current_frame;
window->IDStack.resize(1);
+ // 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)
@@ -4725,13 +4986,14 @@ 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->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;
@@ -4753,7 +5015,8 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
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 padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
- window->Pos = ImMax(window->Pos + window->Size, padding) - window->Size;
+ ImVec2 size_for_clamping = ((g.IO.ConfigWindowsMoveFromTitleBarOnly) && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) ? ImVec2(window->Size.x, window->TitleBarHeight()) : window->Size;
+ window->Pos = ImMax(window->Pos + size_for_clamping, padding) - size_for_clamping;
window->Pos = ImMin(window->Pos, g.IO.DisplaySize - padding);
}
}
@@ -4781,7 +5044,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
// 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 int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // 4
const float grip_draw_size = (float)(int)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]);
@@ -4840,18 +5103,21 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
else
{
// Window background
- ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags));
- if (g.NextWindowData.BgAlphaCond != 0)
+ if (!(flags & ImGuiWindowFlags_NoBackground))
{
- bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(g.NextWindowData.BgAlphaVal) << IM_COL32_A_SHIFT);
- g.NextWindowData.BgAlphaCond = 0;
+ 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);
}
- 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))
+ {
+ ImU32 title_bar_col = GetColorU32(window->Collapsed ? ImGuiCol_TitleBgCollapsed : 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)
@@ -4884,7 +5150,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
}
// Borders
- if (window_border_size > 0.0f)
+ 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)
{
@@ -4931,7 +5197,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
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.NavHasScroll = (GetWindowScrollMaxY(window) > 0.0f);
window->DC.NavLayerActiveMask = window->DC.NavLayerActiveMaskNext;
window->DC.NavLayerActiveMaskNext = 0x00;
window->DC.MenuBarAppending = false;
@@ -4976,8 +5242,8 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
// 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;
+ window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
+ window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu);
// Collapse button
if (!(flags & ImGuiWindowFlags_NoCollapse))
@@ -4993,12 +5259,15 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
*p_open = false;
}
- window->DC.NavLayerCurrent--;
- window->DC.NavLayerCurrentMask >>= 1;
+ window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
+ window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
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);
+ // 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 too much code..
+ const char* UNSAVED_DOCUMENT_MARKER = "*";
+ float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? CalcTextSize(UNSAVED_DOCUMENT_MARKER, NULL, false).x : 0.0f;
+ ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
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);
@@ -5009,6 +5278,12 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
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);
+ if (flags & ImGuiWindowFlags_UnsavedDocument)
+ {
+ ImVec2 marker_pos = ImVec2(ImMax(text_r.Min.x, text_r.Min.x + (text_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x) + text_size.x, text_r.Min.y) + ImVec2(2 - marker_size_x, 0.0f);
+ ImVec2 off = ImVec2(0.0f, (float)(int)(-g.FontSize * 0.25f));
+ RenderTextClipped(marker_pos + off, text_r.Max + off, UNSAVED_DOCUMENT_MARKER, NULL, NULL, ImVec2(0, style.WindowTitleAlign.y), &clip_rect);
+ }
}
// Save clipped aabb so we can access it in constant-time in FindHoveredWindow()
@@ -5021,7 +5296,7 @@ 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
@@ -5075,7 +5350,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
window->HiddenFramesRegular = 1;
// Update the Hidden flag
- window->Hidden = (window->HiddenFramesRegular > 0) || (window->HiddenFramesForResize);
+ window->Hidden = (window->HiddenFramesRegular > 0) || (window->HiddenFramesForResize > 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;
@@ -5089,19 +5364,27 @@ bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_first_use,
{
// 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);
+ 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);
+ SetNextWindowBgAlpha(bg_alpha_override);
- return ImGui::Begin(name, p_open, flags);
+ return Begin(name, p_open, flags);
}
#endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS
void ImGui::End()
{
ImGuiContext& g = *GImGui;
+
+ if (g.CurrentWindowStack.Size <= 1 && g.FrameScopePushedImplicitWindow)
+ {
+ IM_ASSERT(g.CurrentWindowStack.Size > 1 && "Calling End() too many times!");
+ return; // FIXME-ERRORHANDLING
+ }
+ IM_ASSERT(g.CurrentWindowStack.Size > 0);
+
ImGuiWindow* window = g.CurrentWindow;
if (window->DC.ColumnsSet != NULL)
@@ -5115,12 +5398,26 @@ void ImGui::End()
// Pop from window stack
g.CurrentWindowStack.pop_back();
if (window->Flags & ImGuiWindowFlags_Popup)
- g.CurrentPopupStack.pop_back();
+ g.BeginPopupStack.pop_back();
CheckStacksSize(window, false);
SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back());
}
-void ImGui::BringWindowToFront(ImGuiWindow* window)
+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
+ if (g.WindowsFocusOrder[i] == window)
+ {
+ memmove(&g.WindowsFocusOrder[i], &g.WindowsFocusOrder[i + 1], (size_t)(g.WindowsFocusOrder.Size - i - 1) * sizeof(ImGuiWindow*));
+ g.WindowsFocusOrder[g.WindowsFocusOrder.Size - 1] = window;
+ break;
+ }
+}
+
+void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* current_front_window = g.Windows.back();
@@ -5129,13 +5426,13 @@ void ImGui::BringWindowToFront(ImGuiWindow* window)
for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the front most window
if (g.Windows[i] == window)
{
- g.Windows.erase(g.Windows.Data + i);
- g.Windows.push_back(window);
+ memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
+ g.Windows[g.Windows.Size - 1] = window;
break;
}
}
-void ImGui::BringWindowToBack(ImGuiWindow* window)
+void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (g.Windows[0] == window)
@@ -5162,8 +5459,8 @@ void ImGui::FocusWindow(ImGuiWindow* window)
g.NavInitRequest = false;
g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
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", g.FrameCount, window ? window->Name : NULL);
}
// Passing NULL allow to disable keyboard focus
@@ -5180,20 +5477,26 @@ void ImGui::FocusWindow(ImGuiWindow* window)
ClearActiveID();
// Bring to front
+ BringWindowToFocusFront(window);
if (!(window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus))
- BringWindowToFront(window);
+ BringWindowToDisplayFront(window);
}
-void ImGui::FocusFrontMostActiveWindowIgnoringOne(ImGuiWindow* ignore_window)
+void ImGui::FocusPreviousWindowIgnoringOne(ImGuiWindow* ignore_window)
{
ImGuiContext& g = *GImGui;
- for (int i = g.Windows.Size - 1; i >= 0; i--)
- if (g.Windows[i] != ignore_window && g.Windows[i]->WasActive && !(g.Windows[i]->Flags & ImGuiWindowFlags_ChildWindow))
- {
- ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(g.Windows[i]);
- FocusWindow(focus_window);
- return;
- }
+ for (int i = g.WindowsFocusOrder.Size - 1; 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))
+ if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
+ {
+ ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(window);
+ FocusWindow(focus_window);
+ return;
+ }
+ }
}
void ImGui::PushItemWidth(float item_width)
@@ -5288,9 +5591,10 @@ void ImGui::PopItemFlag()
window->DC.ItemFlags = window->DC.ItemFlagsStack.empty() ? ImGuiItemFlags_Default_ : window->DC.ItemFlagsStack.back();
}
+// FIXME: Look into renaming this once we have settled the new Focus/Activation/TabStop system.
void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus)
{
- PushItemFlag(ImGuiItemFlags_AllowKeyboardFocus, allow_keyboard_focus);
+ PushItemFlag(ImGuiItemFlags_NoTabStop, !allow_keyboard_focus);
}
void ImGui::PopAllowKeyboardFocus()
@@ -5385,6 +5689,7 @@ static const ImGuiStyleVarInfo GStyleVarInfo[] =
{ 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
};
@@ -5477,6 +5782,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";
@@ -5549,11 +5859,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:
@@ -5568,6 +5878,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);
@@ -5654,7 +5966,7 @@ static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond con
if (size.x > 0.0f)
{
window->AutoFitFramesX = 0;
- window->SizeFull.x = size.x;
+ window->SizeFull.x = ImFloor(size.x);
}
else
{
@@ -5664,7 +5976,7 @@ static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond con
if (size.y > 0.0f)
{
window->AutoFitFramesY = 0;
- window->SizeFull.y = size.y;
+ window->SizeFull.y = ImFloor(size.y);
}
else
{
@@ -5936,10 +6248,10 @@ 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);
}
@@ -5955,12 +6267,12 @@ float ImGui::GetScrollY()
float ImGui::GetScrollMaxX()
{
- return GetScrollMaxX(GImGui->CurrentWindow);
+ return GetWindowScrollMaxX(GImGui->CurrentWindow);
}
float ImGui::GetScrollMaxY()
{
- return GetScrollMaxY(GImGui->CurrentWindow);
+ return GetWindowScrollMaxY(GImGui->CurrentWindow);
}
void ImGui::SetScrollX(float scroll_x)
@@ -5977,17 +6289,17 @@ void ImGui::SetScrollY(float scroll_y)
window->ScrollTargetCenterRatio.y = 0.0f;
}
-void ImGui::SetScrollFromPosY(float pos_y, float center_y_ratio)
+void ImGui::SetScrollFromPosY(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
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->ScrollTarget.y = (float)(int)(local_y + window->Scroll.y);
window->ScrollTargetCenterRatio.y = center_y_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::SetScrollHere(float center_y_ratio)
+void ImGui::SetScrollHereY(float center_y_ratio)
{
ImGuiWindow* window = GetCurrentWindow();
float target_y = window->DC.CursorPosPrevLine.y - window->Pos.y; // Top of last item, in window space
@@ -6022,7 +6334,7 @@ void ImGui::SetItemDefaultFocus()
g.NavInitResultRectRel = ImRect(g.NavWindow->DC.LastItemRect.Min - g.NavWindow->Pos, g.NavWindow->DC.LastItemRect.Max - g.NavWindow->Pos);
NavUpdateAnyRequestFlag();
if (!IsItemVisible())
- SetScrollHere();
+ SetScrollHereY();
}
}
@@ -6246,7 +6558,7 @@ void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, bool override_previous_
window->HiddenFramesRegular = 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|ImGuiWindowFlags_NoNav;
+ ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoInputs|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize;
Begin(window_name, NULL, flags | extra_flags);
}
@@ -6282,13 +6594,13 @@ 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()
@@ -6315,17 +6627,17 @@ void ImGui::OpenPopupEx(ImGuiID id)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* parent_window = g.CurrentWindow;
- int current_stack_size = g.CurrentPopupStack.Size;
+ int current_stack_size = g.BeginPopupStack.Size;
ImGuiPopupRef 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.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);
@@ -6374,12 +6686,13 @@ 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];
+ ImGuiPopupRef& popup = g.OpenPopupStack[popup_count_to_keep];
if (!popup.Window)
continue;
IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
@@ -6387,47 +6700,60 @@ void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window)
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)
+ bool popup_or_descendent_has_focus = false;
+ for (int m = popup_count_to_keep; m < g.OpenPopupStack.Size && !popup_or_descendent_has_focus; m++)
+ if (g.OpenPopupStack[m].Window && g.OpenPopupStack[m].Window->RootWindow == ref_window->RootWindow)
+ popup_or_descendent_has_focus = true;
+ if (!popup_or_descendent_has_focus)
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, false);
+ }
}
-void ImGui::ClosePopupToLevel(int remaining)
+void ImGui::ClosePopupToLevel(int remaining, bool apply_focus_to_window_under)
{
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;
g.OpenPopupStack.resize(remaining);
-}
-void ImGui::ClosePopup(ImGuiID id)
-{
- if (!IsPopupOpen(id))
- return;
- ImGuiContext& g = *GImGui;
- ClosePopupToLevel(g.OpenPopupStack.Size - 1);
+ // FIXME: This code is faulty and we may want to eventually to replace or remove the 'apply_focus_to_window_under=true' path completely.
+ // Instead of using g.OpenPopupStack[remaining-1].Window etc. we should find the highest root window that is behind the popups we are closing.
+ // The current code will set focus to the parent of the popup window which is incorrect.
+ // It rarely manifested until now because UpdateMouseMovingWindow() would call FocusWindow() again on the clicked window,
+ // leading to a chain of focusing A (clicked window) then B (parent window of the popup) then A again.
+ // However if the clicked window has the _NoMove flag set we would be left with B focused.
+ // For now, we have disabled this path when called from ClosePopupsOverWindow() because the users of ClosePopupsOverWindow() don't need to alter focus anyway,
+ // but we should inspect and fix this properly.
+ if (apply_focus_to_window_under)
+ {
+ if (g.NavLayer == 0)
+ 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))
popup_idx--;
- ClosePopupToLevel(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)
@@ -6441,7 +6767,7 @@ bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags)
char name[20];
if (extra_flags & ImGuiWindowFlags_ChildMenu)
- ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.CurrentPopupStack.Size); // Recycle windows based on depth
+ 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
@@ -6455,14 +6781,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
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 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;
@@ -6479,12 +6808,13 @@ bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags fla
if (g.NextWindowData.PosCond == 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;
@@ -6494,7 +6824,7 @@ 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);
+ 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);
@@ -6643,6 +6973,12 @@ ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
}
//-----------------------------------------------------------------------------
+// [SECTION] VIEWPORTS, PLATFORM WINDOWS
+//-----------------------------------------------------------------------------
+
+// (this section is filled in the 'viewport' and 'docking' branches)
+
+//-----------------------------------------------------------------------------
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
//-----------------------------------------------------------------------------
@@ -6743,7 +7079,7 @@ static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand)
if (ImGui::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 = ImGui::GetOverlayDrawList(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));
@@ -6751,11 +7087,11 @@ static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand)
}
else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate.
{
- if (IsKeyPressedMap(ImGuiKey_C)) { g.NavMoveDirLast = (ImGuiDir)((g.NavMoveDirLast + 1) & 3); g.IO.KeysDownDuration[g.IO.KeyMap[ImGuiKey_C]] = 0.01f; }
+ if (ImGui::IsKeyPressedMap(ImGuiKey_C)) { g.NavMoveDirLast = (ImGuiDir)((g.NavMoveDirLast + 1) & 3); g.IO.KeysDownDuration[g.IO.KeyMap[ImGuiKey_C]] = 0.01f; }
if (quadrant == g.NavMoveDir)
{
ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
- ImDrawList* draw_list = ImGui::GetOverlayDrawList();
+ ImDrawList* draw_list = ImGui::GetOverlayDrawList(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);
}
@@ -6952,7 +7288,7 @@ 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;
@@ -7000,13 +7336,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)
@@ -7052,7 +7395,7 @@ ImVec2 ImGui::GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInput
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]
+ //GetOverlayDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG]
if (window_rect.Contains(item_rect))
return;
@@ -7084,7 +7427,7 @@ 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)
@@ -7131,7 +7474,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
@@ -7197,12 +7540,12 @@ 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
{
@@ -7244,7 +7587,7 @@ static void ImGui::NavUpdate()
if (g.NavMoveRequestForward == ImGuiNavForward_None)
{
g.NavMoveDir = ImGuiDir_None;
- g.NavMoveRequestFlags = 0;
+ g.NavMoveRequestFlags = ImGuiNavMoveFlags_None;
if (g.NavWindow && !g.NavWindowingTarget && allowed_dir_flags && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
{
if ((allowed_dir_flags & (1<<ImGuiDir_Left)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadLeft, ImGuiNavInput_KeyLeft_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Left;
@@ -7341,15 +7684,27 @@ static void ImGui::NavUpdate()
//g.OverlayDrawList.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) { for (int layer = 0; layer < 2; layer++) GetOverlayDrawList(g.NavWindow)->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->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); GetOverlayDrawList(g.NavWindow)->AddCircleFilled(p, 3.0f, col); GetOverlayDrawList(g.NavWindow)->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.
@@ -7379,7 +7734,6 @@ static void ImGui::NavUpdateMoveResult()
NavScrollToBringItemIntoView(result->Window->ParentWindow, ImRect(rect_abs.Min + delta_scroll, rect_abs.Max + delta_scroll));
}
- // Apply result from previous frame navigation directional move request
ClearActiveID();
g.NavWindow = result->Window;
SetNavIDWithRectRel(result->ID, g.NavLayer, result->RectRel);
@@ -7431,11 +7785,11 @@ static float ImGui::NavUpdatePageUpPageDown(int allowed_dir_flags)
return 0.0f;
}
-static int FindWindowIndex(ImGuiWindow* window) // FIXME-OPT O(N)
+static int FindWindowFocusIndex(ImGuiWindow* window) // FIXME-OPT O(N)
{
ImGuiContext& g = *GImGui;
- for (int i = g.Windows.Size-1; i >= 0; i--)
- if (g.Windows[i] == window)
+ for (int i = g.WindowsFocusOrder.Size-1; i >= 0; i--)
+ if (g.WindowsFocusOrder[i] == window)
return i;
return -1;
}
@@ -7443,9 +7797,9 @@ static int FindWindowIndex(ImGuiWindow* window) // FIXME-OPT O(N)
static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
{
ImGuiContext& g = *GImGui;
- for (int i = i_start; i >= 0 && i < g.Windows.Size && i != i_stop; i += dir)
- if (ImGui::IsWindowNavFocusable(g.Windows[i]))
- return g.Windows[i];
+ for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
+ if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
+ return g.WindowsFocusOrder[i];
return NULL;
}
@@ -7456,10 +7810,10 @@ static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
return;
- const int i_current = FindWindowIndex(g.NavWindowingTarget);
+ const int i_current = 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.Windows.Size - 1) : 0, i_current, focus_change_dir);
+ window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
if (window_target) // Don't reset windowing target if there's a single window in the list
g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
g.NavWindowingToggleLayer = false;
@@ -7491,7 +7845,7 @@ static void ImGui::NavUpdateWindowing()
bool start_windowing_with_gamepad = !g.NavWindowingTarget && IsNavInputPressed(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.Windows.Size - 1, -INT_MAX, -1))
+ if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
{
g.NavWindowingTarget = g.NavWindowingTargetAnim = window;
g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
@@ -7573,8 +7927,8 @@ static void ImGui::NavUpdateWindowing()
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;
@@ -7584,7 +7938,9 @@ 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->DC.NavLayerActiveMask & (1 << 1)) == 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)
{
@@ -7594,7 +7950,7 @@ static void ImGui::NavUpdateWindowing()
}
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
- NavRestoreLayer((g.NavWindow->DC.NavLayerActiveMask & (1 << 1)) ? (g.NavLayer ^ 1) : 0);
+ NavRestoreLayer((g.NavWindow->DC.NavLayerActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main);
}
}
@@ -7622,10 +7978,10 @@ void ImGui::NavUpdateWindowingList()
SetNextWindowSizeConstraints(ImVec2(g.IO.DisplaySize.x * 0.20f, g.IO.DisplaySize.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_Always, ImVec2(0.5f, 0.5f));
PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
- Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
- for (int n = g.Windows.Size - 1; n >= 0; n--)
+ Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
+ for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
{
- ImGuiWindow* window = g.Windows[n];
+ ImGuiWindow* window = g.WindowsFocusOrder[n];
if (!IsWindowNavFocusable(window))
continue;
const char* label = window->Name;
@@ -7969,7 +8325,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;
@@ -8238,6 +8594,12 @@ const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDrop
return &payload;
}
+const ImGuiPayload* ImGui::GetDragDropPayload()
+{
+ ImGuiContext& g = *GImGui;
+ return g.DragDropActive ? &g.DragDropPayload : NULL;
+}
+
// We don't really use/need this now, but added it for the sake of consistency and because we might need it later.
void ImGui::EndDragDropTarget()
{
@@ -8248,6 +8610,12 @@ void ImGui::EndDragDropTarget()
}
//-----------------------------------------------------------------------------
+// [SECTION] DOCKING
+//-----------------------------------------------------------------------------
+
+// (this section is filled in the 'docking' branch)
+
+//-----------------------------------------------------------------------------
// [SECTION] LOGGING/CAPTURING
//-----------------------------------------------------------------------------
@@ -8288,29 +8656,17 @@ void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char*
for (;;)
{
// Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry.
- const char* line_end = text_remaining;
- while (line_end < text_end)
- if (*line_end == '\n')
- break;
- else
- line_end++;
- if (line_end >= text_end)
- line_end = NULL;
-
- const bool is_first_line = (text == text_remaining);
- bool is_last_line = false;
- if (line_end == NULL)
- {
- is_last_line = true;
- line_end = text_end;
- }
- if (line_end != NULL && !(is_last_line && (line_end - text_remaining)==0))
+ const char* line_start = text_remaining;
+ const char* line_end = ImStreolRange(line_start, text_end);
+ const bool is_first_line = (line_start == text);
+ const bool is_last_line = (line_end == text_end);
+ if (!is_last_line || (line_start != line_end))
{
- const int char_count = (int)(line_end - text_remaining);
+ 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, text_remaining);
+ LogText(IM_NEWLINE "%*s%.*s", tree_depth*4, "", char_count, line_start);
else
- LogText(" %.*s", char_count, text_remaining);
+ LogText(" %.*s", char_count, line_start);
}
if (is_last_line)
@@ -8446,7 +8802,7 @@ void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
g.SettingsDirtyTimer = g.IO.IniSavingRate;
}
-static ImGuiWindowSettings* CreateNewWindowSettings(const char* name)
+ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
{
ImGuiContext& g = *GImGui;
g.SettingsWindows.push_back(ImGuiWindowSettings());
@@ -8584,7 +8940,7 @@ static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*
{
ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHash(name, 0));
if (!settings)
- settings = CreateNewWindowSettings(name);
+ settings = ImGui::CreateNewWindowSettings(name);
return (void*)settings;
}
@@ -8612,8 +8968,8 @@ static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSetting
ImGuiWindowSettings* settings = (window->SettingsIdx != -1) ? &g.SettingsWindows[window->SettingsIdx] : ImGui::FindWindowSettings(window->ID);
if (!settings)
{
- settings = CreateNewWindowSettings(window->Name);
- window->SettingsIdx = g.SettingsWindows.index_from_pointer(settings);
+ settings = ImGui::CreateNewWindowSettings(window->Name);
+ window->SettingsIdx = g.SettingsWindows.index_from_ptr(settings);
}
IM_ASSERT(settings->ID == window->ID);
settings->Pos = window->Pos;
@@ -8643,7 +8999,7 @@ static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSetting
// [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
@@ -8655,7 +9011,7 @@ static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSetting
#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")
@@ -8766,6 +9122,7 @@ void ImGui::ShowMetricsWindow(bool* p_open)
ImGui::End();
return;
}
+
static bool show_draw_cmd_clip_rects = true;
static bool show_window_begin_order = false;
ImGuiIO& io = ImGui::GetIO();
@@ -8776,7 +9133,6 @@ void ImGui::ShowMetricsWindow(bool* p_open)
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::Separator();
struct Funcs
@@ -8792,7 +9148,7 @@ void ImGui::ShowMetricsWindow(bool* p_open)
return;
}
- ImDrawList* overlay_draw_list = GetOverlayDrawList(); // Render additional visuals into the top-most draw list
+ ImDrawList* overlay_draw_list = GetOverlayDrawList(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));
if (!node_open)
@@ -8866,11 +9222,11 @@ void ImGui::ShowMetricsWindow(bool* p_open)
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("Flags: 0x%08X (%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_NoInputs) ? "NoInputs":"", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
- ImGui::BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f)", window->Scroll.x, GetScrollMaxX(window), window->Scroll.y, GetScrollMaxY(window));
+ 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("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("NavLastIds: 0x%08X,0x%08X, NavLayerActiveMask: %X", window->NavLastIds[0], window->NavLastIds[1], window->DC.NavLayerActiveMask);
@@ -8900,6 +9256,29 @@ void ImGui::ShowMetricsWindow(bool* p_open)
ImGui::BulletText("Storage: %d bytes", window->StateStorage.Data.Size * (int)sizeof(ImGuiStorage::Pair));
ImGui::TreePop();
}
+
+ static void NodeTabBar(ImGuiTabBar* tab_bar)
+ {
+ // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernable 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 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", tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID);
+ ImGui::PopID();
+ }
+ ImGui::TreePop();
+ }
+ }
};
// Access private state, we are going to display the draw lists from last frame
@@ -8920,6 +9299,12 @@ void ImGui::ShowMetricsWindow(bool* p_open)
}
ImGui::TreePop();
}
+ if (ImGui::TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.Data.Size))
+ {
+ for (int n = 0; n < g.TabBars.Data.Size; n++)
+ Funcs::NodeTabBar(g.TabBars.GetByIndex(n));
+ ImGui::TreePop();
+ }
if (ImGui::TreeNode("Internal state"))
{
const char* input_source_names[] = { "None", "Mouse", "Nav", "NavKeyboard", "NavGamepad" }; IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT);
@@ -8951,7 +9336,7 @@ void ImGui::ShowMetricsWindow(bool* p_open)
char buf[32];
ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
float font_size = ImGui::GetFontSize() * 2;
- ImDrawList* overlay_draw_list = GetOverlayDrawList();
+ ImDrawList* overlay_draw_list = GetOverlayDrawList(window);
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);
}