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
path: root/imgui
diff options
context:
space:
mode:
authorBartosz Taudul <wolf.pld@gmail.com>2018-04-14 16:12:16 +0300
committerBartosz Taudul <wolf.pld@gmail.com>2018-04-14 16:12:16 +0300
commit07201a19ad8170f910f36fe47ca6c27cdba56e59 (patch)
treeeddd2c415460a527cb20742f0a7f0dab6c743db1 /imgui
parent3df7c70f99a488fab47f46705ed53805d5a02d5c (diff)
Update imgui to 1.60.
Diffstat (limited to 'imgui')
-rw-r--r--imgui/imconfig.h44
-rw-r--r--imgui/imgui.cpp3990
-rw-r--r--imgui/imgui.h842
-rw-r--r--imgui/imgui_demo.cpp406
-rw-r--r--imgui/imgui_draw.cpp367
-rw-r--r--imgui/imgui_internal.h477
-rw-r--r--imgui/stb_rect_pack.h90
-rw-r--r--imgui/stb_textedit.h3
-rw-r--r--imgui/stb_truetype.h956
9 files changed, 5102 insertions, 2073 deletions
diff --git a/imgui/imconfig.h b/imgui/imconfig.h
index d139e1c5..5ab10e96 100644
--- a/imgui/imconfig.h
+++ b/imgui/imconfig.h
@@ -1,7 +1,12 @@
//-----------------------------------------------------------------------------
-// USER IMPLEMENTATION
-// This file contains compile-time options for ImGui.
-// Other options (memory allocation overrides, callbacks, etc.) can be set at runtime via the ImGuiIO structure - ImGui::GetIO().
+// COMPILE-TIME OPTIONS FOR DEAR IMGUI
+// Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure.
+// You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions.
+//-----------------------------------------------------------------------------
+// A) You may edit imconfig.h (and not overwrite it when updating imgui, or maintain a patch/branch with your modifications to imconfig.h)
+// B) or add configuration directives in your own file and compile with #define IMGUI_USER_CONFIG "myfilename.h"
+// C) Many compile-time options have an effect on data structures. They need defined consistently _everywhere_ imgui.h is included,
+// not only for the imgui*.cpp compilation units. Defining those options in imconfig.h will ensure they correctly get used everywhere.
//-----------------------------------------------------------------------------
#pragma once
@@ -13,30 +18,35 @@
//#define IMGUI_API __declspec( dllexport )
//#define IMGUI_API __declspec( dllimport )
-//---- Don't define obsolete functions names. Consider enabling from time to time or when updating to reduce like hood of using already obsolete function/names
+//---- Don't define obsolete functions/enums names. Consider enabling from time to time after updating to avoid using soon-to-be obsolete function/names
//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS
-//---- Include imgui_user.h at the end of imgui.h
-//#define IMGUI_INCLUDE_IMGUI_USER_H
-
-//---- Don't implement default handlers for Windows (so as not to link with OpenClipboard() and others Win32 functions)
-//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
-//#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
+//---- Don't implement default handlers for Windows (so as not to link with certain functions)
+//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // Don't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc.
+//#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // Don't use and link with ImmGetContext/ImmSetCompositionWindow.
//---- Don't implement demo windows functionality (ShowDemoWindow()/ShowStyleEditor()/ShowUserGuide() methods will be empty)
-//---- It is very strongly recommended to NOT disable the demo windows. Please read the comment at the top of imgui_demo.cpp to learn why.
+//---- It is very strongly recommended to NOT disable the demo windows during development. Please read the comments in imgui_demo.cpp.
//#define IMGUI_DISABLE_DEMO_WINDOWS
//---- Don't implement ImFormatString(), ImFormatStringV() so you can reimplement them yourself.
//#define IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS
-//---- Pack colors to BGRA instead of RGBA (remove need to post process vertex buffer in back ends)
+//---- Include imgui_user.h at the end of imgui.h as a convenience
+//#define IMGUI_INCLUDE_IMGUI_USER_H
+
+//---- Pack colors to BGRA8 instead of RGBA8 (if you needed to convert from one to another anyway)
//#define IMGUI_USE_BGRA_PACKED_COLOR
-//---- Implement STB libraries in a namespace to avoid linkage conflicts
-//#define IMGUI_STB_NAMESPACE ImGuiStb
+//---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version
+// By default the embedded implementations are declared static and not available outside of imgui cpp files.
+//#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h"
+//#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h"
+//#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION
+//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION
//---- Define constructor and implicit cast operators to convert back<>forth from your math types and ImVec2/ImVec4.
+// This will be inlined as part of ImVec2 and ImVec4 class declarations.
/*
#define IM_VEC2_CLASS_EXTRA \
ImVec2(const MyVec2& f) { x = f.x; y = f.y; } \
@@ -47,15 +57,13 @@
operator MyVec4() const { return MyVec4(x,y,z,w); }
*/
-//---- Use 32-bit vertex indices (instead of default: 16-bit) to allow meshes with more than 64K vertices
+//---- Use 32-bit vertex indices (default is 16-bit) to allow meshes with more than 64K vertices. Render function needs to support it.
#define ImDrawIdx unsigned int
//---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files.
-//---- e.g. create variants of the ImGui::Value() helper for your low-level math types, or your own widgets/helpers.
/*
namespace ImGui
{
- void Value(const char* prefix, const MyMatrix44& v, const char* float_format = NULL);
+ void MyFunction(const char* name, const MyMatrix44& v);
}
*/
-
diff --git a/imgui/imgui.cpp b/imgui/imgui.cpp
index 075fb8c4..33b35193 100644
--- a/imgui/imgui.cpp
+++ b/imgui/imgui.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.53
+// dear imgui, v1.60
// (main code and documentation)
// Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code.
@@ -8,7 +8,13 @@
// 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.
// 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
+// If you work for a company, please consider financial support, see README. For individuals: 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
+// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
+// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
+// to a better solution or official support for them.
/*
@@ -19,21 +25,21 @@
- Read first
- How to update to a newer version of Dear ImGui
- Getting started with integrating Dear ImGui in your code/engine
+ - Using gamepad/keyboard navigation controls [BETA]
- API BREAKING CHANGES (read me when you update!)
- ISSUES & TODO LIST
- FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
- - How can I help?
- - What is ImTextureID and how do I display an image?
- - 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 have multiple widgets with the same label? Can I have widget without a label? (Yes). A primer on labels/IDs.
- - How can I tell when Dear ImGui wants my mouse/keyboard inputs VS when I can pass them to my application?
+ - 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 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 preserve my Dear ImGui context across reloading a DLL? (loss of the global/static variables)
- How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
+ - I integrated Dear ImGui in my engine and the text or lines are blurry..
+ - I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
+ - How can I help?
- ISSUES & TODO-LIST
- CODE
@@ -48,8 +54,8 @@
- 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 won't allocate anything)
+ - 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
@@ -76,6 +82,8 @@
- ESCAPE to revert text to its original value.
- You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!)
- Controls are automatically adjusted for OSX to match standard OSX text editing operations.
+ - General Keyboard controls: enable with ImGuiConfigFlags_NavEnableKeyboard.
+ - General Gamepad controls: enable with ImGuiConfigFlags_NavEnableGamepad. See suggested mappings in imgui.h ImGuiNavInput_ + download PNG/PSD at http://goo.gl/9LgVZW
PROGRAMMER GUIDE
@@ -84,8 +92,8 @@
READ FIRST
- Read the FAQ below this section!
- - Your code creates the UI, if your code doesn't run the UI is gone! == very dynamic UI, no construction/destructions steps, less data retention
- on your side, no state duplication, less sync, less bugs.
+ - 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.
- 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
@@ -93,18 +101,18 @@
- Overwrite all the sources files except for imconfig.h (if you have made modification to your copy of imconfig.h)
- 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!
+ 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
+ - Run and study the examples and demo to get acquainted with the library.
- Add the Dear ImGui source files to your projects, 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.
- - See examples/ folder for standalone sample applications.
- - You may be able to grab and copy a ready made imgui_impl_*** file from the examples/.
+ - You may be able to grab and copy a ready made imgui_impl_*** file from the examples/ folder.
- When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
- Init: retrieve the ImGuiIO structure with ImGui::GetIO() and fill the fields marked 'Settings': at minimum you need to set io.DisplaySize
@@ -125,10 +133,10 @@
- A minimal application skeleton may be:
// Application init
+ ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
io.DisplaySize.x = 1920.0f;
io.DisplaySize.y = 1280.0f;
- io.RenderDrawListsFn = MyRenderFunction; // Setup a render function, or set to NULL and call GetDrawData() after Render() to access render data.
// TODO: Fill others settings of the io structure later.
// Load texture atlas (there is a default font so you don't need to care about choosing a font yet)
@@ -159,12 +167,17 @@
// Render & swap video buffers
ImGui::Render();
+ MyImGuiRenderFunction(ImGui::GetDrawData());
SwapBuffers();
}
+ // Shutdown
+ ImGui::DestroyContext();
+
+
- A minimal render function skeleton may be:
- void void MyRenderFunction(ImDrawData* draw_data)(ImDrawData* draw_data)
+ void void MyRenderFunction(ImDrawData* draw_data)
{
// TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
// TODO: Setup viewport, orthographic projection matrix
@@ -187,7 +200,8 @@
MyEngineBindTexture(pcmd->TextureId);
// We are using scissoring to clip some objects. All low-level graphics API supports it.
- // If your engine doesn't support scissoring yet, you will get some small glitches (some elements outside their bounds) which you can fix later.
+ // 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!
MyEngineScissor((int)pcmd->ClipRect.x, (int)pcmd->ClipRect.y, (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
// Render 'pcmd->ElemCount/3' indexed triangles.
@@ -200,10 +214,45 @@
}
- The examples/ folders contains many functional implementation of the pseudo-code above.
- - When calling NewFrame(), the 'io.WantCaptureMouse'/'io.WantCaptureKeyboard'/'io.WantTextInput' flags are updated.
- They tell you if ImGui intends to use your inputs. So for example, if 'io.WantCaptureMouse' is set you would typically want to hide
- mouse inputs from the rest of your application. Read the FAQ below for more information about those flags.
-
+ - 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.
+ However, 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!
+
+ USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS [BETA]
+
+ - The gamepad/keyboard navigation is in Beta. 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:
+ - Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable.
+ - Backend: Set io.BackendFlags |= ImGuiBackendFlags_HasGamepad + fill the io.NavInputs[] fields before calling NewFrame().
+ Note that io.NavInputs[] is cleared by EndFrame().
+ - See 'enum ImGuiNavInput_' in imgui.h for a description of inputs. For each entry of io.NavInputs[], set the following values:
+ 0.0f= not held. 1.0f= fully held. Pass intermediate 0.0f..1.0f values for analog triggers/sticks.
+ - We uses a simple >0.0f test for activation testing, and won't attempt to test for a dead-zone.
+ Your code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
+ - You can download PNG/PSD files depicting the gamepad controls for common controllers at: goo.gl/9LgVZW.
+ - If you need to share inputs between your game and the imgui parts, the easiest approach is to go all-or-nothing, with a buttons combo
+ to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
+ - Keyboard:
+ - Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable.
+ NewFrame() will automatically fill io.NavInputs[] based on your io.KeyDown[] + io.KeyMap[] arrays.
+ - When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard), the io.WantCaptureKeyboard flag
+ will be set. For more advanced uses, you may want to read from:
+ - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
+ - io.NavVisible: true when the navigation cursor is visible (and usually goes false when mouse is used).
+ - or query focus information with e.g. IsWindowFocused(ImGuiFocusedFlags_AnyWindow), IsItemFocused() etc. functions.
+ Please reach out if you think the game vs navigation input sharing could be improved.
+ - Mouse:
+ - PS4 users: Consider emulating a mouse cursor with DualShock4 touch pad or a spare analog stick as a mouse-emulation fallback.
+ - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + uSynergy.c (on your console/tablet/phone app) to share your PC mouse/keyboard.
+ - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
+ Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs dear imgui to move your mouse cursor along with navigation movements.
+ When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
+ When that happens your back-end NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the binding in examples/ do that.
+ (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, imgui will misbehave as it will see your mouse as moving back and forth!)
+ (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
+ to set a boolean to ignore your other external mouse positions until the external source is moved again.)
API BREAKING CHANGES
@@ -213,6 +262,23 @@
Here is a change-log of API breaking changes, if you are using one of the functions listed, expect to have to fix some code.
Also read releases logs https://github.com/ocornut/imgui/releases for more details.
+ - 2018/03/20 (1.60) - Renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some binding ahead of merging the Nav branch).
+ - 2018/03/12 (1.60) - Removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
+ - 2018/03/08 (1.60) - Changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
+ - 2018/03/03 (1.60) - Renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
+ - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
+ - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
+ - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
+ - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
+ - removed Shutdown() function, as DestroyContext() serve this purpose.
+ - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwhise CreateContext() will create its own font atlas instance.
+ - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
+ - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
+ - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
+ - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
+ - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
+ - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
+ - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
- 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
- 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
- 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
@@ -290,18 +356,11 @@
this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
- if you are using a vanilla copy of one of the imgui_impl_XXXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
- the signature of the io.RenderDrawListsFn handler has changed!
- ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
- became:
- ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
- argument 'cmd_lists' -> 'draw_data->CmdLists'
- argument 'cmd_lists_count' -> 'draw_data->CmdListsCount'
- ImDrawList 'commands' -> 'CmdBuffer'
- ImDrawList 'vtx_buffer' -> 'VtxBuffer'
- ImDrawList n/a -> 'IdxBuffer' (new)
- ImDrawCmd 'vtx_count' -> 'ElemCount'
- ImDrawCmd 'clip_rect' -> 'ClipRect'
- ImDrawCmd 'user_callback' -> 'UserCallback'
- ImDrawCmd 'texture_id' -> 'TextureId'
+ 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'
+ 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.
- if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
- refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
@@ -332,18 +391,9 @@
- 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.
- this sequence:
- const void* png_data;
- unsigned int png_size;
- ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size);
- // <Copy to GPU>
- became:
- unsigned char* pixels;
- int width, height;
- io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
- // <Copy to GPU>
- io.Fonts->TexID = (your_texture_identifier);
- you now have much 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 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)
@@ -369,79 +419,90 @@
FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
======================================
- Q: How can I help?
- A: - If you are experienced enough with Dear ImGui and with C/C++, look at the todo list and see how you want/can help!
- - Become a Patron/donate! Convince your company to become a Patron or provide serious funding for development time! See http://www.patreon.com/imgui
+ Q: How can I tell whether to dispatch mouse/keyboard to imgui or to my application?
+ A: You can read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags from the ImGuiIO structure.
+ - When 'io.WantCaptureMouse' is set, imgui wants to use your mouse state, and you may want to discard/hide the inputs from the rest of your application.
+ - When 'io.WantCaptureKeyboard' is set, imgui wants to use your keyboard state, and you may want to discard/hide the inputs from the rest of your application.
+ - When 'io.WantTextInput' is set to may want to notify your OS to popup an on-screen keyboard, if available (e.g. on a mobile phone, or console OS).
+ Note: you should always pass your mouse/keyboard inputs to imgui, even when the io.WantCaptureXXX flag are set false.
+ This is because imgui needs to detect that you clicked in the void to unfocus its windows.
+ Note: The 'io.WantCaptureMouse' is more accurate that any attempt to "check if the mouse is hovering a window" (don't do that!).
+ It handle mouse dragging correctly (both dragging that started over your application or over an imgui window) and handle e.g. modal windows blocking inputs.
+ Those flags are updated by ImGui::NewFrame(). Preferably read the flags after calling NewFrame() if you can afford it, but reading them before is also
+ perfectly fine, as the bool toggle fairly rarely. If you have on a touch device, you might find use for an early call to NewFrameUpdateHoveredWindowAndCaptureFlags().
+ Note: Text input widget releases focus on "Return KeyDown", so the subsequent "Return KeyUp" event that your application receive will typically
+ have 'io.WantCaptureKeyboard=false'. Depending on your application logic it may or not be inconvenient. You might want to track which key-downs
+ were targetted for Dear ImGui, e.g. with an array of bool, and filter out the corresponding key-ups.)
- Q: What is ImTextureID and how do I display an image?
+ Q: How can I display an image? What is ImTextureID, how does it works?
A: ImTextureID is a void* used to pass renderer-agnostic texture references around until it hits your render function.
Dear ImGui knows nothing about what those bits represent, it just passes them around. It is up to you to decide what you want the void* to carry!
It could be an identifier to your OpenGL texture (cast GLuint to void*), a pointer to your custom engine material (cast MyMaterial* to void*), etc.
At the end of the chain, your renderer takes this void* to cast it back into whatever it needs to select a current texture to render.
Refer to examples applications, where each renderer (in a imgui_impl_xxxx.cpp file) is treating ImTextureID as a different thing.
- (c++ tip: OpenGL uses integers to identify textures. You can safely store an integer into a void*, just cast it to void*, don't take it's address!)
+ (C++ tip: OpenGL uses integers to identify textures. You can safely store an integer into a void*, just cast it to void*, don't take it's address!)
To display a custom image/texture within an ImGui window, you may use ImGui::Image(), ImGui::ImageButton(), ImDrawList::AddImage() functions.
Dear ImGui will generate the geometry and draw calls using the ImTextureID that you passed and which your renderer can use.
+ You may call ImGui::ShowMetricsWindow() to explore active draw lists and visualize/understand how the draw data is generated.
It is your responsibility to get textures uploaded to your GPU.
- Q: I integrated Dear ImGui in my engine and the text or lines are blurry..
- A: In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f).
- Also make sure your orthographic projection matrix and io.DisplaySize matches your actual framebuffer dimension.
+ Q: How can I have multiple widgets with the same label or without a label?
+ A: A primer on labels and the ID Stack...
- Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
- A: You are probably mishandling the clipping rectangles in your render function.
- Rectangles provided by ImGui are defined as (x1=left,y1=top,x2=right,y2=bottom) and NOT as (x1,y1,width,height).
+ - Elements that are typically not clickable, such as Text() items don't need an ID.
- Q: Can I have multiple widgets with the same label? Can I have widget without a label?
- A: Yes. A primer on the use of labels/IDs in Dear ImGui..
+ - Interactive widgets require state to be carried over multiple frames (most typically Dear ImGui
+ often needs to remember what is the "active" widget). To do so they need a unique ID. Unique ID
+ are typically derived from a string label, an integer index or a pointer.
- - Elements that are not clickable, such as Text() items don't need an ID.
+ Button("OK"); // Label = "OK", ID = top of id stack + hash of "OK"
+ Button("Cancel"); // Label = "Cancel", ID = top of id stack + hash of "Cancel"
- - Interactive widgets require state to be carried over multiple frames (most typically Dear ImGui often needs to remember what is
- the "active" widget). to do so they need a unique ID. unique ID are typically derived from a string label, an integer index or a pointer.
-
- Button("OK"); // Label = "OK", ID = hash of "OK"
- Button("Cancel"); // Label = "Cancel", ID = hash of "Cancel"
-
- - ID are uniquely scoped within windows, tree nodes, etc. so no conflict can happen if you have two buttons called "OK"
- in two different windows or in two different locations of a tree.
+ - ID are uniquely scoped within windows, tree nodes, etc. which all pushes to the ID stack. Having
+ two buttons labeled "OK" in different windows or different tree locations is fine.
- If you have a same ID twice in the same location, you'll have a conflict:
Button("OK");
- Button("OK"); // ID collision! Both buttons will be treated as the same.
+ Button("OK"); // ID collision! Interacting with either button will trigger the first one.
Fear not! this is easy to solve and there are many ways to solve it!
- - When passing a label you can optionally specify extra unique ID information within string itself.
- This helps solving the simpler collision cases. Use "##" to pass a complement to the ID that won't be visible to the end-user:
+ - Solving ID conflict in a simple/local context:
+ When passing a label you can optionally specify extra ID information within string itself.
+ Use "##" to pass a complement to the ID that won't be visible to the end-user.
+ This helps solving the simple collision cases when you know e.g. at compilation time which items
+ are going to be created:
- Button("Play"); // Label = "Play", ID = hash of "Play"
- Button("Play##foo1"); // Label = "Play", ID = hash of "Play##foo1" (different from above)
- Button("Play##foo2"); // Label = "Play", ID = hash of "Play##foo2" (different from above)
+ Button("Play"); // Label = "Play", ID = top of id stack + hash of "Play"
+ Button("Play##foo1"); // Label = "Play", ID = top of id stack + hash of "Play##foo1" (different from above)
+ Button("Play##foo2"); // Label = "Play", ID = top of id stack + hash of "Play##foo2" (different from above)
- If you want to completely hide the label, but still need an ID:
- Checkbox("##On", &b); // Label = "", ID = hash of "##On" (no label!)
+ Checkbox("##On", &b); // Label = "", ID = top of id stack + hash of "##On" (no label!)
- - 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 (and windows are uniquely identified by their ID.. obviously)
- Use "###" to pass a label that isn't part of ID:
+ - 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)
+ Button("Hello###ID"; // Label = "Hello", ID = top of id stack + hash of "ID"
+ Button("World###ID"; // Label = "World", ID = top of id stack + hash of "ID" (same as above)
- sprintf(buf, "My game (%f FPS)###MyGame");
+ sprintf(buf, "My game (%f FPS)###MyGame", fps);
Begin(buf); // Variable label, ID = hash of "MyGame"
- - Use PushID() / PopID() to create scopes and avoid ID conflicts within the same Window.
- This is the most convenient way of distinguishing ID if you are iterating and creating many UI elements.
- You can push a pointer, a string or an integer value. Remember that ID are formed from the concatenation of everything in the ID stack!
+ - 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!
for (int i = 0; i < 100; i++)
{
PushID(i);
- Button("Click"); // Label = "Click", ID = hash of integer + "label" (unique)
+ Button("Click"); // Label = "Click", ID = top of id stack + hash of integer + hash of "Click"
PopID();
}
@@ -449,7 +510,7 @@
{
MyObject* obj = Objects[i];
PushID(obj);
- Button("Click"); // Label = "Click", ID = hash of pointer + "label" (unique)
+ Button("Click"); // Label = "Click", ID = top of id stack + hash of pointer + hash of "Click"
PopID();
}
@@ -457,62 +518,57 @@
{
MyObject* obj = Objects[i];
PushID(obj->Name);
- Button("Click"); // Label = "Click", ID = hash of string + "label" (unique)
+ Button("Click"); // Label = "Click", ID = top of id stack + hash of string + hash of "Click"
PopID();
}
- More example showing that you can stack multiple prefixes into the ID stack:
- Button("Click"); // Label = "Click", ID = hash of "Click"
+ Button("Click"); // Label = "Click", ID = top of id stack + hash of "Click"
PushID("node");
- Button("Click"); // Label = "Click", ID = hash of "node" + "Click"
+ Button("Click"); // Label = "Click", ID = top of id stack + hash of "node" + hash of "Click"
PushID(my_ptr);
- Button("Click"); // Label = "Click", ID = hash of "node" + ptr + "Click"
+ Button("Click"); // Label = "Click", ID = top of id stack + hash of "node" + hash of ptr + hash of "Click"
PopID();
PopID();
- Tree nodes implicitly creates a scope for you by calling PushID().
- Button("Click"); // Label = "Click", ID = hash of "Click"
+ Button("Click"); // Label = "Click", ID = top of id stack + hash of "Click"
if (TreeNode("node"))
{
- Button("Click"); // Label = "Click", ID = hash of "node" + "Click"
+ Button("Click"); // Label = "Click", ID = top of id stack + hash of "node" + hash of "Click"
TreePop();
}
- When working with trees, ID are used to preserve the open/close state of each tree node.
Depending on your use cases you may want to use strings, indices or pointers as ID.
- e.g. when displaying a single object that may change over time (dynamic 1-1 relationship), using a static string as ID will preserve your
- node open/closed state when the targeted object change.
- e.g. when displaying a list of objects, using indices or pointers as ID will preserve the node open/closed state differently.
- experiment and see what makes more sense!
-
- Q: How can I tell when Dear ImGui wants my mouse/keyboard inputs VS when I can pass them to my application?
- A: You can read the 'io.WantCaptureMouse'/'io.WantCaptureKeyboard'/'ioWantTextInput' flags from the ImGuiIO structure.
- - When 'io.WantCaptureMouse' or 'io.WantCaptureKeyboard' flags are set 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).
- Preferably read the flags after calling ImGui::NewFrame() to avoid them lagging by one frame. But reading those flags before calling NewFrame() is
- also generally ok, as the bool toggles fairly rarely and you don't generally expect to interact with either Dear ImGui or your application during
- the same frame when that transition occurs. Dear ImGui is tracking dragging and widget activity that may occur outside the boundary of a window,
- so 'io.WantCaptureMouse' is more accurate and correct than checking if a window is hovered.
- (Advanced note: text input releases focus on Return 'KeyDown', so the following Return 'KeyUp' event that your application receive will typically
- have 'io.WantCaptureKeyboard=false'. Depending on your application logic it may or not be inconvenient. You might want to track which key-downs
- were for Dear ImGui, e.g. with an array of bool, and filter out the corresponding key-ups.)
+ e.g. when following a single pointer that may change over time, using a static string as ID
+ will preserve your node open/closed state when the targeted object change.
+ e.g. when displaying a list of objects, using indices or pointers as ID will preserve the
+ node open/closed state differently. See what makes more sense in your situation!
- Q: How can I load a different font than the default? (default is an embedded version of ProggyClean.ttf, rendered at size 13)
+ Q: How can I load a different font than the default?
A: Use the font atlas to load the TTF/OTF file you want:
-
ImGuiIO& io = ImGui::GetIO();
io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels);
io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
+ (default is ProggyClean.ttf, rendered at size 13, embedded in dear imgui's source code)
+
+ New programmers: remember that in C/C++ and most programming languages if you want to use a
+ backslash \ within a string literal, you need to write it double backslash "\\":
+ io.Fonts->AddFontFromFileTTF("MyDataFolder\MyFontFile.ttf", size_in_pixels); // WRONG (you are escape the M here!)
+ io.Fonts->AddFontFromFileTTF("MyDataFolder\\MyFontFile.ttf", size_in_pixels); // CORRECT
+ io.Fonts->AddFontFromFileTTF("MyDataFolder/MyFontFile.ttf", size_in_pixels); // ALSO CORRECT
Q: How can I 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 'extra_fonts/README.txt' for instructions and useful header files.
+ 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.
Q: How can I load multiple fonts?
A: Use the font atlas to pack them into a single texture:
- (Read extra_fonts/README.txt and the code in ImFontAtlas for more details.)
+ (Read misc/fonts/README.txt and the code in ImFontAtlas for more details.)
ImGuiIO& io = ImGui::GetIO();
ImFont* font0 = io.Fonts->AddFontDefault();
@@ -553,29 +609,44 @@
builder.BuildRanges(&ranges); // Build the final result (ordered ranges with all the unique characters submitted)
io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, ranges.Data);
- All your strings needs to use UTF-8 encoding. In C++11 you can encode a string literal in UTF-8 by using the u8"hello" syntax.
- Specifying literal in your source code using a local code page (such as CP-923 for Japanese or CP-1251 for Cyrillic) will NOT work!
+ All your strings needs to use UTF-8 encoding. In C++11 you can encode a string literal in UTF-8
+ by using the u8"hello" syntax. Specifying literal in your source code using a local code page
+ (such as CP-923 for Japanese or CP-1251 for Cyrillic) will NOT work!
Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8.
- Text input: it is up to your application to pass the right character code to io.AddInputCharacter(). The applications in examples/ are doing that.
- For languages using IME, on Windows you can copy the Hwnd of your application to io.ImeWindowHandle.
- The default implementation of io.ImeSetInputScreenPosFn() on Windows will set your IME position correctly.
-
- Q: How can I preserve my Dear ImGui context across reloading a DLL? (loss of the global/static variables)
- A: Create your own context 'ctx = CreateContext()' + 'SetCurrentContext(ctx)' and your own font atlas 'ctx->GetIO().Fonts = new ImFontAtlas()'
- so you don't rely on the default globals.
+ Text input: it is up to your application to pass the right character code by calling
+ io.AddInputCharacter(). The applications in examples/ are doing that. For languages relying
+ on an Input Method Editor (IME), on Windows you can copy the Hwnd of your application in the
+ io.ImeWindowHandle field. The default implementation of io.ImeSetInputScreenPosFn() will set
+ your Microsoft IME position correctly.
Q: How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
- A: The easiest way is to create a dummy window. Call Begin() with NoTitleBar|NoResize|NoMove|NoScrollbar|NoSavedSettings|NoInputs flag,
- zero background alpha, then retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like.
- You can also perfectly create a standalone ImDrawList instance _but_ you need ImGui to be initialized because ImDrawList pulls from ImGui
- data to retrieve the coordinates of the white pixel.
+ A: - You can create a dummy window. Call SetNextWindowBgAlpha(0.0f), call Begin() with NoTitleBar|NoResize|NoMove|NoScrollbar|NoSavedSettings|NoInputs flags.
+ 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.
+
+ Q: I integrated Dear ImGui in my engine and the text or lines are blurry..
+ A: In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f).
+ Also make sure your orthographic projection matrix and io.DisplaySize matches your actual framebuffer dimension.
+
+ Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
+ A: You are probably mishandling the clipping rectangles in your render function.
+ Rectangles provided by ImGui are defined as (x1=left,y1=top,x2=right,y2=bottom) and NOT as (x1,y1,width,height).
+
+ Q: How can I help?
+ A: - If you are experienced with Dear ImGui and C++, look at the github issues, or 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.
+ - 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.
+ But even without visuals, disclosing your use of dear imgui help the library grow credibility, and help other teams and programmers with taking decisions.
+ - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on github or privately).
- tip: you can call Begin() multiple times with the same name during the same frame, it will keep appending to the same window.
- this is also useful to set yourself in the context of another window (to get/set other settings)
+ this is also useful to set yourself in the context of another window (to get/set other settings)
- tip: you can create widgets without a Begin()/End() block, they will go in an implicit window called "Debug".
- tip: the ImGuiOnceUponAFrame helper will allow run the block of code only once a frame. You can use it to quickly add custom UI in the middle
- of a deep nested inner loop in your code.
+ of a deep nested inner loop in your code.
- tip: you can call Render() multiple times (e.g for VR renders).
- tip: call and read the ShowDemoWindow() code in imgui_demo.cpp for more example of how to use ImGui!
@@ -592,13 +663,16 @@
#include <ctype.h> // toupper, isprint
#include <stdlib.h> // NULL, malloc, free, qsort, atoi
#include <stdio.h> // vsnprintf, sscanf, printf
-#include <limits.h> // INT_MIN, INT_MAX
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
#include <stddef.h> // intptr_t
#else
#include <stdint.h> // intptr_t
#endif
+#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: 4505) // unreferenced local function has been removed (stb stuff)
@@ -615,15 +689,22 @@
#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'
#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
#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
-#pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'xxxx' to type 'xxxx' casts away qualifiers
#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
+#pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
+#endif
+
+// Enforce cdecl calling convention for functions called by the standard library, in case compilation settings changed the default to e.g. __vectorcall
+#ifdef _MSC_VER
+#define IMGUI_CDECL __cdecl
+#else
+#define IMGUI_CDECL
#endif
//-------------------------------------------------------------------------
@@ -633,21 +714,20 @@
static bool IsKeyPressedMap(ImGuiKey key, bool repeat = true);
static ImFont* GetDefaultFont();
-static void SetCurrentFont(ImFont* font);
static void SetCurrentWindow(ImGuiWindow* window);
+static void SetWindowScrollX(ImGuiWindow* window, float new_scroll_x);
static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y);
static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond);
static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond);
static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond);
-static ImGuiWindow* FindHoveredWindow(ImVec2 pos);
+static ImGuiWindow* FindHoveredWindow();
static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags);
-static void ClearSetNextWindowData();
static void CheckStacksSize(ImGuiWindow* window, bool write);
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
-static void AddDrawListToRenderList(ImVector<ImDrawList*>& out_render_list, ImDrawList* draw_list);
-static void AddWindowToRenderList(ImVector<ImDrawList*>& out_render_list, ImGuiWindow* window);
-static void AddWindowToSortedBuffer(ImVector<ImGuiWindow*>& out_sorted_windows, ImGuiWindow* window);
+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 ImGuiWindowSettings* AddWindowSettings(const char* name);
@@ -657,9 +737,8 @@ static void SaveIniSettingsToDisk(const char* ini_filename);
static void SaveIniSettingsToMemory(ImVector<char>& out_buf);
static void MarkIniSettingsDirty(ImGuiWindow* window);
-static ImRect GetVisibleRect();
+static ImRect GetViewportRect();
-static void CloseInactivePopups(ImGuiWindow* ref_window);
static void ClosePopupToLevel(int remaining);
static ImGuiWindow* GetFrontMostModalRootWindow();
@@ -669,12 +748,19 @@ static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const
static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, const char* display_format, char* buf, int buf_size);
static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size);
-static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* value1, const void* value2);
+static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* arg_1, const void* arg_2);
static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format);
namespace ImGui
{
-static void FocusPreviousWindow();
+static void NavUpdate();
+static void NavUpdateWindowing();
+static void NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, const ImGuiID id);
+
+static void NewFrameUpdateMovingWindow();
+static void NewFrameUpdateMouseInputs();
+static void UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]);
+static void FocusFrontMostActiveWindow(ImGuiWindow* ignore_window);
}
//-----------------------------------------------------------------------------
@@ -689,21 +775,32 @@ static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y);
// Context
//-----------------------------------------------------------------------------
-// Default font atlas storage.
-// New contexts always point by default to this font atlas. It can be changed by reassigning the GetIO().Fonts variable.
-static ImFontAtlas GImDefaultFontAtlas;
-
-// Default context storage + current context pointer.
-// Implicitely used by all ImGui functions. Always assumed to be != NULL. Change to a different context by calling ImGui::SetCurrentContext()
-// If you are hot-reloading this code in a DLL you will lose the static/global variables. Create your own context+font atlas instead of relying on those default (see FAQ entry "How can I preserve my ImGui context across reloading a DLL?").
-// ImGui is currently not thread-safe because of this variable. If you want thread-safety to allow N threads to access N different contexts, you might work around it by:
+// Current context pointer. Implicitely used by all ImGui functions. Always assumed to be != NULL.
+// CreateContext() will automatically set this pointer if it is NULL. Change to a different context by calling ImGui::SetCurrentContext().
+// If you use DLL hotreloading you might need to call SetCurrentContext() after reloading code from this file.
+// ImGui functions are not thread-safe because of this pointer. If you want thread-safety to allow N threads to access N different contexts, you can:
+// - Change this variable to use thread local storage. You may #define GImGui in imconfig.h for that purpose. Future development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
// - Having multiple instances of the ImGui code compiled inside different namespace (easiest/safest, if you have a finite number of contexts)
-// - or: Changing this variable to be TLS. You may #define GImGui in imconfig.h for further custom hackery. Future development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
#ifndef GImGui
-static ImGuiContext GImDefaultContext;
-ImGuiContext* GImGui = &GImDefaultContext;
+ImGuiContext* GImGui = NULL;
#endif
+// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
+// If you use DLL hotreloading you might need to call SetAllocatorFunctions() after reloading code from this file.
+// Otherwise, you probably don't want to modify them mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
+#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
+static void* MallocWrapper(size_t size, void* user_data) { (void)user_data; return malloc(size); }
+static void FreeWrapper(void* ptr, void* user_data) { (void)user_data; free(ptr); }
+#else
+static void* MallocWrapper(size_t size, void* user_data) { (void)user_data; (void)size; IM_ASSERT(0); return NULL; }
+static void FreeWrapper(void* ptr, void* user_data) { (void)user_data; (void)ptr; IM_ASSERT(0); }
+#endif
+
+static void* (*GImAllocatorAllocFunc)(size_t size, void* user_data) = MallocWrapper;
+static void (*GImAllocatorFreeFunc)(void* ptr, void* user_data) = FreeWrapper;
+static void* GImAllocatorUserData = NULL;
+static size_t GImAllocatorActiveAllocationsCount = 0;
+
//-----------------------------------------------------------------------------
// User facing structures
//-----------------------------------------------------------------------------
@@ -713,7 +810,7 @@ ImGuiStyle::ImGuiStyle()
Alpha = 1.0f; // Global alpha applies to everything in ImGui
WindowPadding = ImVec2(8,8); // Padding within a window
WindowRounding = 7.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows
- WindowBorderSize = 0.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
+ WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
WindowMinSize = ImVec2(32,32); // Minimum window size
WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
@@ -735,11 +832,13 @@ ImGuiStyle::ImGuiStyle()
ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
DisplayWindowPadding = ImVec2(22,22); // Window positions are clamped to be visible within the display area by at least this amount. Only covers regular windows.
DisplaySafeAreaPadding = ImVec2(4,4); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
+ MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU.
AntiAliasedFill = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.)
CurveTessellationTol = 1.25f; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
- ImGui::StyleColorsClassic(this);
+ // Default theme
+ ImGui::StyleColorsDark(this);
}
// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
@@ -764,6 +863,7 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor)
GrabRounding = ImFloor(GrabRounding * scale_factor);
DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);
DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);
+ MouseCursorScale = ImFloor(MouseCursorScale * scale_factor);
}
ImGuiIO::ImGuiIO()
@@ -772,6 +872,8 @@ ImGuiIO::ImGuiIO()
memset(this, 0, sizeof(*this));
// Settings
+ ConfigFlags = 0x00;
+ BackendFlags = 0x00;
DisplaySize = ImVec2(-1.0f, -1.0f);
DeltaTime = 1.0f/60.0f;
IniSavingRate = 5.0f;
@@ -785,7 +887,7 @@ ImGuiIO::ImGuiIO()
KeyRepeatRate = 0.050f;
UserData = NULL;
- Fonts = &GImDefaultFontAtlas;
+ Fonts = NULL;
FontGlobalScale = 1.0f;
FontDefault = NULL;
FontAllowUserScaling = false;
@@ -799,23 +901,25 @@ ImGuiIO::ImGuiIO()
OptMacOSXBehaviors = false;
#endif
OptCursorBlink = true;
-
+
// Settings (User Functions)
- RenderDrawListsFn = NULL;
- MemAllocFn = malloc;
- MemFreeFn = free;
GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
ClipboardUserData = NULL;
ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl;
ImeWindowHandle = NULL;
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ RenderDrawListsFn = NULL;
+#endif
+
// 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;
for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
- for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++) KeysDownDuration[i] = KeysDownDurationPrev[i] = -1.0f;
+ for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++) KeysDownDuration[i] = KeysDownDurationPrev[i] = -1.0f;
+ for (int i = 0; i < IM_ARRAYSIZE(NavInputsDownDuration); i++) NavInputsDownDuration[i] = -1.0f;
}
// Pass in translated ASCII characters for text input.
@@ -848,25 +952,17 @@ void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
#define IM_F32_TO_INT8_UNBOUND(_VAL) ((int)((_VAL) * 255.0f + ((_VAL)>=0 ? 0.5f : -0.5f))) // Unsaturated, for display purpose
#define IM_F32_TO_INT8_SAT(_VAL) ((int)(ImSaturate(_VAL) * 255.0f + 0.5f)) // Saturated, always output 0..255
-// Play it nice with Windows users. Notepad in 2015 still doesn't display text data with Unix-style \n.
-#ifdef _WIN32
-#define IM_NEWLINE "\r\n"
-#else
-#define IM_NEWLINE "\n"
-#endif
-
ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
{
ImVec2 ap = p - a;
ImVec2 ab_dir = b - a;
- float ab_len = sqrtf(ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y);
- ab_dir *= 1.0f / ab_len;
float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
if (dot < 0.0f)
return a;
- if (dot > ab_len)
+ float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
+ if (dot > ab_len_sqr)
return b;
- return a + ab_dir * dot;
+ return a + ab_dir * dot / ab_len_sqr;
}
bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
@@ -932,11 +1028,11 @@ char* ImStrdup(const char *str)
return (char*)memcpy(buf, (const void*)str, len);
}
-char* ImStrchrRange(const char* str, const char* str_end, char c)
+const char* ImStrchrRange(const char* str, const char* str_end, char c)
{
for ( ; str < str_end; str++)
if (*str == c)
- return (char*)str;
+ return str;
return NULL;
}
@@ -1285,8 +1381,8 @@ ImU32 ImGui::GetColorU32(ImU32 col)
float style_alpha = GImGui->Style.Alpha;
if (style_alpha >= 1.0f)
return col;
- int a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
- a = (int)(a * style_alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
+ ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
+ a = (ImU32)(a * style_alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
}
@@ -1377,7 +1473,7 @@ void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, int*
}
int file_size = (int)file_size_signed;
- void* file_data = ImGui::MemAlloc(file_size + padding_bytes);
+ void* file_data = ImGui::MemAlloc((size_t)(file_size + padding_bytes));
if (file_data == NULL)
{
fclose(f);
@@ -1390,7 +1486,7 @@ void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, int*
return NULL;
}
if (padding_bytes > 0)
- memset((void *)(((char*)file_data) + file_size), 0, padding_bytes);
+ memset((void *)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
fclose(f);
if (out_file_size)
@@ -1432,7 +1528,7 @@ void ImGuiStorage::BuildSortByKey()
{
struct StaticFunc
{
- static int PairCompareByID(const void* lhs, const void* rhs)
+ static int IMGUI_CDECL PairCompareByID(const void* lhs, const void* rhs)
{
// We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
if (((const Pair*)lhs)->key > ((const Pair*)rhs)->key) return +1;
@@ -1677,7 +1773,7 @@ void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
}
Buf.resize(needed_sz);
- ImFormatStringV(&Buf[write_off - 1], len + 1, fmt, args_copy);
+ ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
}
void ImGuiTextBuffer::appendf(const char* fmt, ...)
@@ -1692,7 +1788,7 @@ void ImGuiTextBuffer::appendf(const char* fmt, ...)
// ImGuiSimpleColumns (internal use only)
//-----------------------------------------------------------------------------
-ImGuiSimpleColumns::ImGuiSimpleColumns()
+ImGuiMenuColumns::ImGuiMenuColumns()
{
Count = 0;
Spacing = Width = NextWidth = 0.0f;
@@ -1700,7 +1796,7 @@ ImGuiSimpleColumns::ImGuiSimpleColumns()
memset(NextWidths, 0, sizeof(NextWidths));
}
-void ImGuiSimpleColumns::Update(int count, float spacing, bool clear)
+void ImGuiMenuColumns::Update(int count, float spacing, bool clear)
{
IM_ASSERT(Count <= IM_ARRAYSIZE(Pos));
Count = count;
@@ -1717,7 +1813,7 @@ void ImGuiSimpleColumns::Update(int count, float spacing, bool clear)
}
}
-float ImGuiSimpleColumns::DeclColumns(float w0, float w1, float w2) // not using va_arg because they promote float to double
+float ImGuiMenuColumns::DeclColumns(float w0, float w1, float w2) // not using va_arg because they promote float to double
{
NextWidth = 0.0f;
NextWidths[0] = ImMax(NextWidths[0], w0);
@@ -1728,7 +1824,7 @@ float ImGuiSimpleColumns::DeclColumns(float w0, float w1, float w2) // not using
return ImMax(Width, NextWidth);
}
-float ImGuiSimpleColumns::CalcExtraSpace(float avail_w)
+float ImGuiMenuColumns::CalcExtraSpace(float avail_w)
{
return ImMax(0.0f, avail_w - Width);
}
@@ -1740,13 +1836,14 @@ float ImGuiSimpleColumns::CalcExtraSpace(float avail_w)
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.
- // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue. Consider moving within SetCursorXXX functions?
+ // 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.PrevLineHeight = (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->CellMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
+ window->DC.ColumnsSet->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
}
// Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1
@@ -1833,6 +1930,7 @@ ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name)
WindowRounding = 0.0f;
WindowBorderSize = 0.0f;
MoveId = GetID("#MOVE");
+ ChildId = 0;
Scroll = ImVec2(0.0f, 0.0f);
ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
@@ -1841,6 +1939,7 @@ ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name)
Active = WasActive = false;
WriteAccessed = false;
Collapsed = false;
+ CollapseToggleWanted = false;
SkipItems = false;
Appearing = false;
CloseButton = false;
@@ -1864,7 +1963,13 @@ ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name)
DrawList->_OwnerName = Name;
ParentWindow = NULL;
RootWindow = NULL;
- RootNonPopupWindow = NULL;
+ RootWindowForTitleBarHighlight = NULL;
+ RootWindowForTabbing = NULL;
+ RootWindowForNav = NULL;
+
+ NavLastIds[0] = NavLastIds[1] = 0;
+ NavRectRel[0] = NavRectRel[1] = ImRect();
+ NavLastChildNavWindow = NULL;
FocusIdxAllCounter = FocusIdxTabCounter = -1;
FocusIdxAllRequestCurrent = FocusIdxTabRequestCurrent = INT_MAX;
@@ -1875,6 +1980,8 @@ ImGuiWindow::~ImGuiWindow()
{
IM_DELETE(DrawList);
IM_DELETE(Name);
+ for (int i = 0; i != ColumnsStorage.Size; i++)
+ ColumnsStorage[i].~ImGuiColumnsSet();
}
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
@@ -1921,6 +2028,25 @@ static void SetCurrentWindow(ImGuiWindow* window)
g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
}
+static void SetNavID(ImGuiID id, int nav_layer)
+{
+ ImGuiContext& g = *GImGui;
+ IM_ASSERT(g.NavWindow);
+ IM_ASSERT(nav_layer == 0 || nav_layer == 1);
+ g.NavId = id;
+ g.NavWindow->NavLastIds[nav_layer] = id;
+}
+
+static void SetNavIDWithRectRel(ImGuiID id, int nav_layer, const ImRect& rect_rel)
+{
+ ImGuiContext& g = *GImGui;
+ SetNavID(id, nav_layer);
+ g.NavWindow->NavRectRel[nav_layer] = rect_rel;
+ g.NavMousePosDirty = true;
+ g.NavDisableHighlight = false;
+ g.NavDisableMouseHover = true;
+}
+
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
@@ -1928,9 +2054,42 @@ void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
if (g.ActiveIdIsJustActivated)
g.ActiveIdTimer = 0.0f;
g.ActiveId = id;
+ g.ActiveIdAllowNavDirFlags = 0;
g.ActiveIdAllowOverlap = false;
- g.ActiveIdIsAlive |= (id != 0);
g.ActiveIdWindow = window;
+ if (id)
+ {
+ g.ActiveIdIsAlive = true;
+ g.ActiveIdSource = (g.NavActivateId == id || g.NavInputId == id || g.NavJustTabbedId == id || g.NavJustMovedToId == id) ? ImGuiInputSource_Nav : ImGuiInputSource_Mouse;
+ }
+}
+
+ImGuiID ImGui::GetActiveID()
+{
+ ImGuiContext& g = *GImGui;
+ return g.ActiveId;
+}
+
+void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
+{
+ ImGuiContext& g = *GImGui;
+ IM_ASSERT(id != 0);
+
+ // Assume that SetFocusID() is called in the context where its NavLayer is the current layer, which is the case everywhere we call it.
+ const int nav_layer = window->DC.NavLayerCurrent;
+ if (g.NavWindow != window)
+ g.NavInitRequest = false;
+ g.NavId = id;
+ g.NavWindow = window;
+ g.NavLayer = nav_layer;
+ window->NavLastIds[nav_layer] = id;
+ if (window->DC.LastItemId == id)
+ window->NavRectRel[nav_layer] = ImRect(window->DC.LastItemRect.Min - window->Pos, window->DC.LastItemRect.Max - window->Pos);
+
+ if (g.ActiveIdSource == ImGuiInputSource_Nav)
+ g.NavDisableMouseHover = true;
+ else
+ g.NavDisableHighlight = true;
}
void ImGui::ClearActiveID()
@@ -1946,6 +2105,12 @@ void ImGui::SetHoveredID(ImGuiID id)
g.HoveredIdTimer = (id != 0 && g.HoveredIdPreviousFrame == id) ? (g.HoveredIdTimer + g.IO.DeltaTime) : 0.0f;
}
+ImGuiID ImGui::GetHoveredID()
+{
+ ImGuiContext& g = *GImGui;
+ return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
+}
+
void ImGui::KeepAliveID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
@@ -2005,23 +2170,290 @@ void ImGui::ItemSize(const ImRect& bb, float text_offset_y)
ItemSize(bb.GetSize(), text_offset_y);
}
+static ImGuiDir NavScoreItemGetQuadrant(float dx, float dy)
+{
+ if (fabsf(dx) > fabsf(dy))
+ return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
+ return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
+}
+
+static float NavScoreItemDistInterval(float a0, float a1, float b0, float b1)
+{
+ if (a1 < b0)
+ return a1 - b0;
+ if (b1 < a0)
+ return a0 - b1;
+ return 0.0f;
+}
+
+// Scoring function for directional navigation. Based on https://gist.github.com/rygorous/6981057
+static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ if (g.NavLayer != window->DC.NavLayerCurrent)
+ return false;
+
+ const ImRect& curr = g.NavScoringRectScreen; // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
+ g.NavScoringCount++;
+
+ // We perform scoring on items bounding box clipped by their parent window on the other axis (clipping on our movement axis would give us equal scores for all clipped items)
+ if (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right)
+ {
+ cand.Min.y = ImClamp(cand.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y);
+ cand.Max.y = ImClamp(cand.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y);
+ }
+ else
+ {
+ cand.Min.x = ImClamp(cand.Min.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
+ cand.Max.x = ImClamp(cand.Max.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
+ }
+
+ // Compute distance between boxes
+ // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
+ float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
+ float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
+ if (dby != 0.0f && dbx != 0.0f)
+ dbx = (dbx/1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
+ float dist_box = fabsf(dbx) + fabsf(dby);
+
+ // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
+ float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
+ float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
+ float dist_center = fabsf(dcx) + fabsf(dcy); // L1 metric (need this for our connectedness guarantee)
+
+ // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
+ ImGuiDir quadrant;
+ float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
+ if (dbx != 0.0f || dby != 0.0f)
+ {
+ // For non-overlapping boxes, use distance between boxes
+ dax = dbx;
+ day = dby;
+ dist_axial = dist_box;
+ quadrant = NavScoreItemGetQuadrant(dbx, dby);
+ }
+ else if (dcx != 0.0f || dcy != 0.0f)
+ {
+ // For overlapping boxes with different centers, use distance between centers
+ dax = dcx;
+ day = dcy;
+ dist_axial = dist_center;
+ quadrant = NavScoreItemGetQuadrant(dcx, dcy);
+ }
+ else
+ {
+ // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
+ quadrant = (window->DC.LastItemId < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
+ }
+
+#if IMGUI_DEBUG_NAV_SCORING
+ char buf[128];
+ 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]);
+ g.OverlayDrawList.AddRect(curr.Min, curr.Max, IM_COL32(255, 200, 0, 100));
+ g.OverlayDrawList.AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200));
+ g.OverlayDrawList.AddRectFilled(cand.Max-ImVec2(4,4), cand.Max+ImGui::CalcTextSize(buf)+ImVec2(4,4), IM_COL32(40,0,0,150));
+ g.OverlayDrawList.AddText(g.IO.FontDefault, 13.0f, cand.Max, ~0U, buf);
+ }
+ else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate.
+ {
+ if (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);
+ g.OverlayDrawList.AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 200));
+ g.OverlayDrawList.AddText(g.IO.FontDefault, 13.0f, cand.Min, IM_COL32(255, 255, 255, 255), buf);
+ }
+ }
+ #endif
+
+ // Is it in the quadrant we're interesting in moving to?
+ bool new_best = false;
+ if (quadrant == g.NavMoveDir)
+ {
+ // Does it beat the current best candidate?
+ if (dist_box < result->DistBox)
+ {
+ result->DistBox = dist_box;
+ result->DistCenter = dist_center;
+ return true;
+ }
+ if (dist_box == result->DistBox)
+ {
+ // Try using distance between center points to break ties
+ if (dist_center < result->DistCenter)
+ {
+ result->DistCenter = dist_center;
+ new_best = true;
+ }
+ else if (dist_center == result->DistCenter)
+ {
+ // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
+ // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
+ // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
+ if (((g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
+ new_best = true;
+ }
+ }
+ }
+
+ // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
+ // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
+ // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
+ // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
+ // Disabling it may however lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
+ if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial) // Check axial match
+ if (g.NavLayer == 1 && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
+ if ((g.NavMoveDir == ImGuiDir_Left && dax < 0.0f) || (g.NavMoveDir == ImGuiDir_Right && dax > 0.0f) || (g.NavMoveDir == ImGuiDir_Up && day < 0.0f) || (g.NavMoveDir == ImGuiDir_Down && day > 0.0f))
+ {
+ result->DistAxial = dist_axial;
+ new_best = true;
+ }
+
+ return new_best;
+}
+
+static void NavSaveLastChildNavWindow(ImGuiWindow* child_window)
+{
+ ImGuiWindow* parent_window = child_window;
+ while (parent_window && (parent_window->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (parent_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
+ parent_window = parent_window->ParentWindow;
+ if (parent_window && parent_window != child_window)
+ parent_window->NavLastChildNavWindow = child_window;
+}
+
+// Call when we are expected to land on Layer 0 after FocusWindow()
+static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window)
+{
+ return window->NavLastChildNavWindow ? window->NavLastChildNavWindow : window;
+}
+
+static void NavRestoreLayer(int layer)
+{
+ ImGuiContext& g = *GImGui;
+ g.NavLayer = layer;
+ if (layer == 0)
+ g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow);
+ if (layer == 0 && g.NavWindow->NavLastIds[0] != 0)
+ SetNavIDWithRectRel(g.NavWindow->NavLastIds[0], layer, g.NavWindow->NavRectRel[0]);
+ else
+ ImGui::NavInitWindow(g.NavWindow, true);
+}
+
+static inline void NavUpdateAnyRequestFlag()
+{
+ ImGuiContext& g = *GImGui;
+ g.NavAnyRequest = g.NavMoveRequest || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
+ if (g.NavAnyRequest)
+ IM_ASSERT(g.NavWindow != NULL);
+}
+
+static bool NavMoveRequestButNoResultYet()
+{
+ ImGuiContext& g = *GImGui;
+ return g.NavMoveRequest && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
+}
+
+void ImGui::NavMoveRequestCancel()
+{
+ ImGuiContext& g = *GImGui;
+ g.NavMoveRequest = false;
+ NavUpdateAnyRequestFlag();
+}
+
+// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
+static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, const ImGuiID id)
+{
+ ImGuiContext& g = *GImGui;
+ //if (!g.IO.NavActive) // [2017/10/06] Removed this possibly redundant test but I am not sure of all the side-effects yet. Some of the feature here will need to work regardless of using a _NoNavInputs flag.
+ // return;
+
+ const ImGuiItemFlags item_flags = window->DC.ItemFlags;
+ const ImRect nav_bb_rel(nav_bb.Min - window->Pos, nav_bb.Max - window->Pos);
+ if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent)
+ {
+ // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
+ if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus) || g.NavInitResultId == 0)
+ {
+ g.NavInitResultId = id;
+ g.NavInitResultRectRel = nav_bb_rel;
+ }
+ if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus))
+ {
+ g.NavInitRequest = false; // Found a match, clear request
+ NavUpdateAnyRequestFlag();
+ }
+ }
+
+ // Scoring for navigation
+ if (g.NavId != id && !(item_flags & ImGuiItemFlags_NoNav))
+ {
+ ImGuiNavMoveResult* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
+#if IMGUI_DEBUG_NAV_SCORING
+ // [DEBUG] Score all items in NavWindow at all times
+ if (!g.NavMoveRequest)
+ g.NavMoveDir = g.NavMoveDirLast;
+ bool new_best = NavScoreItem(result, nav_bb) && g.NavMoveRequest;
+#else
+ bool new_best = g.NavMoveRequest && NavScoreItem(result, nav_bb);
+#endif
+ if (new_best)
+ {
+ result->ID = id;
+ result->ParentID = window->IDStack.back();
+ result->Window = window;
+ result->RectRel = nav_bb_rel;
+ }
+ }
+
+ // Update window-relative bounding box of navigated item
+ if (g.NavId == id)
+ {
+ g.NavWindow = window; // Always refresh g.NavWindow, because some operations such as FocusItem() don't have a window.
+ g.NavLayer = window->DC.NavLayerCurrent;
+ g.NavIdIsAlive = true;
+ g.NavIdTabCounter = window->FocusIdxTabCounter;
+ window->NavRectRel[window->DC.NavLayerCurrent] = nav_bb_rel; // Store item bounding box (relative to window position)
+ }
+}
+
// Declare item bounding box for clipping and interaction.
// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
-// declares their minimum size requirement to ItemSize() and then use a larger region for drawing/interaction, which is passed to ItemAdd().
-bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id)
+// declare their minimum size requirement to ItemSize() and then use a larger region for drawing/interaction, which is passed to ItemAdd().
+bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
- const bool is_clipped = IsClippedEx(bb, id, false);
+
+ if (id != 0)
+ {
+ // Navigation processing runs prior to clipping early-out
+ // (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
+ // (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests unfortunately, but it is still limited to one window.
+ // it may not scale very well for windows with ten of thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
+ // We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick)
+ window->DC.NavLayerActiveMaskNext |= window->DC.NavLayerCurrentMask;
+ if (g.NavId == id || g.NavAnyRequest)
+ if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
+ if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
+ NavProcessItem(window, nav_bb_arg ? *nav_bb_arg : bb, id);
+ }
+
window->DC.LastItemId = id;
window->DC.LastItemRect = bb;
- window->DC.LastItemRectHoveredRect = false;
+ window->DC.LastItemStatusFlags = 0;
+
+ // Clipping test
+ const bool is_clipped = IsClippedEx(bb, id, false);
if (is_clipped)
return false;
//if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
// We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
- window->DC.LastItemRectHoveredRect = IsMouseHoveringRect(bb.Min, bb.Max);
+ if (IsMouseHoveringRect(bb.Min, bb.Max))
+ window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HoveredRect;
return true;
}
@@ -2032,9 +2464,11 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
+ if (g.NavDisableMouseHover && !g.NavDisableHighlight)
+ return IsItemFocused();
// Test for bounding box overlap, as updated as ItemAdd()
- if (!window->DC.LastItemRectHoveredRect)
+ if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect))
return false;
IM_ASSERT((flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows)) == 0); // Flags not supported by this function
@@ -2079,7 +2513,7 @@ bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id)
return false;
if (!IsMouseHoveringRect(bb.Min, bb.Max))
return false;
- if (!IsWindowContentHoverable(window, ImGuiHoveredFlags_Default))
+ if (g.NavDisableMouseHover || !IsWindowContentHoverable(window, ImGuiHoveredFlags_Default))
return false;
if (window->DC.ItemFlags & ImGuiItemFlags_Disabled)
return false;
@@ -2115,10 +2549,11 @@ bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id, bool tab_stop
if (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent)
return true;
-
- if (allow_keyboard_focus)
- if (window->FocusIdxTabCounter == window->FocusIdxTabRequestCurrent)
- return true;
+ if (allow_keyboard_focus && window->FocusIdxTabCounter == window->FocusIdxTabRequestCurrent)
+ {
+ g.NavJustTabbedId = id;
+ return true;
+ }
return false;
}
@@ -2160,14 +2595,14 @@ float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
void* ImGui::MemAlloc(size_t sz)
{
- GImGui->IO.MetricsAllocs++;
- return GImGui->IO.MemAllocFn(sz);
+ GImAllocatorActiveAllocationsCount++;
+ return GImAllocatorAllocFunc(sz, GImAllocatorUserData);
}
void ImGui::MemFree(void* ptr)
{
- if (ptr) GImGui->IO.MetricsAllocs--;
- return GImGui->IO.MemFreeFn(ptr);
+ if (ptr) GImAllocatorActiveAllocationsCount--;
+ return GImAllocatorFreeFunc(ptr, GImAllocatorUserData);
}
const char* ImGui::GetClipboardText()
@@ -2202,39 +2637,49 @@ void ImGui::SetCurrentContext(ImGuiContext* ctx)
#endif
}
-ImGuiContext* ImGui::CreateContext(void* (*malloc_fn)(size_t), void (*free_fn)(void*))
+void ImGui::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void(*free_func)(void* ptr, void* user_data), void* user_data)
{
- if (!malloc_fn) malloc_fn = malloc;
- ImGuiContext* ctx = (ImGuiContext*)malloc_fn(sizeof(ImGuiContext));
- IM_PLACEMENT_NEW(ctx) ImGuiContext();
- ctx->IO.MemAllocFn = malloc_fn;
- ctx->IO.MemFreeFn = free_fn ? free_fn : free;
+ GImAllocatorAllocFunc = alloc_func;
+ GImAllocatorFreeFunc = free_func;
+ GImAllocatorUserData = user_data;
+}
+
+ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
+{
+ ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
+ if (GImGui == NULL)
+ SetCurrentContext(ctx);
+ Initialize(ctx);
return ctx;
}
void ImGui::DestroyContext(ImGuiContext* ctx)
{
- void (*free_fn)(void*) = ctx->IO.MemFreeFn;
- ctx->~ImGuiContext();
- free_fn(ctx);
+ if (ctx == NULL)
+ ctx = GImGui;
+ Shutdown(ctx);
if (GImGui == ctx)
SetCurrentContext(NULL);
+ IM_DELETE(ctx);
}
ImGuiIO& ImGui::GetIO()
{
+ IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
return GImGui->IO;
}
ImGuiStyle& ImGui::GetStyle()
{
+ IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
return GImGui->Style;
}
-// Same value as passed to your RenderDrawListsFn() function. valid after Render() and until the next call to NewFrame()
+// Same value as passed to the old io.RenderDrawListsFn function. Valid after Render() and until the next call to NewFrame()
ImDrawData* ImGui::GetDrawData()
{
- return GImGui->RenderDrawData.Valid ? &GImGui->RenderDrawData : NULL;
+ ImGuiContext& g = *GImGui;
+ return g.DrawData.Valid ? &g.DrawData : NULL;
}
float ImGui::GetTime()
@@ -2257,81 +2702,608 @@ ImDrawListSharedData* ImGui::GetDrawListSharedData()
return &GImGui->DrawListSharedData;
}
-void ImGui::NewFrame()
+// This needs to be called before we submit any widget (aka in or before Begin)
+void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
{
ImGuiContext& g = *GImGui;
+ IM_ASSERT(window == g.NavWindow);
+ bool init_for_nav = false;
+ if (!(window->Flags & ImGuiWindowFlags_NoNavInputs))
+ if (!(window->Flags & ImGuiWindowFlags_ChildWindow) || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
+ init_for_nav = true;
+ if (init_for_nav)
+ {
+ SetNavID(0, g.NavLayer);
+ g.NavInitRequest = true;
+ g.NavInitRequestFromMove = false;
+ g.NavInitResultId = 0;
+ g.NavInitResultRectRel = ImRect();
+ NavUpdateAnyRequestFlag();
+ }
+ else
+ {
+ g.NavId = window->NavLastIds[0];
+ }
+}
- // Check user data
- // (We pass an error message in the assert expression as a trick to get it visible to programmers who are not using a debugger, as most assert handlers display their argument)
- IM_ASSERT(g.IO.DeltaTime >= 0.0f && "Need a positive DeltaTime (zero is tolerated but will cause some timing issues)");
- IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value");
- IM_ASSERT(g.IO.Fonts->Fonts.Size > 0 && "Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?");
- IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded() && "Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?");
- IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting");
- IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting. Alpha cannot be negative (allows us to avoid a few clamps in color computations)");
- IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
+static ImVec2 NavCalcPreferredMousePos()
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.NavWindow;
+ if (!window)
+ return g.IO.MousePos;
+ const ImRect& rect_rel = window->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.
+}
- // Initialize on first frame
- if (!g.Initialized)
- Initialize();
+static int FindWindowIndex(ImGuiWindow* window) // FIXME-OPT O(N)
+{
+ ImGuiContext& g = *GImGui;
+ for (int i = g.Windows.Size-1; i >= 0; i--)
+ if (g.Windows[i] == window)
+ return i;
+ return -1;
+}
- SetCurrentFont(GetDefaultFont());
- IM_ASSERT(g.Font->IsLoaded());
- g.DrawListSharedData.ClipRectFullscreen = ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y);
- g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
+static ImGuiWindow* FindWindowNavigable(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];
+ return NULL;
+}
- g.Time += g.IO.DeltaTime;
- g.FrameCount += 1;
- g.TooltipOverrideCount = 0;
- g.WindowsActiveCount = 0;
- g.OverlayDrawList.Clear();
- g.OverlayDrawList.PushTextureID(g.IO.Fonts->TexID);
- g.OverlayDrawList.PushClipRectFullScreen();
- g.OverlayDrawList.Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0);
+float ImGui::GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode)
+{
+ ImGuiContext& g = *GImGui;
+ if (mode == ImGuiInputReadMode_Down)
+ return g.IO.NavInputs[n]; // Instant, read analog input (0.0f..1.0f, as provided by user)
- // Mark rendering data as invalid to prevent user who may have a handle on it to use it
- g.RenderDrawData.Valid = false;
- g.RenderDrawData.CmdLists = NULL;
- g.RenderDrawData.CmdListsCount = g.RenderDrawData.TotalVtxCount = g.RenderDrawData.TotalIdxCount = 0;
+ const float t = g.IO.NavInputsDownDuration[n];
+ if (t < 0.0f && mode == ImGuiInputReadMode_Released) // Return 1.0f when just released, no repeat, ignore analog input.
+ return (g.IO.NavInputsDownDurationPrev[n] >= 0.0f ? 1.0f : 0.0f);
+ if (t < 0.0f)
+ return 0.0f;
+ if (mode == ImGuiInputReadMode_Pressed) // Return 1.0f when just pressed, no repeat, ignore analog input.
+ return (t == 0.0f) ? 1.0f : 0.0f;
+ if (mode == ImGuiInputReadMode_Repeat)
+ return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 0.80f, g.IO.KeyRepeatRate * 0.80f);
+ if (mode == ImGuiInputReadMode_RepeatSlow)
+ return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 1.00f, g.IO.KeyRepeatRate * 2.00f);
+ if (mode == ImGuiInputReadMode_RepeatFast)
+ return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 0.80f, g.IO.KeyRepeatRate * 0.30f);
+ return 0.0f;
+}
- // Clear reference to active widget if the widget isn't alive anymore
- if (!g.HoveredIdPreviousFrame)
- g.HoveredIdTimer = 0.0f;
- g.HoveredIdPreviousFrame = g.HoveredId;
- g.HoveredId = 0;
- g.HoveredIdAllowOverlap = false;
- if (!g.ActiveIdIsAlive && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0)
+// Equivalent of IsKeyDown() for NavInputs[]
+static bool IsNavInputDown(ImGuiNavInput n)
+{
+ return GImGui->IO.NavInputs[n] > 0.0f;
+}
+
+// Equivalent of IsKeyPressed() for NavInputs[]
+static bool IsNavInputPressed(ImGuiNavInput n, ImGuiInputReadMode mode)
+{
+ return ImGui::GetNavInputAmount(n, mode) > 0.0f;
+}
+
+static bool IsNavInputPressedAnyOfTwo(ImGuiNavInput n1, ImGuiNavInput n2, ImGuiInputReadMode mode)
+{
+ return (ImGui::GetNavInputAmount(n1, mode) + ImGui::GetNavInputAmount(n2, mode)) > 0.0f;
+}
+
+ImVec2 ImGui::GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInputReadMode mode, float slow_factor, float fast_factor)
+{
+ ImVec2 delta(0.0f, 0.0f);
+ if (dir_sources & ImGuiNavDirSourceFlags_Keyboard)
+ delta += ImVec2(GetNavInputAmount(ImGuiNavInput_KeyRight_, mode) - GetNavInputAmount(ImGuiNavInput_KeyLeft_, mode), GetNavInputAmount(ImGuiNavInput_KeyDown_, mode) - GetNavInputAmount(ImGuiNavInput_KeyUp_, mode));
+ if (dir_sources & ImGuiNavDirSourceFlags_PadDPad)
+ delta += ImVec2(GetNavInputAmount(ImGuiNavInput_DpadRight, mode) - GetNavInputAmount(ImGuiNavInput_DpadLeft, mode), GetNavInputAmount(ImGuiNavInput_DpadDown, mode) - GetNavInputAmount(ImGuiNavInput_DpadUp, mode));
+ if (dir_sources & ImGuiNavDirSourceFlags_PadLStick)
+ delta += ImVec2(GetNavInputAmount(ImGuiNavInput_LStickRight, mode) - GetNavInputAmount(ImGuiNavInput_LStickLeft, mode), GetNavInputAmount(ImGuiNavInput_LStickDown, mode) - GetNavInputAmount(ImGuiNavInput_LStickUp, mode));
+ if (slow_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakSlow))
+ delta *= slow_factor;
+ if (fast_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakFast))
+ delta *= fast_factor;
+ return delta;
+}
+
+static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
+{
+ ImGuiContext& g = *GImGui;
+ IM_ASSERT(g.NavWindowingTarget);
+ if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
+ return;
+
+ const int i_current = FindWindowIndex(g.NavWindowingTarget);
+ ImGuiWindow* window_target = FindWindowNavigable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
+ if (!window_target)
+ window_target = FindWindowNavigable((focus_change_dir < 0) ? (g.Windows.Size - 1) : 0, i_current, focus_change_dir);
+ g.NavWindowingTarget = window_target;
+ g.NavWindowingToggleLayer = false;
+}
+
+// Window management mode (hold to: change focus/move/resize, tap to: toggle menu layer)
+static void ImGui::NavUpdateWindowing()
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* apply_focus_window = NULL;
+ bool apply_toggle_layer = false;
+
+ 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 : FindWindowNavigable(g.Windows.Size - 1, -INT_MAX, -1))
+ {
+ g.NavWindowingTarget = window->RootWindowForTabbing;
+ g.NavWindowingHighlightTimer = g.NavWindowingHighlightAlpha = 0.0f;
+ g.NavWindowingToggleLayer = start_windowing_with_keyboard ? false : true;
+ g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_NavKeyboard : ImGuiInputSource_NavGamepad;
+ }
+
+ // Gamepad update
+ g.NavWindowingHighlightTimer += g.IO.DeltaTime;
+ if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_NavGamepad)
+ {
+ // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
+ g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingHighlightTimer - 0.20f) / 0.05f));
+
+ // Select window to focus
+ const int focus_change_dir = (int)IsNavInputPressed(ImGuiNavInput_FocusPrev, ImGuiInputReadMode_RepeatSlow) - (int)IsNavInputPressed(ImGuiNavInput_FocusNext, ImGuiInputReadMode_RepeatSlow);
+ if (focus_change_dir != 0)
+ {
+ NavUpdateWindowingHighlightWindow(focus_change_dir);
+ g.NavWindowingHighlightAlpha = 1.0f;
+ }
+
+ // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered front-most)
+ if (!IsNavInputDown(ImGuiNavInput_Menu))
+ {
+ g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
+ if (g.NavWindowingToggleLayer && g.NavWindow)
+ apply_toggle_layer = true;
+ else if (!g.NavWindowingToggleLayer)
+ apply_focus_window = g.NavWindowingTarget;
+ g.NavWindowingTarget = NULL;
+ }
+ }
+
+ // Keyboard: Focus
+ if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_NavKeyboard)
+ {
+ // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
+ g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingHighlightTimer - 0.15f) / 0.04f)); // 1.0f
+ if (IsKeyPressedMap(ImGuiKey_Tab, true))
+ NavUpdateWindowingHighlightWindow(g.IO.KeyShift ? +1 : -1);
+ if (!g.IO.KeyCtrl)
+ apply_focus_window = g.NavWindowingTarget;
+ }
+
+ // Keyboard: Press and Release ALT to toggle menu layer
+ // FIXME: We lack an explicit IO variable for "is the imgui window focused", so compare mouse validity to detect the common case of back-end clearing releases all keys on ALT-TAB
+ if ((g.ActiveId == 0 || g.ActiveIdAllowOverlap) && IsNavInputPressed(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Released))
+ if (IsMousePosValid(&g.IO.MousePos) == IsMousePosValid(&g.IO.MousePosPrev))
+ apply_toggle_layer = true;
+
+ // Move window
+ if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
+ {
+ ImVec2 move_delta;
+ if (g.NavInputSource == ImGuiInputSource_NavKeyboard && !g.IO.KeyShift)
+ move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down);
+ if (g.NavInputSource == ImGuiInputSource_NavGamepad)
+ move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down);
+ if (move_delta.x != 0.0f || move_delta.y != 0.0f)
+ {
+ const float NAV_MOVE_SPEED = 800.0f;
+ const float move_speed = ImFloor(NAV_MOVE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y));
+ g.NavWindowingTarget->PosFloat += move_delta * move_speed;
+ g.NavDisableMouseHover = true;
+ MarkIniSettingsDirty(g.NavWindowingTarget);
+ }
+ }
+
+ // Apply final focus
+ if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindowForTabbing))
+ {
+ g.NavDisableHighlight = false;
+ g.NavDisableMouseHover = true;
+ apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window);
+ ClosePopupsOverWindow(apply_focus_window);
+ FocusWindow(apply_focus_window);
+ if (apply_focus_window->NavLastIds[0] == 0)
+ NavInitWindow(apply_focus_window, false);
+
+ // If the window only has a menu layer, select it directly
+ if (apply_focus_window->DC.NavLayerActiveMask == (1 << 1))
+ g.NavLayer = 1;
+ }
+ if (apply_focus_window)
+ g.NavWindowingTarget = NULL;
+
+ // Apply menu/layer toggle
+ if (apply_toggle_layer && g.NavWindow)
+ {
+ 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)
+ new_nav_window = new_nav_window->ParentWindow;
+ if (new_nav_window != g.NavWindow)
+ {
+ ImGuiWindow* old_nav_window = g.NavWindow;
+ FocusWindow(new_nav_window);
+ new_nav_window->NavLastChildNavWindow = old_nav_window;
+ }
+ g.NavDisableHighlight = false;
+ g.NavDisableMouseHover = true;
+ NavRestoreLayer((g.NavWindow->DC.NavLayerActiveMask & (1 << 1)) ? (g.NavLayer ^ 1) : 0);
+ }
+}
+
+// NB: We modify rect_rel by the amount we scrolled for, so it is immediately updated.
+static void NavScrollToBringItemIntoView(ImGuiWindow* window, ImRect& item_rect_rel)
+{
+ // Scroll to keep newly navigated item fully into view
+ ImRect window_rect_rel(window->InnerRect.Min - window->Pos - ImVec2(1, 1), window->InnerRect.Max - window->Pos + ImVec2(1, 1));
+ //g.OverlayDrawList.AddRect(window->Pos + window_rect_rel.Min, window->Pos + window_rect_rel.Max, IM_COL32_WHITE); // [DEBUG]
+ if (window_rect_rel.Contains(item_rect_rel))
+ return;
+
+ ImGuiContext& g = *GImGui;
+ if (window->ScrollbarX && item_rect_rel.Min.x < window_rect_rel.Min.x)
+ {
+ window->ScrollTarget.x = item_rect_rel.Min.x + window->Scroll.x - g.Style.ItemSpacing.x;
+ window->ScrollTargetCenterRatio.x = 0.0f;
+ }
+ else if (window->ScrollbarX && item_rect_rel.Max.x >= window_rect_rel.Max.x)
+ {
+ window->ScrollTarget.x = item_rect_rel.Max.x + window->Scroll.x + g.Style.ItemSpacing.x;
+ window->ScrollTargetCenterRatio.x = 1.0f;
+ }
+ if (item_rect_rel.Min.y < window_rect_rel.Min.y)
+ {
+ window->ScrollTarget.y = item_rect_rel.Min.y + window->Scroll.y - g.Style.ItemSpacing.y;
+ window->ScrollTargetCenterRatio.y = 0.0f;
+ }
+ else if (item_rect_rel.Max.y >= window_rect_rel.Max.y)
+ {
+ window->ScrollTarget.y = item_rect_rel.Max.y + window->Scroll.y + g.Style.ItemSpacing.y;
+ window->ScrollTargetCenterRatio.y = 1.0f;
+ }
+
+ // Estimate upcoming scroll so we can offset our relative mouse position so mouse position can be applied immediately (under this block)
+ ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
+ item_rect_rel.Translate(window->Scroll - next_scroll);
+}
+
+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);
+#endif
+
+ if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad))
+ if (g.IO.NavInputs[ImGuiNavInput_Activate] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Input] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Cancel] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Menu] > 0.0f)
+ g.NavInputSource = ImGuiInputSource_NavGamepad;
+
+ // Update Keyboard->Nav inputs mapping
+ if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard)
+ {
+ #define NAV_MAP_KEY(_KEY, _NAV_INPUT) if (IsKeyDown(g.IO.KeyMap[_KEY])) { g.IO.NavInputs[_NAV_INPUT] = 1.0f; g.NavInputSource = ImGuiInputSource_NavKeyboard; }
+ NAV_MAP_KEY(ImGuiKey_Space, ImGuiNavInput_Activate );
+ NAV_MAP_KEY(ImGuiKey_Enter, ImGuiNavInput_Input );
+ NAV_MAP_KEY(ImGuiKey_Escape, ImGuiNavInput_Cancel );
+ NAV_MAP_KEY(ImGuiKey_LeftArrow, ImGuiNavInput_KeyLeft_ );
+ NAV_MAP_KEY(ImGuiKey_RightArrow,ImGuiNavInput_KeyRight_);
+ NAV_MAP_KEY(ImGuiKey_UpArrow, ImGuiNavInput_KeyUp_ );
+ NAV_MAP_KEY(ImGuiKey_DownArrow, ImGuiNavInput_KeyDown_ );
+ if (g.IO.KeyCtrl) g.IO.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f;
+ if (g.IO.KeyShift) g.IO.NavInputs[ImGuiNavInput_TweakFast] = 1.0f;
+ if (g.IO.KeyAlt) g.IO.NavInputs[ImGuiNavInput_KeyMenu_] = 1.0f;
+ #undef NAV_MAP_KEY
+ }
+
+ memcpy(g.IO.NavInputsDownDurationPrev, g.IO.NavInputsDownDuration, sizeof(g.IO.NavInputsDownDuration));
+ for (int i = 0; i < IM_ARRAYSIZE(g.IO.NavInputs); i++)
+ g.IO.NavInputsDownDuration[i] = (g.IO.NavInputs[i] > 0.0f) ? (g.IO.NavInputsDownDuration[i] < 0.0f ? 0.0f : g.IO.NavInputsDownDuration[i] + g.IO.DeltaTime) : -1.0f;
+
+ // Process navigation init request (select first/default focus)
+ if (g.NavInitResultId != 0 && (!g.NavDisableHighlight || g.NavInitRequestFromMove))
+ {
+ // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
+ IM_ASSERT(g.NavWindow);
+ if (g.NavInitRequestFromMove)
+ SetNavIDWithRectRel(g.NavInitResultId, g.NavLayer, g.NavInitResultRectRel);
+ else
+ SetNavID(g.NavInitResultId, g.NavLayer);
+ g.NavWindow->NavRectRel[g.NavLayer] = g.NavInitResultRectRel;
+ }
+ g.NavInitRequest = false;
+ g.NavInitRequestFromMove = false;
+ g.NavInitResultId = 0;
+ g.NavJustMovedToId = 0;
+
+ // Process navigation move request
+ if (g.NavMoveRequest && (g.NavMoveResultLocal.ID != 0 || g.NavMoveResultOther.ID != 0))
+ {
+ // Select which result to use
+ ImGuiNavMoveResult* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
+ if (g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow) // Maybe entering a flattened child? In this case solve the tie using the regular scoring rules
+ if ((g.NavMoveResultOther.DistBox < g.NavMoveResultLocal.DistBox) || (g.NavMoveResultOther.DistBox == g.NavMoveResultLocal.DistBox && g.NavMoveResultOther.DistCenter < g.NavMoveResultLocal.DistCenter))
+ result = &g.NavMoveResultOther;
+
+ IM_ASSERT(g.NavWindow && result->Window);
+
+ // Scroll to keep newly navigated item fully into view
+ if (g.NavLayer == 0)
+ NavScrollToBringItemIntoView(result->Window, result->RectRel);
+
+ // Apply result from previous frame navigation directional move request
ClearActiveID();
- if (g.ActiveId)
- g.ActiveIdTimer += g.IO.DeltaTime;
- g.ActiveIdPreviousFrame = g.ActiveId;
- g.ActiveIdIsAlive = false;
- g.ActiveIdIsJustActivated = false;
- if (g.ScalarAsInputTextId && g.ActiveId != g.ScalarAsInputTextId)
- g.ScalarAsInputTextId = 0;
+ g.NavWindow = result->Window;
+ SetNavIDWithRectRel(result->ID, g.NavLayer, result->RectRel);
+ g.NavJustMovedToId = result->ID;
+ g.NavMoveFromClampedRefRect = false;
+ }
- // Elapse drag & drop payload
- if (g.DragDropActive && g.DragDropPayload.DataFrameCount + 1 < g.FrameCount)
+ // When a forwarded move request failed, we restore the highlight that we disabled during the forward frame
+ if (g.NavMoveRequestForward == ImGuiNavForward_ForwardActive)
{
- ClearDragDrop();
- g.DragDropPayloadBufHeap.clear();
- memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
+ IM_ASSERT(g.NavMoveRequest);
+ if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0)
+ g.NavDisableHighlight = false;
+ g.NavMoveRequestForward = ImGuiNavForward_None;
}
- g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
- g.DragDropAcceptIdCurr = 0;
- g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
- // Update keyboard input state
- memcpy(g.IO.KeysDownDurationPrev, g.IO.KeysDownDuration, sizeof(g.IO.KeysDownDuration));
- for (int i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++)
- g.IO.KeysDownDuration[i] = g.IO.KeysDown[i] ? (g.IO.KeysDownDuration[i] < 0.0f ? 0.0f : g.IO.KeysDownDuration[i] + g.IO.DeltaTime) : -1.0f;
+ // Apply application mouse position movement, after we had a chance to process move request result.
+ if (g.NavMousePosDirty && g.NavIdIsAlive)
+ {
+ // Set mouse position given our knowledge of the nav widget position from last frame
+ if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (g.IO.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
+ {
+ g.IO.MousePos = g.IO.MousePosPrev = NavCalcPreferredMousePos();
+ g.IO.WantSetMousePos = true;
+ }
+ g.NavMousePosDirty = false;
+ }
+ g.NavIdIsAlive = false;
+ g.NavJustTabbedId = 0;
+ IM_ASSERT(g.NavLayer == 0 || g.NavLayer == 1);
+
+ // Store our return window (for returning from Layer 1 to Layer 0) and clear it as soon as we step back in our own Layer 0
+ if (g.NavWindow)
+ NavSaveLastChildNavWindow(g.NavWindow);
+ if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == 0)
+ g.NavWindow->NavLastChildNavWindow = NULL;
+
+ NavUpdateWindowing();
+
+ // Set output flags for user application
+ bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
+ bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
+ g.IO.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
+ g.IO.NavVisible = (g.IO.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL) || g.NavInitRequest;
+
+ // Process NavCancel input (to close a popup, get back to parent, clear focus)
+ if (IsNavInputPressed(ImGuiNavInput_Cancel, ImGuiInputReadMode_Pressed))
+ {
+ if (g.ActiveId != 0)
+ {
+ ClearActiveID();
+ }
+ else if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow) && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow)
+ {
+ // Exit child window
+ ImGuiWindow* child_window = g.NavWindow;
+ ImGuiWindow* parent_window = g.NavWindow->ParentWindow;
+ IM_ASSERT(child_window->ChildId != 0);
+ FocusWindow(parent_window);
+ SetNavID(child_window->ChildId, 0);
+ g.NavIdIsAlive = false;
+ if (g.NavDisableMouseHover)
+ g.NavMousePosDirty = true;
+ }
+ else if (g.OpenPopupStack.Size > 0)
+ {
+ // Close open popup/menu
+ if (!(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
+ ClosePopupToLevel(g.OpenPopupStack.Size - 1);
+ }
+ else if (g.NavLayer != 0)
+ {
+ // Leave the "menu" layer
+ NavRestoreLayer(0);
+ }
+ else
+ {
+ // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
+ if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
+ g.NavWindow->NavLastIds[0] = 0;
+ g.NavId = 0;
+ }
+ }
+
+ // Process manual activation request
+ g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = 0;
+ if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
+ {
+ bool activate_down = IsNavInputDown(ImGuiNavInput_Activate);
+ bool activate_pressed = activate_down && IsNavInputPressed(ImGuiNavInput_Activate, ImGuiInputReadMode_Pressed);
+ if (g.ActiveId == 0 && activate_pressed)
+ g.NavActivateId = g.NavId;
+ if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_down)
+ g.NavActivateDownId = g.NavId;
+ if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_pressed)
+ g.NavActivatePressedId = g.NavId;
+ if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && IsNavInputPressed(ImGuiNavInput_Input, ImGuiInputReadMode_Pressed))
+ g.NavInputId = g.NavId;
+ }
+ if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
+ g.NavDisableHighlight = true;
+ if (g.NavActivateId != 0)
+ IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
+ g.NavMoveRequest = false;
+
+ // Process programmatic activation request
+ if (g.NavNextActivateId != 0)
+ g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = g.NavNextActivateId;
+ g.NavNextActivateId = 0;
+
+ // Initiate directional inputs request
+ const int allowed_dir_flags = (g.ActiveId == 0) ? ~0 : g.ActiveIdAllowNavDirFlags;
+ if (g.NavMoveRequestForward == ImGuiNavForward_None)
+ {
+ g.NavMoveDir = ImGuiDir_None;
+ 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;
+ if ((allowed_dir_flags & (1<<ImGuiDir_Right)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadRight,ImGuiNavInput_KeyRight_,ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Right;
+ if ((allowed_dir_flags & (1<<ImGuiDir_Up)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadUp, ImGuiNavInput_KeyUp_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Up;
+ if ((allowed_dir_flags & (1<<ImGuiDir_Down)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadDown, ImGuiNavInput_KeyDown_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Down;
+ }
+ }
+ else
+ {
+ // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
+ IM_ASSERT(g.NavMoveDir != ImGuiDir_None);
+ IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_ForwardQueued);
+ g.NavMoveRequestForward = ImGuiNavForward_ForwardActive;
+ }
+
+ if (g.NavMoveDir != ImGuiDir_None)
+ {
+ g.NavMoveRequest = true;
+ g.NavMoveDirLast = g.NavMoveDir;
+ }
+
+ // If we initiate a movement request and have no current NavId, we initiate a InitDefautRequest that will be used as a fallback if the direction fails to find a match
+ if (g.NavMoveRequest && g.NavId == 0)
+ {
+ g.NavInitRequest = g.NavInitRequestFromMove = true;
+ g.NavInitResultId = 0;
+ g.NavDisableHighlight = false;
+ }
+
+ NavUpdateAnyRequestFlag();
+
+ // Scrolling
+ if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
+ {
+ // *Fallback* manual-scroll with NavUp/NavDown when window has no navigable item
+ ImGuiWindow* window = g.NavWindow;
+ const float scroll_speed = ImFloor(window->CalcFontSize() * 100 * g.IO.DeltaTime + 0.5f); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
+ if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll && g.NavMoveRequest)
+ {
+ if (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right)
+ SetWindowScrollX(window, ImFloor(window->Scroll.x + ((g.NavMoveDir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
+ if (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down)
+ SetWindowScrollY(window, ImFloor(window->Scroll.y + ((g.NavMoveDir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
+ }
+
+ // *Normal* Manual scroll with NavScrollXXX keys
+ // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
+ ImVec2 scroll_dir = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down, 1.0f/10.0f, 10.0f);
+ if (scroll_dir.x != 0.0f && window->ScrollbarX)
+ {
+ SetWindowScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed));
+ g.NavMoveFromClampedRefRect = true;
+ }
+ if (scroll_dir.y != 0.0f)
+ {
+ SetWindowScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed));
+ g.NavMoveFromClampedRefRect = true;
+ }
+ }
+
+ // Reset search results
+ g.NavMoveResultLocal.Clear();
+ g.NavMoveResultOther.Clear();
+
+ // When we have manually scrolled (without using navigation) and NavId becomes out of bounds, we project its bounding box to the visible area to restart navigation within visible items
+ if (g.NavMoveRequest && g.NavMoveFromClampedRefRect && g.NavLayer == 0)
+ {
+ ImGuiWindow* window = g.NavWindow;
+ ImRect window_rect_rel(window->InnerRect.Min - window->Pos - ImVec2(1,1), window->InnerRect.Max - window->Pos + ImVec2(1,1));
+ if (!window_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
+ {
+ float pad = window->CalcFontSize() * 0.5f;
+ window_rect_rel.Expand(ImVec2(-ImMin(window_rect_rel.GetWidth(), pad), -ImMin(window_rect_rel.GetHeight(), pad))); // Terrible approximation for the intent of starting navigation from first fully visible item
+ window->NavRectRel[g.NavLayer].ClipWith(window_rect_rel);
+ g.NavId = 0;
+ }
+ g.NavMoveFromClampedRefRect = false;
+ }
+
+ // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
+ ImRect nav_rect_rel = (g.NavWindow && !g.NavWindow->NavRectRel[g.NavLayer].IsInverted()) ? g.NavWindow->NavRectRel[g.NavLayer] : ImRect(0,0,0,0);
+ g.NavScoringRectScreen = g.NavWindow ? ImRect(g.NavWindow->Pos + nav_rect_rel.Min, g.NavWindow->Pos + nav_rect_rel.Max) : GetViewportRect();
+ g.NavScoringRectScreen.Min.x = ImMin(g.NavScoringRectScreen.Min.x + 1.0f, g.NavScoringRectScreen.Max.x);
+ g.NavScoringRectScreen.Max.x = g.NavScoringRectScreen.Min.x;
+ IM_ASSERT(!g.NavScoringRectScreen.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allows us to remove extraneous fabsf() calls in NavScoreItem().
+ //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++) g.OverlayDrawList.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 = NavCalcPreferredMousePos(); 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); }
+#endif
+}
+
+static void ImGui::NewFrameUpdateMovingWindow()
+{
+ ImGuiContext& g = *GImGui;
+ if (g.MovingWindow && g.MovingWindow->MoveId == g.ActiveId && g.ActiveIdSource == ImGuiInputSource_Mouse)
+ {
+ // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
+ // We track it to preserve Focus and so that ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
+ KeepAliveID(g.ActiveId);
+ IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindow);
+ ImGuiWindow* moving_window = g.MovingWindow->RootWindow;
+ if (g.IO.MouseDown[0])
+ {
+ ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
+ if (moving_window->PosFloat.x != pos.x || moving_window->PosFloat.y != pos.y)
+ {
+ MarkIniSettingsDirty(moving_window);
+ moving_window->PosFloat = pos;
+ }
+ FocusWindow(g.MovingWindow);
+ }
+ else
+ {
+ ClearActiveID();
+ g.MovingWindow = NULL;
+ }
+ }
+ else
+ {
+ // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
+ if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
+ {
+ KeepAliveID(g.ActiveId);
+ if (!g.IO.MouseDown[0])
+ ClearActiveID();
+ }
+ g.MovingWindow = NULL;
+ }
+}
+
+static void ImGui::NewFrameUpdateMouseInputs()
+{
+ ImGuiContext& g = *GImGui;
- // Update mouse input state
// If mouse just appeared or disappeared (usually denoted by -FLT_MAX component, but in reality we test for -256000.0f) we cancel out movement in MouseDelta
- if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MousePosPrev))
+ if (ImGui::IsMousePosValid(&g.IO.MousePos) && ImGui::IsMousePosValid(&g.IO.MousePosPrev))
g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev;
else
g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
+ if (g.IO.MouseDelta.x != 0.0f || g.IO.MouseDelta.y != 0.0f)
+ g.NavDisableMouseHover = false;
+
g.IO.MousePosPrev = g.IO.MousePos;
for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
{
@@ -2363,70 +3335,34 @@ void ImGui::NewFrame()
g.IO.MouseDragMaxDistanceAbs[i].y = ImMax(g.IO.MouseDragMaxDistanceAbs[i].y, mouse_delta.y < 0.0f ? -mouse_delta.y : mouse_delta.y);
g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(mouse_delta));
}
+ if (g.IO.MouseClicked[i]) // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
+ g.NavDisableMouseHover = false;
}
+}
- // Calculate frame-rate for the user, as a purely luxurious feature
- g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
- g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
- g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
- g.IO.Framerate = 1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame));
-
- // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering). Only valid for root windows.
- if (g.MovingWindowMoveId && g.MovingWindowMoveId == g.ActiveId)
- {
- KeepAliveID(g.MovingWindowMoveId);
- IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindow);
- IM_ASSERT(g.MovingWindow->MoveId == g.MovingWindowMoveId);
- if (g.IO.MouseDown[0])
- {
- ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
- if (g.MovingWindow->RootWindow->PosFloat.x != pos.x || g.MovingWindow->RootWindow->PosFloat.y != pos.y)
- MarkIniSettingsDirty(g.MovingWindow->RootWindow);
- g.MovingWindow->RootWindow->PosFloat = pos;
- FocusWindow(g.MovingWindow);
- }
- else
- {
- ClearActiveID();
- g.MovingWindow = NULL;
- g.MovingWindowMoveId = 0;
- }
- }
- else
- {
- g.MovingWindow = NULL;
- g.MovingWindowMoveId = 0;
- }
-
- // Delay saving settings so we don't spam disk too much
- if (g.SettingsDirtyTimer > 0.0f)
- {
- g.SettingsDirtyTimer -= g.IO.DeltaTime;
- if (g.SettingsDirtyTimer <= 0.0f)
- SaveIniSettingsToDisk(g.IO.IniFilename);
- }
+// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
+void ImGui::NewFrameUpdateHoveredWindowAndCaptureFlags()
+{
+ ImGuiContext& g = *GImGui;
- // Find the window we are hovering
+ // Find the window hovered by mouse:
// - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
- // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point.
+ // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
// - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
- g.HoveredWindow = (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoInputs)) ? g.MovingWindow : FindHoveredWindow(g.IO.MousePos);
+ g.HoveredWindow = (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoInputs)) ? g.MovingWindow : FindHoveredWindow();
g.HoveredRootWindow = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
+ // Modal windows prevents cursor from hovering behind them.
ImGuiWindow* modal_window = GetFrontMostModalRootWindow();
- if (modal_window != NULL)
- {
- g.ModalWindowDarkeningRatio = ImMin(g.ModalWindowDarkeningRatio + g.IO.DeltaTime * 6.0f, 1.0f);
+ if (modal_window)
if (g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, modal_window))
g.HoveredRootWindow = g.HoveredWindow = NULL;
- }
- else
- {
- g.ModalWindowDarkeningRatio = 0.0f;
- }
- // Update the WantCaptureMouse/WantCAptureKeyboard flags, so user can capture/discard the inputs away from the rest of their application.
- // When clicking outside of a window we assume the click is owned by the application and won't request capture. We need to track click ownership.
+ // Disabled mouse?
+ if (g.IO.ConfigFlags & ImGuiConfigFlags_NoMouse)
+ g.HoveredWindow = g.HoveredRootWindow = NULL;
+
+ // We track click ownership. When clicked outside of a window the click is owned by the application and won't report hovering nor request capture even while dragging over our windows afterward.
int mouse_earliest_button_down = -1;
bool mouse_any_down = false;
for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
@@ -2438,63 +3374,196 @@ void ImGui::NewFrame()
if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[i] < g.IO.MouseClickedTime[mouse_earliest_button_down])
mouse_earliest_button_down = i;
}
- bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down];
+ const bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down];
+
+ // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
+ // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
+ const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
+ if (!mouse_avail_to_imgui && !mouse_dragging_extern_payload)
+ g.HoveredWindow = g.HoveredRootWindow = NULL;
+
+ // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to imgui, false = dispatch mouse info to imgui + app)
if (g.WantCaptureMouseNextFrame != -1)
g.IO.WantCaptureMouse = (g.WantCaptureMouseNextFrame != 0);
else
g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (!g.OpenPopupStack.empty());
+
+ // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to imgui, false = dispatch keyboard info to imgui + app)
if (g.WantCaptureKeyboardNextFrame != -1)
g.IO.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
else
g.IO.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
+ if (g.IO.NavActive && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
+ g.IO.WantCaptureKeyboard = true;
+
+ // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
g.IO.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : 0;
+}
+
+void ImGui::NewFrame()
+{
+ IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
+ ImGuiContext& g = *GImGui;
+
+ // Check user data
+ // (We pass an error message in the assert expression as a trick to get it visible to programmers who are not using a debugger, as most assert handlers display their argument)
+ IM_ASSERT(g.Initialized);
+ IM_ASSERT(g.IO.DeltaTime >= 0.0f && "Need a positive DeltaTime (zero is tolerated but will cause some timing issues)");
+ IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value");
+ IM_ASSERT(g.IO.Fonts->Fonts.Size > 0 && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
+ IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded() && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
+ IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting");
+ IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting. Alpha cannot be negative (allows us to avoid a few clamps in color computations)");
+ IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
+ for (int n = 0; n < ImGuiKey_COUNT; n++)
+ IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < IM_ARRAYSIZE(g.IO.KeysDown) && "io.KeyMap[] contains an out of bound value (need to be 0..512, or -1 for unmapped key)");
+
+ // Do a simple check for required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was super recently added in 1.60 WIP)
+ if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard)
+ IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
+
+ // Load settings on first frame
+ if (!g.SettingsLoaded)
+ {
+ IM_ASSERT(g.SettingsWindows.empty());
+ LoadIniSettingsFromDisk(g.IO.IniFilename);
+ g.SettingsLoaded = true;
+ }
+
+ // Save settings (with a delay so we don't spam disk too much)
+ if (g.SettingsDirtyTimer > 0.0f)
+ {
+ g.SettingsDirtyTimer -= g.IO.DeltaTime;
+ if (g.SettingsDirtyTimer <= 0.0f)
+ SaveIniSettingsToDisk(g.IO.IniFilename);
+ }
+
+ g.Time += g.IO.DeltaTime;
+ g.FrameCount += 1;
+ g.TooltipOverrideCount = 0;
+ g.WindowsActiveCount = 0;
+
+ SetCurrentFont(GetDefaultFont());
+ IM_ASSERT(g.Font->IsLoaded());
+ g.DrawListSharedData.ClipRectFullscreen = ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y);
+ g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
+
+ g.OverlayDrawList.Clear();
+ g.OverlayDrawList.PushTextureID(g.IO.Fonts->TexID);
+ g.OverlayDrawList.PushClipRectFullScreen();
+ g.OverlayDrawList.Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0);
+
+ // Mark rendering data as invalid to prevent user who may have a handle on it to use it
+ g.DrawData.Clear();
+
+ // Clear reference to active widget if the widget isn't alive anymore
+ if (!g.HoveredIdPreviousFrame)
+ g.HoveredIdTimer = 0.0f;
+ g.HoveredIdPreviousFrame = g.HoveredId;
+ g.HoveredId = 0;
+ g.HoveredIdAllowOverlap = false;
+ if (!g.ActiveIdIsAlive && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0)
+ ClearActiveID();
+ if (g.ActiveId)
+ g.ActiveIdTimer += g.IO.DeltaTime;
+ g.ActiveIdPreviousFrame = g.ActiveId;
+ g.ActiveIdIsAlive = false;
+ g.ActiveIdIsJustActivated = false;
+ if (g.ScalarAsInputTextId && g.ActiveId != g.ScalarAsInputTextId)
+ g.ScalarAsInputTextId = 0;
+
+ // Elapse drag & drop payload
+ if (g.DragDropActive && g.DragDropPayload.DataFrameCount + 1 < g.FrameCount)
+ {
+ ClearDragDrop();
+ g.DragDropPayloadBufHeap.clear();
+ memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
+ }
+ g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
+ g.DragDropAcceptIdCurr = 0;
+ g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
+
+ // Update keyboard input state
+ memcpy(g.IO.KeysDownDurationPrev, g.IO.KeysDownDuration, sizeof(g.IO.KeysDownDuration));
+ for (int i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++)
+ g.IO.KeysDownDuration[i] = g.IO.KeysDown[i] ? (g.IO.KeysDownDuration[i] < 0.0f ? 0.0f : g.IO.KeysDownDuration[i] + g.IO.DeltaTime) : -1.0f;
+
+ // Update gamepad/keyboard directional navigation
+ NavUpdate();
+
+ // Update mouse input state
+ NewFrameUpdateMouseInputs();
+
+ // Calculate frame-rate for the user, as a purely luxurious feature
+ g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
+ g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
+ g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
+ g.IO.Framerate = 1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame));
+
+ // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
+ NewFrameUpdateMovingWindow();
+ NewFrameUpdateHoveredWindowAndCaptureFlags();
+
+ if (GetFrontMostModalRootWindow() != NULL)
+ g.ModalWindowDarkeningRatio = ImMin(g.ModalWindowDarkeningRatio + g.IO.DeltaTime * 6.0f, 1.0f);
+ else
+ g.ModalWindowDarkeningRatio = 0.0f;
+
g.MouseCursor = ImGuiMouseCursor_Arrow;
g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
g.OsImePosRequest = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default
- // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
- // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
- bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
- if (!mouse_avail_to_imgui && !mouse_dragging_extern_payload)
- g.HoveredWindow = g.HoveredRootWindow = NULL;
-
- // Scale & Scrolling
- if (g.HoveredWindow && g.IO.MouseWheel != 0.0f && !g.HoveredWindow->Collapsed)
+ // Mouse wheel scrolling, scale
+ if (g.HoveredWindow && !g.HoveredWindow->Collapsed && (g.IO.MouseWheel != 0.0f || g.IO.MouseWheelH != 0.0f))
{
+ // 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;
- if (g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
- {
- // Zoom / Scale window
- const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
- const float scale = new_font_scale / window->FontWindowScale;
- window->FontWindowScale = new_font_scale;
+ 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)
+ scroll_window = scroll_window->ParentWindow;
+ const bool scroll_allowed = !(scroll_window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(scroll_window->Flags & ImGuiWindowFlags_NoInputs);
- const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
- window->Pos += offset;
- window->PosFloat += offset;
- window->Size *= scale;
- window->SizeFull *= scale;
- }
- else if (!g.IO.KeyCtrl)
+ if (g.IO.MouseWheel != 0.0f)
{
- // Mouse wheel Scrolling
- // 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* 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)
- scroll_window = scroll_window->ParentWindow;
-
- if (!(scroll_window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(scroll_window->Flags & ImGuiWindowFlags_NoInputs))
+ if (g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
{
+ // Zoom / Scale window
+ const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
+ const float scale = new_font_scale / window->FontWindowScale;
+ window->FontWindowScale = new_font_scale;
+
+ const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
+ window->Pos += offset;
+ window->PosFloat += offset;
+ window->Size *= scale;
+ window->SizeFull *= scale;
+ }
+ else if (!g.IO.KeyCtrl && scroll_allowed)
+ {
+ // Mouse wheel vertical scrolling
float scroll_amount = 5 * scroll_window->CalcFontSize();
scroll_amount = (float)(int)ImMin(scroll_amount, (scroll_window->ContentsRegionRect.GetHeight() + scroll_window->WindowPadding.y * 2.0f) * 0.67f);
SetWindowScrollY(scroll_window, scroll_window->Scroll.y - g.IO.MouseWheel * scroll_amount);
}
}
+ if (g.IO.MouseWheelH != 0.0f && scroll_allowed)
+ {
+ // Mouse wheel horizontal scrolling (for hardware that supports it)
+ float scroll_amount = scroll_window->CalcFontSize();
+ if (!g.IO.KeyCtrl && !(window->Flags & ImGuiWindowFlags_NoScrollWithMouse))
+ SetWindowScrollX(window, window->Scroll.x - g.IO.MouseWheelH * scroll_amount);
+ }
}
// Pressing TAB activate widget focus
- if (g.ActiveId == 0 && g.NavWindow != NULL && g.NavWindow->Active && IsKeyPressedMap(ImGuiKey_Tab, false))
- g.NavWindow->FocusIdxTabRequestNext = 0;
+ if (g.ActiveId == 0 && g.NavWindow != NULL && g.NavWindow->Active && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab, false))
+ {
+ if (g.NavId != 0 && g.NavIdTabCounter != INT_MAX)
+ g.NavWindow->FocusIdxTabRequestNext = g.NavIdTabCounter + 1 + (g.IO.KeyShift ? -1 : 1);
+ else
+ g.NavWindow->FocusIdxTabRequestNext = g.IO.KeyShift ? -1 : 0;
+ }
+ g.NavIdTabCounter = INT_MAX;
// Mark all windows as not visible
for (int i = 0; i != g.Windows.Size; i++)
@@ -2507,13 +3576,13 @@ 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)
- FocusPreviousWindow();
+ FocusFrontMostActiveWindow(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);
- CloseInactivePopups(g.NavWindow);
+ ClosePopupsOverWindow(g.NavWindow);
// Create implicit window - 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.
@@ -2521,7 +3590,7 @@ void ImGui::NewFrame()
Begin("Debug##Default");
}
-static void* SettingsHandlerWindow_ReadOpen(ImGuiContext&, const char* name)
+static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
{
ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHash(name, 0));
if (!settings)
@@ -2529,7 +3598,7 @@ static void* SettingsHandlerWindow_ReadOpen(ImGuiContext&, const char* name)
return (void*)settings;
}
-static void SettingsHandlerWindow_ReadLine(ImGuiContext&, void* entry, const char* line)
+static void SettingsHandlerWindow_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
{
ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
float x, y;
@@ -2539,9 +3608,10 @@ static void SettingsHandlerWindow_ReadLine(ImGuiContext&, void* entry, const cha
else if (sscanf(line, "Collapsed=%d", &i) == 1) settings->Collapsed = (i != 0);
}
-static void SettingsHandlerWindow_WriteAll(ImGuiContext& g, ImGuiTextBuffer* buf)
+static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
{
// Gather data from windows that were active during this session
+ ImGuiContext& g = *imgui_ctx;
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
@@ -2566,7 +3636,7 @@ static void SettingsHandlerWindow_WriteAll(ImGuiContext& g, ImGuiTextBuffer* buf
const char* name = settings->Name;
if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
name = p;
- buf->appendf("[Window][%s]\n", name);
+ buf->appendf("[%s][%s]\n", handler->TypeName, name);
buf->appendf("Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y);
buf->appendf("Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y);
buf->appendf("Collapsed=%d\n", settings->Collapsed);
@@ -2574,9 +3644,10 @@ static void SettingsHandlerWindow_WriteAll(ImGuiContext& g, ImGuiTextBuffer* buf
}
}
-void ImGui::Initialize()
+void ImGui::Initialize(ImGuiContext* context)
{
- ImGuiContext& g = *GImGui;
+ ImGuiContext& g = *context;
+ IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
g.LogClipboard = IM_NEW(ImGuiTextBuffer)();
// Add .ini handle for ImGuiWindow type
@@ -2588,20 +3659,17 @@ void ImGui::Initialize()
ini_handler.WriteAllFn = SettingsHandlerWindow_WriteAll;
g.SettingsHandlers.push_front(ini_handler);
- // Load .ini file
- IM_ASSERT(g.SettingsWindows.empty());
- LoadIniSettingsFromDisk(g.IO.IniFilename);
g.Initialized = true;
}
// This function is merely here to free heap allocations.
-void ImGui::Shutdown()
+void ImGui::Shutdown(ImGuiContext* context)
{
- ImGuiContext& g = *GImGui;
+ ImGuiContext& g = *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)
- if (g.IO.Fonts) // Testing for NULL to allow user to NULLify in case of running Shutdown() on multiple contexts. Bit hacky.
- g.IO.Fonts->Clear();
+ if (g.IO.Fonts && g.FontAtlasOwnedByContext)
+ IM_DELETE(g.IO.Fonts);
// Cleanup of other data are conditional on actually having initialize ImGui.
if (!g.Initialized)
@@ -2609,6 +3677,7 @@ void ImGui::Shutdown()
SaveIniSettingsToDisk(g.IO.IniFilename);
+ // Clear everything else
for (int i = 0; i < g.Windows.Size; i++)
IM_DELETE(g.Windows[i]);
g.Windows.clear();
@@ -2628,10 +3697,7 @@ void ImGui::Shutdown()
g.FontStack.clear();
g.OpenPopupStack.clear();
g.CurrentPopupStack.clear();
- g.SetNextWindowSizeConstraintCallback = NULL;
- g.SetNextWindowSizeConstraintCallbackUserData = NULL;
- for (int i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++)
- g.RenderDrawLists[i].clear();
+ g.DrawDataBuilder.ClearFreeMemory();
g.OverlayDrawList.ClearFreeMemory();
g.PrivateClipboard.clear();
g.InputTextState.Text.clear();
@@ -2682,9 +3748,10 @@ static void LoadIniSettingsFromDisk(const char* ini_filename)
ImGui::MemFree(file_data);
}
-ImGuiSettingsHandler* ImGui::FindSettingsHandler(ImGuiID type_hash)
+ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
{
ImGuiContext& g = *GImGui;
+ const ImGuiID type_hash = ImHash(type_name, 0, 0);
for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
if (g.SettingsHandlers[handler_n].TypeHash == type_hash)
return &g.SettingsHandlers[handler_n];
@@ -2700,7 +3767,7 @@ static void LoadIniSettingsFromMemory(const char* buf_readonly)
ImGuiContext& g = *GImGui;
void* entry_data = NULL;
- const ImGuiSettingsHandler* entry_handler = NULL;
+ ImGuiSettingsHandler* entry_handler = NULL;
char* line_end = NULL;
for (char* line = buf; line < buf_end; line = line_end + 1)
@@ -2719,7 +3786,7 @@ static void LoadIniSettingsFromMemory(const char* buf_readonly)
line_end[-1] = 0;
const char* name_end = line_end - 1;
const char* type_start = line + 1;
- char* type_end = ImStrchrRange(type_start, name_end, ']');
+ char* type_end = (char*)(intptr_t)ImStrchrRange(type_start, name_end, ']');
const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
if (!type_end || !name_start)
{
@@ -2731,17 +3798,17 @@ static void LoadIniSettingsFromMemory(const char* buf_readonly)
*type_end = 0; // Overwrite first ']'
name_start++; // Skip second '['
}
- const ImGuiID type_hash = ImHash(type_start, 0, 0);
- entry_handler = ImGui::FindSettingsHandler(type_hash);
- entry_data = entry_handler ? entry_handler->ReadOpenFn(g, name_start) : NULL;
+ entry_handler = ImGui::FindSettingsHandler(type_start);
+ entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
}
else if (entry_handler != NULL && entry_data != NULL)
{
// Let type handler parse the line
- entry_handler->ReadLineFn(g, entry_data, line);
+ entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
}
}
ImGui::MemFree(buf);
+ g.SettingsLoaded = true;
}
static void SaveIniSettingsToDisk(const char* ini_filename)
@@ -2768,7 +3835,10 @@ static void SaveIniSettingsToMemory(ImVector<char>& out_buf)
ImGuiTextBuffer buf;
for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
- g.SettingsHandlers[handler_n].WriteAllFn(g, &buf);
+ {
+ ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n];
+ handler->WriteAllFn(&g, handler, &buf);
+ }
buf.Buf.pop_back(); // Remove extra zero-terminator used by ImGuiTextBuffer
out_buf.swap(buf.Buf);
@@ -2790,10 +3860,10 @@ static void MarkIniSettingsDirty(ImGuiWindow* window)
}
// FIXME: Add a more explicit sort order in the window structure.
-static int ChildWindowComparer(const void* lhs, const void* rhs)
+static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
{
- const ImGuiWindow* a = *(const ImGuiWindow**)lhs;
- const ImGuiWindow* b = *(const ImGuiWindow**)rhs;
+ const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
+ const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
return d;
if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
@@ -2801,9 +3871,9 @@ static int ChildWindowComparer(const void* lhs, const void* rhs)
return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
}
-static void AddWindowToSortedBuffer(ImVector<ImGuiWindow*>& out_sorted_windows, ImGuiWindow* window)
+static void AddWindowToSortedBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
{
- out_sorted_windows.push_back(window);
+ out_sorted_windows->push_back(window);
if (window->Active)
{
int count = window->DC.ChildWindows.Size;
@@ -2818,7 +3888,7 @@ static void AddWindowToSortedBuffer(ImVector<ImGuiWindow*>& out_sorted_windows,
}
}
-static void AddDrawListToRenderList(ImVector<ImDrawList*>& out_render_list, ImDrawList* draw_list)
+static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_render_list, ImDrawList* draw_list)
{
if (draw_list->CmdBuffer.empty())
return;
@@ -2837,9 +3907,9 @@ static void AddDrawListToRenderList(ImVector<ImDrawList*>& out_render_list, ImDr
IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
- // Check that draw_list doesn't use more vertices than indexable in a single draw call (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window)
+ // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window)
// If this assert triggers because you are drawing lots of stuff manually:
- // A) Make sure you are coarse clipping, because ImDrawList let all your vertices pass. You can use thre Metrics window to inspect draw list contents.
+ // A) Make sure you are coarse clipping, because ImDrawList let all your vertices pass. You can use the Metrics window to inspect draw list contents.
// B) If you need/want meshes with more than 64K vertices, uncomment the '#define ImDrawIdx unsigned int' line in imconfig.h to set the index size to 4 bytes.
// You'll need to handle the 4-bytes indices to your renderer. For example, the OpenGL example code detect index size at compile-time by doing:
// glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
@@ -2848,36 +3918,59 @@ static void AddDrawListToRenderList(ImVector<ImDrawList*>& out_render_list, ImDr
if (sizeof(ImDrawIdx) == 2)
IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above");
- out_render_list.push_back(draw_list);
- GImGui->IO.MetricsRenderVertices += draw_list->VtxBuffer.Size;
- GImGui->IO.MetricsRenderIndices += draw_list->IdxBuffer.Size;
+ out_render_list->push_back(draw_list);
}
-static void AddWindowToRenderList(ImVector<ImDrawList*>& out_render_list, ImGuiWindow* window)
+static void AddWindowToDrawData(ImVector<ImDrawList*>* out_render_list, ImGuiWindow* window)
{
- AddDrawListToRenderList(out_render_list, window->DrawList);
+ AddDrawListToDrawData(out_render_list, window->DrawList);
for (int i = 0; i < window->DC.ChildWindows.Size; i++)
{
ImGuiWindow* child = window->DC.ChildWindows[i];
- if (!child->Active) // clipped children may have been marked not active
- continue;
- if ((child->Flags & ImGuiWindowFlags_Popup) && child->HiddenFrames > 0)
- continue;
- AddWindowToRenderList(out_render_list, child);
+ if (child->Active && child->HiddenFrames == 0) // clipped children may have been marked not active
+ AddWindowToDrawData(out_render_list, child);
}
}
-static void AddWindowToRenderListSelectLayer(ImGuiWindow* window)
+static void AddWindowToDrawDataSelectLayer(ImGuiWindow* window)
{
- // FIXME: Generalize this with a proper layering system so e.g. user can draw in specific layers, below text, ..
ImGuiContext& g = *GImGui;
g.IO.MetricsActiveWindows++;
- if (window->Flags & ImGuiWindowFlags_Popup)
- AddWindowToRenderList(g.RenderDrawLists[1], window);
- else if (window->Flags & ImGuiWindowFlags_Tooltip)
- AddWindowToRenderList(g.RenderDrawLists[2], window);
+ if (window->Flags & ImGuiWindowFlags_Tooltip)
+ AddWindowToDrawData(&g.DrawDataBuilder.Layers[1], window);
else
- AddWindowToRenderList(g.RenderDrawLists[0], window);
+ AddWindowToDrawData(&g.DrawDataBuilder.Layers[0], window);
+}
+
+void ImDrawDataBuilder::FlattenIntoSingleLayer()
+{
+ int n = Layers[0].Size;
+ int size = n;
+ for (int i = 1; i < IM_ARRAYSIZE(Layers); i++)
+ size += Layers[i].Size;
+ Layers[0].resize(size);
+ for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++)
+ {
+ ImVector<ImDrawList*>& layer = Layers[layer_n];
+ if (layer.empty())
+ continue;
+ memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
+ n += layer.Size;
+ layer.resize(0);
+ }
+}
+
+static void SetupDrawData(ImVector<ImDrawList*>* draw_lists, ImDrawData* out_draw_data)
+{
+ out_draw_data->Valid = true;
+ out_draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL;
+ out_draw_data->CmdListsCount = draw_lists->Size;
+ out_draw_data->TotalVtxCount = out_draw_data->TotalIdxCount = 0;
+ for (int n = 0; n < draw_lists->Size; n++)
+ {
+ out_draw_data->TotalVtxCount += draw_lists->Data[n]->VtxBuffer.Size;
+ out_draw_data->TotalIdxCount += draw_lists->Data[n]->IdxBuffer.Size;
+ }
}
// When using this function it is sane to ensure that float are perfectly rounded to integer values, to that e.g. (int)(max.x-min.x) in user's render produce correct result.
@@ -2914,7 +4007,7 @@ void ImGui::EndFrame()
IM_ASSERT(g.CurrentWindowStack.Size == 1); // Mismatched Begin()/End() calls
if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
g.CurrentWindow->Active = false;
- ImGui::End();
+ End();
if (g.ActiveId == 0 && g.HoveredId == 0)
{
@@ -2925,14 +4018,13 @@ void ImGui::EndFrame()
{
if (g.HoveredRootWindow != NULL)
{
+ // Set ActiveId even if the _NoMove flag is set, without it dragging away from a window with _NoMove would activate hover on other windows.
FocusWindow(g.HoveredWindow);
+ SetActiveID(g.HoveredWindow->MoveId, g.HoveredWindow);
+ g.NavDisableHighlight = true;
+ g.ActiveIdClickOffset = g.IO.MousePos - g.HoveredRootWindow->Pos;
if (!(g.HoveredWindow->Flags & ImGuiWindowFlags_NoMove) && !(g.HoveredRootWindow->Flags & ImGuiWindowFlags_NoMove))
- {
g.MovingWindow = g.HoveredWindow;
- g.MovingWindowMoveId = g.MovingWindow->MoveId;
- SetActiveID(g.MovingWindowMoveId, g.HoveredRootWindow);
- g.ActiveIdClickOffset = g.IO.MousePos - g.MovingWindow->RootWindow->Pos;
- }
}
else if (g.NavWindow != NULL && GetFrontMostModalRootWindow() == NULL)
{
@@ -2942,7 +4034,7 @@ void ImGui::EndFrame()
}
// With right mouse button we close popups without changing focus
- // (The left mouse button path calls FocusWindow which will lead NewFrame->CloseInactivePopups to trigger)
+ // (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.
@@ -2959,7 +4051,7 @@ void ImGui::EndFrame()
if (window == g.HoveredWindow)
hovered_window_above_modal = true;
}
- CloseInactivePopups(hovered_window_above_modal ? g.HoveredWindow : modal);
+ ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal);
}
}
}
@@ -2973,15 +4065,16 @@ 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);
+ AddWindowToSortedBuffer(&g.WindowsSortBuffer, window);
}
IM_ASSERT(g.Windows.Size == g.WindowsSortBuffer.Size); // we done something wrong
g.Windows.swap(g.WindowsSortBuffer);
// Clear Input data for next frame
- g.IO.MouseWheel = 0.0f;
+ g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters));
+ memset(g.IO.NavInputs, 0, sizeof(g.IO.NavInputs));
g.FrameCountEnded = g.FrameCount;
}
@@ -2995,64 +4088,47 @@ void ImGui::Render()
ImGui::EndFrame();
g.FrameCountRendered = g.FrameCount;
- // Skip render altogether if alpha is 0.0
- // Note that vertex buffers have been created and are wasted, so it is best practice that you don't create windows in the first place, or consistently respond to Begin() returning false.
- if (g.Style.Alpha > 0.0f)
- {
- // Gather windows to render
- g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = g.IO.MetricsActiveWindows = 0;
- for (int i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++)
- g.RenderDrawLists[i].resize(0);
- for (int i = 0; i != g.Windows.Size; i++)
- {
- ImGuiWindow* window = g.Windows[i];
- if (window->Active && window->HiddenFrames <= 0 && (window->Flags & (ImGuiWindowFlags_ChildWindow)) == 0)
- AddWindowToRenderListSelectLayer(window);
- }
-
- // Flatten layers
- int n = g.RenderDrawLists[0].Size;
- int flattened_size = n;
- for (int i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++)
- flattened_size += g.RenderDrawLists[i].Size;
- g.RenderDrawLists[0].resize(flattened_size);
- for (int i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++)
- {
- ImVector<ImDrawList*>& layer = g.RenderDrawLists[i];
- if (layer.empty())
- continue;
- memcpy(&g.RenderDrawLists[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
- n += layer.Size;
- }
-
- // Draw software mouse cursor if requested
- if (g.IO.MouseDrawCursor)
- {
- const ImGuiMouseCursorData& cursor_data = g.MouseCursorData[g.MouseCursor];
- const ImVec2 pos = g.IO.MousePos - cursor_data.HotOffset;
- const ImVec2 size = cursor_data.Size;
- const ImTextureID tex_id = g.IO.Fonts->TexID;
- g.OverlayDrawList.PushTextureID(tex_id);
- g.OverlayDrawList.AddImage(tex_id, pos+ImVec2(1,0), pos+ImVec2(1,0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], IM_COL32(0,0,0,48)); // Shadow
- g.OverlayDrawList.AddImage(tex_id, pos+ImVec2(2,0), pos+ImVec2(2,0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], IM_COL32(0,0,0,48)); // Shadow
- g.OverlayDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], IM_COL32(0,0,0,255)); // Black border
- g.OverlayDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[0], cursor_data.TexUvMax[0], IM_COL32(255,255,255,255)); // White fill
- g.OverlayDrawList.PopTextureID();
- }
- if (!g.OverlayDrawList.VtxBuffer.empty())
- AddDrawListToRenderList(g.RenderDrawLists[0], &g.OverlayDrawList);
-
- // Setup draw data
- g.RenderDrawData.Valid = true;
- g.RenderDrawData.CmdLists = (g.RenderDrawLists[0].Size > 0) ? &g.RenderDrawLists[0][0] : NULL;
- g.RenderDrawData.CmdListsCount = g.RenderDrawLists[0].Size;
- g.RenderDrawData.TotalVtxCount = g.IO.MetricsRenderVertices;
- g.RenderDrawData.TotalIdxCount = g.IO.MetricsRenderIndices;
-
- // Render. If user hasn't set a callback then they may retrieve the draw data via GetDrawData()
- if (g.RenderDrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL)
- g.IO.RenderDrawListsFn(&g.RenderDrawData);
- }
+ // Gather windows to render
+ g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = g.IO.MetricsActiveWindows = 0;
+ g.DrawDataBuilder.Clear();
+ ImGuiWindow* window_to_render_front_most = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget : NULL;
+ for (int n = 0; n != g.Windows.Size; n++)
+ {
+ ImGuiWindow* window = g.Windows[n];
+ if (window->Active && window->HiddenFrames == 0 && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != window_to_render_front_most)
+ AddWindowToDrawDataSelectLayer(window);
+ }
+ if (window_to_render_front_most && window_to_render_front_most->Active && window_to_render_front_most->HiddenFrames == 0) // NavWindowingTarget is always temporarily displayed as the front-most window
+ AddWindowToDrawDataSelectLayer(window_to_render_front_most);
+ g.DrawDataBuilder.FlattenIntoSingleLayer();
+
+ // Draw software mouse cursor if requested
+ ImVec2 offset, size, uv[4];
+ if (g.IO.MouseDrawCursor && g.IO.Fonts->GetMouseCursorTexData(g.MouseCursor, &offset, &size, &uv[0], &uv[2]))
+ {
+ const ImVec2 pos = g.IO.MousePos - offset;
+ const ImTextureID tex_id = g.IO.Fonts->TexID;
+ const float sc = g.Style.MouseCursorScale;
+ g.OverlayDrawList.PushTextureID(tex_id);
+ g.OverlayDrawList.AddImage(tex_id, pos + ImVec2(1,0)*sc, pos+ImVec2(1,0)*sc + size*sc, uv[2], uv[3], IM_COL32(0,0,0,48)); // Shadow
+ g.OverlayDrawList.AddImage(tex_id, pos + ImVec2(2,0)*sc, pos+ImVec2(2,0)*sc + size*sc, uv[2], uv[3], IM_COL32(0,0,0,48)); // Shadow
+ g.OverlayDrawList.AddImage(tex_id, pos, pos + size*sc, uv[2], uv[3], IM_COL32(0,0,0,255)); // Black border
+ g.OverlayDrawList.AddImage(tex_id, pos, pos + size*sc, uv[0], uv[1], IM_COL32(255,255,255,255)); // White fill
+ g.OverlayDrawList.PopTextureID();
+ }
+ if (!g.OverlayDrawList.VtxBuffer.empty())
+ AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.OverlayDrawList);
+
+ // Setup ImDrawData structure for end-user
+ SetupDrawData(&g.DrawDataBuilder.Layers[0], &g.DrawData);
+ g.IO.MetricsRenderVertices = g.DrawData.TotalVtxCount;
+ g.IO.MetricsRenderIndices = g.DrawData.TotalIdxCount;
+
+ // Render. If user hasn't set a callback then they may retrieve the draw data via GetDrawData()
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ if (g.DrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL)
+ g.IO.RenderDrawListsFn(&g.DrawData);
+#endif
}
const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
@@ -3252,7 +4328,7 @@ void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
}
// Render a triangle to denote expanded/collapsed state
-void ImGui::RenderTriangle(ImVec2 p_min, ImGuiDir dir, float scale)
+void ImGui::RenderArrow(ImVec2 p_min, ImGuiDir dir, float scale)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
@@ -3281,7 +4357,7 @@ void ImGui::RenderTriangle(ImVec2 p_min, ImGuiDir dir, float scale)
c = ImVec2(-0.500f,-0.866f) * r;
break;
case ImGuiDir_None:
- case ImGuiDir_Count_:
+ case ImGuiDir_COUNT:
IM_ASSERT(0);
break;
}
@@ -3314,6 +4390,38 @@ void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col, float sz)
window->DrawList->PathStroke(col, false, thickness);
}
+void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
+{
+ ImGuiContext& g = *GImGui;
+ if (id != g.NavId)
+ return;
+ if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
+ return;
+ ImGuiWindow* window = ImGui::GetCurrentWindow();
+ if (window->DC.NavHideHighlightOneFrame)
+ return;
+
+ float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
+ ImRect display_rect = bb;
+ display_rect.ClipWith(window->ClipRect);
+ if (flags & ImGuiNavHighlightFlags_TypeDefault)
+ {
+ const float THICKNESS = 2.0f;
+ const float DISTANCE = 3.0f + THICKNESS * 0.5f;
+ display_rect.Expand(ImVec2(DISTANCE,DISTANCE));
+ bool fully_visible = window->ClipRect.Contains(display_rect);
+ if (!fully_visible)
+ window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
+ window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), display_rect.Max - ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, ImDrawCornerFlags_All, THICKNESS);
+ if (!fully_visible)
+ window->DrawList->PopClipRect();
+ }
+ if (flags & ImGuiNavHighlightFlags_TypeThin)
+ {
+ window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, ~0, 1.0f);
+ }
+}
+
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
// CalcTextSize("") should return ImVec2(0.0f, GImGui->FontSize)
ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
@@ -3365,6 +4473,11 @@ void ImGui::CalcListClipping(int items_count, float items_height, int* out_items
const ImVec2 pos = window->DC.CursorPos;
int start = (int)((window->ClipRect.Min.y - pos.y) / items_height);
int end = (int)((window->ClipRect.Max.y - pos.y) / items_height);
+ if (g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Up) // When performing a navigation request, ensure we have one item extra in the direction we are moving to
+ start--;
+ if (g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Down)
+ end++;
+
start = ImClamp(start, 0, items_count);
end = ImClamp(end + 1, start, items_count);
*out_items_display_start = start;
@@ -3373,7 +4486,7 @@ void ImGui::CalcListClipping(int items_count, float items_height, int* out_items
// Find window given position, search front-to-back
// FIXME: Note that we have a lag here because WindowRectClipped is updated in Begin() so windows moved by user via SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is called, aka before the next Begin(). Moving window thankfully isn't affected.
-static ImGuiWindow* FindHoveredWindow(ImVec2 pos)
+static ImGuiWindow* FindHoveredWindow()
{
ImGuiContext& g = *GImGui;
for (int i = g.Windows.Size - 1; i >= 0; i--)
@@ -3386,7 +4499,7 @@ static ImGuiWindow* FindHoveredWindow(ImVec2 pos)
// Using the clipped AABB, a child window will typically be clipped by its parent (not always)
ImRect bb(window->WindowRectClipped.Min - g.Style.TouchExtraPadding, window->WindowRectClipped.Max + g.Style.TouchExtraPadding);
- if (bb.Contains(pos))
+ if (bb.Contains(g.IO.MousePos))
return window;
}
return NULL;
@@ -3410,18 +4523,6 @@ bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool c
return rect_for_touch.Contains(g.IO.MousePos);
}
-bool ImGui::IsAnyWindowHovered()
-{
- ImGuiContext& g = *GImGui;
- return g.HoveredWindow != NULL;
-}
-
-bool ImGui::IsAnyWindowFocused()
-{
- ImGuiContext& g = *GImGui;
- return g.NavWindow != NULL;
-}
-
static bool IsKeyPressedMap(ImGuiKey key, bool repeat)
{
const int key_index = GImGui->IO.KeyMap[key];
@@ -3434,7 +4535,7 @@ int ImGui::GetKeyIndex(ImGuiKey imgui_key)
return GImGui->IO.KeyMap[imgui_key];
}
-// Note that imgui doesn't know the semantic of each entry of io.KeyDown[]. Use your own indices/enums according to how your backend/engine stored them into KeyDown[]!
+// Note that imgui doesn't know the semantic of each entry of io.KeyDown[]. Use your own indices/enums according to how your back-end/engine stored them into KeyDown[]!
bool ImGui::IsKeyDown(int user_key_index)
{
if (user_key_index < 0) return false;
@@ -3479,9 +4580,7 @@ bool ImGui::IsKeyReleased(int user_key_index)
ImGuiContext& g = *GImGui;
if (user_key_index < 0) return false;
IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
- if (g.IO.KeysDownDurationPrev[user_key_index] >= 0.0f && !g.IO.KeysDown[user_key_index])
- return true;
- return false;
+ return g.IO.KeysDownDurationPrev[user_key_index] >= 0.0f && !g.IO.KeysDown[user_key_index];
}
bool ImGui::IsMouseDown(int button)
@@ -3491,6 +4590,15 @@ bool ImGui::IsMouseDown(int button)
return g.IO.MouseDown[button];
}
+bool ImGui::IsAnyMouseDown()
+{
+ ImGuiContext& g = *GImGui;
+ for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
+ if (g.IO.MouseDown[n])
+ return true;
+ return false;
+}
+
bool ImGui::IsMouseClicked(int button, bool repeat)
{
ImGuiContext& g = *GImGui;
@@ -3544,7 +4652,7 @@ ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
{
ImGuiContext& g = *GImGui;
if (g.CurrentPopupStack.Size > 0)
- return g.OpenPopupStack[g.CurrentPopupStack.Size-1].MousePosOnOpen;
+ return g.OpenPopupStack[g.CurrentPopupStack.Size-1].OpenMousePos;
return g.IO.MousePos;
}
@@ -3557,6 +4665,7 @@ bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
return mouse_pos->x >= MOUSE_INVALID && mouse_pos->y >= MOUSE_INVALID;
}
+// 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)
{
ImGuiContext& g = *GImGui;
@@ -3608,6 +4717,12 @@ bool ImGui::IsItemActive()
return false;
}
+bool ImGui::IsItemFocused()
+{
+ ImGuiContext& g = *GImGui;
+ return g.NavId && !g.NavDisableHighlight && g.NavId == g.CurrentWindow->DC.LastItemId;
+}
+
bool ImGui::IsItemClicked(int mouse_button)
{
return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_Default);
@@ -3621,7 +4736,14 @@ bool ImGui::IsAnyItemHovered()
bool ImGui::IsAnyItemActive()
{
- return GImGui->ActiveId != 0;
+ ImGuiContext& g = *GImGui;
+ return g.ActiveId != 0;
+}
+
+bool ImGui::IsAnyItemFocused()
+{
+ ImGuiContext& g = *GImGui;
+ return g.NavId != 0 && !g.NavDisableHighlight;
}
bool ImGui::IsItemVisible()
@@ -3658,15 +4780,7 @@ ImVec2 ImGui::GetItemRectSize()
return window->DC.LastItemRect.GetSize();
}
-ImVec2 ImGui::CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge, float outward)
-{
- ImGuiWindow* window = GetCurrentWindowRead();
- ImRect rect = window->DC.LastItemRect;
- rect.Expand(outward);
- return rect.GetClosestPoint(pos, on_edge);
-}
-
-static ImRect GetVisibleRect()
+static ImRect GetViewportRect()
{
ImGuiContext& g = *GImGui;
if (g.IO.DisplayVisibleMin.x != g.IO.DisplayVisibleMax.x && g.IO.DisplayVisibleMin.y != g.IO.DisplayVisibleMax.y)
@@ -3684,11 +4798,11 @@ void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, bool override_previous_
if (ImGuiWindow* window = FindWindowByName(window_name))
if (window->Active)
{
- // Hide previous tooltips. We can't easily "reset" the content of a window so we create a new one.
+ // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
window->HiddenFrames = 1;
ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
}
- ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize;
+ ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoInputs|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoNav;
Begin(window_name, NULL, flags | extra_flags);
}
@@ -3715,40 +4829,59 @@ void ImGui::BeginTooltip()
void ImGui::EndTooltip()
{
IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
- ImGui::End();
+ End();
}
// Mark popup as open (toggle toward open state).
// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
-void ImGui::OpenPopupEx(ImGuiID id, bool reopen_existing)
+void ImGui::OpenPopupEx(ImGuiID id)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* parent_window = g.CurrentWindow;
int current_stack_size = g.CurrentPopupStack.Size;
- ImGuiPopupRef popup_ref = ImGuiPopupRef(id, parent_window, parent_window->GetID("##Menus"), g.IO.MousePos); // Tagged as new ref because constructor sets Window to NULL.
+ 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 = (!g.NavDisableHighlight && g.NavDisableMouseHover) ? NavCalcPreferredMousePos() : g.IO.MousePos;
+
+ //printf("[%05d] OpenPopupEx(0x%08X)\n", g.FrameCount, id);
if (g.OpenPopupStack.Size < current_stack_size + 1)
+ {
g.OpenPopupStack.push_back(popup_ref);
- else if (reopen_existing || g.OpenPopupStack[current_stack_size].PopupId != id)
+ }
+ else
{
- g.OpenPopupStack.resize(current_stack_size+1);
- g.OpenPopupStack[current_stack_size] = popup_ref;
+ // Close child popups if any
+ g.OpenPopupStack.resize(current_stack_size + 1);
+
+ // Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui
+ // would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing
+ // situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand.
+ if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)
+ g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
+ else
+ g.OpenPopupStack[current_stack_size] = popup_ref;
- // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by CloseInactivePopups().
+ // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
// This is equivalent to what ClosePopupToLevel() does.
- if (g.OpenPopupStack[current_stack_size].PopupId == id)
- FocusWindow(parent_window);
+ //if (g.OpenPopupStack[current_stack_size].PopupId == id)
+ // FocusWindow(parent_window);
}
}
void ImGui::OpenPopup(const char* str_id)
{
ImGuiContext& g = *GImGui;
- OpenPopupEx(g.CurrentWindow->GetID(str_id), false);
+ OpenPopupEx(g.CurrentWindow->GetID(str_id));
}
-static void CloseInactivePopups(ImGuiWindow* ref_window)
+void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window)
{
ImGuiContext& g = *GImGui;
if (g.OpenPopupStack.empty())
@@ -3792,11 +4925,13 @@ static ImGuiWindow* GetFrontMostModalRootWindow()
static void ClosePopupToLevel(int remaining)
{
+ IM_ASSERT(remaining >= 0);
ImGuiContext& g = *GImGui;
- if (remaining > 0)
- ImGui::FocusWindow(g.OpenPopupStack[remaining-1].Window);
- else
- ImGui::FocusWindow(g.OpenPopupStack[0].ParentWindow);
+ ImGuiWindow* focus_window = (remaining > 0) ? g.OpenPopupStack[remaining-1].Window : g.OpenPopupStack[0].ParentWindow;
+ if (g.NavLayer == 0)
+ focus_window = NavRestoreLastChildNavWindow(focus_window);
+ ImGui::FocusWindow(focus_window);
+ focus_window->DC.NavHideHighlightOneFrame = true;
g.OpenPopupStack.resize(remaining);
}
@@ -3820,20 +4955,12 @@ void ImGui::CloseCurrentPopup()
ClosePopupToLevel(popup_idx);
}
-static inline void ClearSetNextWindowData()
-{
- // FIXME-OPT
- ImGuiContext& g = *GImGui;
- g.SetNextWindowPosCond = g.SetNextWindowSizeCond = g.SetNextWindowContentSizeCond = g.SetNextWindowCollapsedCond = 0;
- g.SetNextWindowSizeConstraint = g.SetNextWindowFocus = false;
-}
-
bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags)
{
ImGuiContext& g = *GImGui;
if (!IsPopupOpen(id))
{
- ClearSetNextWindowData(); // We behave like Begin() and need to consume those values
+ g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values
return false;
}
@@ -3850,15 +4977,15 @@ bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags)
return is_open;
}
-bool ImGui::BeginPopup(const char* str_id)
+bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
if (g.OpenPopupStack.Size <= g.CurrentPopupStack.Size) // Early out for performance
{
- ClearSetNextWindowData(); // We behave like Begin() and need to consume those values
+ g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values
return false;
}
- return BeginPopupEx(g.CurrentWindow->GetID(str_id), ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
+ return BeginPopupEx(g.CurrentWindow->GetID(str_id), flags|ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
bool ImGui::IsPopupOpen(ImGuiID id)
@@ -3873,23 +5000,23 @@ bool ImGui::IsPopupOpen(const char* str_id)
return g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].PopupId == g.CurrentWindow->GetID(str_id);
}
-bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags extra_flags)
+bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const ImGuiID id = window->GetID(name);
if (!IsPopupOpen(id))
{
- ClearSetNextWindowData(); // We behave like Begin() and need to consume those values
+ g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values
return false;
}
// Center modal windows by default
- if ((window->SetWindowPosAllowFlags & g.SetNextWindowPosCond) == 0)
+ // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
+ if (g.NextWindowData.PosCond == 0)
SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
- ImGuiWindowFlags flags = extra_flags|ImGuiWindowFlags_Popup|ImGuiWindowFlags_Modal|ImGuiWindowFlags_NoCollapse|ImGuiWindowFlags_NoSavedSettings;
- bool is_open = Begin(name, p_open, flags);
+ bool is_open = Begin(name, p_open, flags | ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings);
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();
@@ -3901,22 +5028,38 @@ bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags ext
return is_open;
}
+static void NavProcessMoveRequestWrapAround(ImGuiWindow* window)
+{
+ ImGuiContext& g = *GImGui;
+ if (g.NavWindow == window && NavMoveRequestButNoResultYet())
+ if ((g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) && g.NavMoveRequestForward == ImGuiNavForward_None && g.NavLayer == 0)
+ {
+ g.NavMoveRequestForward = ImGuiNavForward_ForwardQueued;
+ ImGui::NavMoveRequestCancel();
+ g.NavWindow->NavRectRel[0].Min.y = g.NavWindow->NavRectRel[0].Max.y = ((g.NavMoveDir == ImGuiDir_Up) ? ImMax(window->SizeFull.y, window->SizeContents.y) : 0.0f) - window->Scroll.y;
+ }
+}
+
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);
+
+ // Make all menus and popups wrap around for now, may need to expose that policy.
+ NavProcessMoveRequestWrapAround(g.CurrentWindow);
+
End();
}
bool ImGui::OpenPopupOnItemClick(const char* str_id, int mouse_button)
{
ImGuiWindow* window = GImGui->CurrentWindow;
- if (IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
+ if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
{
ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
IM_ASSERT(id != 0); // However, you cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
- OpenPopupEx(id, true);
+ OpenPopupEx(id);
return true;
}
return false;
@@ -3930,9 +5073,8 @@ bool ImGui::BeginPopupContextItem(const char* str_id, int mouse_button)
ImGuiWindow* window = GImGui->CurrentWindow;
ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
IM_ASSERT(id != 0); // However, you cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
- if (IsMouseClicked(mouse_button))
- if (IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
- OpenPopupEx(id, true);
+ if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
+ OpenPopupEx(id);
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
@@ -3941,10 +5083,9 @@ bool ImGui::BeginPopupContextWindow(const char* str_id, int mouse_button, bool a
if (!str_id)
str_id = "window_context";
ImGuiID id = GImGui->CurrentWindow->GetID(str_id);
- if (IsMouseClicked(mouse_button))
- if (IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
- if (also_over_items || !IsAnyItemHovered())
- OpenPopupEx(id, true);
+ if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
+ if (also_over_items || !IsAnyItemHovered())
+ OpenPopupEx(id);
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
@@ -3953,8 +5094,8 @@ bool ImGui::BeginPopupContextVoid(const char* str_id, int mouse_button)
if (!str_id)
str_id = "void_context";
ImGuiID id = GImGui->CurrentWindow->GetID(str_id);
- if (!IsAnyWindowHovered() && IsMouseClicked(mouse_button))
- OpenPopupEx(id, true);
+ if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
+ OpenPopupEx(id);
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
@@ -3980,16 +5121,26 @@ static bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, b
char title[256];
if (name)
- ImFormatString(title, IM_ARRAYSIZE(title), "%s/%s_%08X", parent_window->Name, name, id);
+ ImFormatString(title, IM_ARRAYSIZE(title), "%s/%s", parent_window->Name, name);
else
ImFormatString(title, IM_ARRAYSIZE(title), "%s/%08X", parent_window->Name, id);
ImGui::SetNextWindowSize(size);
bool ret = ImGui::Begin(title, NULL, flags);
ImGuiWindow* child_window = ImGui::GetCurrentWindow();
+ child_window->ChildId = id;
child_window->AutoFitChildAxises = auto_fit_axises;
g.Style.ChildBorderSize = backup_border_size;
+ // Process navigation-in immediately so NavInit can run on first frame
+ if (!(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayerActiveMask != 0 || child_window->DC.NavHasScroll) && g.NavActivateId == id)
+ {
+ ImGui::FocusWindow(child_window);
+ ImGui::NavInitWindow(child_window, false);
+ ImGui::SetActiveID(id+1, child_window); // Steal ActiveId with a dummy id so that key-press won't activate child item
+ g.ActiveIdSource = ImGuiInputSource_Nav;
+ }
+
return ret;
}
@@ -4001,17 +5152,19 @@ bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border,
bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
{
+ IM_ASSERT(id != 0);
return BeginChildEx(NULL, id, size_arg, border, extra_flags);
}
void ImGui::EndChild()
{
- ImGuiWindow* window = GetCurrentWindow();
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() callss
if (window->BeginCount > 1)
{
- ImGui::End();
+ End();
}
else
{
@@ -4021,12 +5174,25 @@ void ImGui::EndChild()
sz.x = ImMax(4.0f, sz.x);
if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y))
sz.y = ImMax(4.0f, sz.y);
- ImGui::End();
+ End();
- ImGuiWindow* parent_window = GetCurrentWindow();
+ ImGuiWindow* parent_window = g.CurrentWindow;
ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz);
ItemSize(sz);
- ItemAdd(bb, 0);
+ if ((window->DC.NavLayerActiveMask != 0 || window->DC.NavHasScroll) && !(window->Flags & ImGuiWindowFlags_NavFlattened))
+ {
+ ItemAdd(bb, window->ChildId);
+ RenderNavHighlight(bb, window->ChildId);
+
+ // When browsing a window that has no activable items (scroll only) we keep a highlight on the child
+ if (window->DC.NavLayerActiveMask == 0 && window == g.NavWindow)
+ RenderNavHighlight(ImRect(bb.Min - ImVec2(2,2), bb.Max + ImVec2(2,2)), g.NavId, ImGuiNavHighlightFlags_TypeThin);
+ }
+ else
+ {
+ // Not navigable into
+ ItemAdd(bb, 0);
+ }
}
}
@@ -4077,7 +5243,7 @@ static ImVec2 FindBestWindowPosForPopup(const ImVec2& ref_pos, const ImVec2& siz
// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
ImVec2 safe_padding = style.DisplaySafeAreaPadding;
- ImRect r_outer(GetVisibleRect());
+ ImRect r_outer(GetViewportRect());
r_outer.Expand(ImVec2((size.x - r_outer.GetWidth() > safe_padding.x*2) ? -safe_padding.x : 0.0f, (size.y - r_outer.GetHeight() > safe_padding.y*2) ? -safe_padding.y : 0.0f));
ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
//GImGui->OverlayDrawList.AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
@@ -4086,8 +5252,8 @@ static ImVec2 FindBestWindowPosForPopup(const ImVec2& ref_pos, const ImVec2& siz
// Combo Box policy (we want a connecting edge)
if (policy == ImGuiPopupPositionPolicy_ComboBox)
{
- const ImGuiDir dir_prefered_order[ImGuiDir_Count_] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
- for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_Count_; n++)
+ const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
+ for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
{
const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
if (n != -1 && dir == *last_dir) // Already tried this direction?
@@ -4105,8 +5271,8 @@ static ImVec2 FindBestWindowPosForPopup(const ImVec2& ref_pos, const ImVec2& siz
}
// Default popup policy
- const ImGuiDir dir_prefered_order[ImGuiDir_Count_] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
- for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_Count_; n++)
+ const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
+ for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
{
const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
if (n != -1 && dir == *last_dir) // Already tried this direction?
@@ -4158,14 +5324,13 @@ static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFl
{
// Retrieve settings from .ini file
// Use SetWindowPos() or SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
- window->PosFloat = ImVec2(60, 60);
- window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
+ window->Pos = window->PosFloat = ImVec2(60, 60);
if (ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID))
{
SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
window->PosFloat = settings->Pos;
- window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
+ window->Pos = ImFloor(window->PosFloat);
window->Collapsed = settings->Collapsed;
if (ImLengthSqr(settings->Size) > 0.00001f)
size = settings->Size;
@@ -4197,20 +5362,20 @@ static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFl
static ImVec2 CalcSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size)
{
ImGuiContext& g = *GImGui;
- if (g.SetNextWindowSizeConstraint)
+ if (g.NextWindowData.SizeConstraintCond != 0)
{
// Using -1,-1 on either X/Y axis to preserve the current size.
- ImRect cr = g.SetNextWindowSizeConstraintRect;
+ ImRect cr = g.NextWindowData.SizeConstraintRect;
new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
- if (g.SetNextWindowSizeConstraintCallback)
+ if (g.NextWindowData.SizeCallback)
{
- ImGuiSizeConstraintCallbackData data;
- data.UserData = g.SetNextWindowSizeConstraintCallbackUserData;
+ ImGuiSizeCallbackData data;
+ data.UserData = g.NextWindowData.SizeCallbackUserData;
data.Pos = window->Pos;
data.CurrentSize = window->SizeFull;
data.DesiredSize = new_size;
- g.SetNextWindowSizeConstraintCallback(&data);
+ g.NextWindowData.SizeCallback(&data);
new_size = data.DesiredSize;
}
}
@@ -4334,6 +5499,112 @@ static ImRect GetBorderRect(ImGuiWindow* window, int border_n, float perp_paddin
return ImRect();
}
+// Handle resize for: Resize Grips, Borders, Gamepad
+static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4])
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindowFlags flags = window->Flags;
+ if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
+ return;
+
+ const int resize_border_count = (flags & ImGuiWindowFlags_ResizeFromAnySide) ? 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);
+
+ ImVec2 pos_target(FLT_MAX, FLT_MAX);
+ ImVec2 size_target(FLT_MAX, FLT_MAX);
+
+ // Manual resize grips
+ PushID("#RESIZE");
+ for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
+ {
+ const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
+ const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPos);
+
+ // 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);
+ resize_rect.FixInverted();
+ bool hovered, held;
+ ButtonBehavior(resize_rect, window->GetID((void*)(intptr_t)resize_grip_n), &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
+ if (hovered || held)
+ g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
+
+ if (g.HoveredWindow == window && held && g.IO.MouseDoubleClicked[0] && resize_grip_n == 0)
+ {
+ // Manual auto-fit when double-clicking
+ size_target = CalcSizeAfterConstraint(window, size_auto_fit);
+ ClearActiveID();
+ }
+ else if (held)
+ {
+ // Resize from any of the four corners
+ // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
+ ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + resize_rect.GetSize() * 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)
+ resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
+ }
+ 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 = GetBorderRect(window, border_n, grip_hover_size, BORDER_SIZE);
+ ButtonBehavior(border_rect, window->GetID((void*)(intptr_t)(border_n + 4)), &hovered, &held, ImGuiButtonFlags_FlattenChildren);
+ if ((hovered && g.HoveredIdTimer > BORDER_APPEAR_TIMER) || held)
+ {
+ g.MouseCursor = (border_n & 1) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
+ if (held) *border_held = border_n;
+ }
+ if (held)
+ {
+ ImVec2 border_target = window->Pos;
+ ImVec2 border_posn;
+ if (border_n == 0) { border_posn = ImVec2(0, 0); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y); }
+ 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); }
+ CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target);
+ }
+ }
+ PopID();
+
+ // Navigation resize (keyboard/gamepad)
+ if (g.NavWindowingTarget == window)
+ {
+ ImVec2 nav_resize_delta;
+ if (g.NavInputSource == ImGuiInputSource_NavKeyboard && g.IO.KeyShift)
+ nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down);
+ if (g.NavInputSource == ImGuiInputSource_NavGamepad)
+ nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_Down);
+ if (nav_resize_delta.x != 0.0f || nav_resize_delta.y != 0.0f)
+ {
+ const float NAV_RESIZE_SPEED = 600.0f;
+ nav_resize_delta *= ImFloor(NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y));
+ g.NavWindowingToggleLayer = false;
+ g.NavDisableMouseHover = true;
+ resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
+ // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
+ size_target = CalcSizeAfterConstraint(window, window->SizeFull + nav_resize_delta);
+ }
+ }
+
+ // Apply back modified position/size to window
+ if (size_target.x != FLT_MAX)
+ {
+ window->SizeFull = size_target;
+ MarkIniSettingsDirty(window);
+ }
+ if (pos_target.x != FLT_MAX)
+ {
+ window->Pos = window->PosFloat = ImFloor(pos_target);
+ MarkIniSettingsDirty(window);
+ }
+
+ window->Size = window->SizeFull;
+}
+
// Push a new ImGui window to add widgets to.
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
// - Begin/End can be called multiple times during the frame with the same window name to append content.
@@ -4349,17 +5620,22 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
IM_ASSERT(g.Initialized); // 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
- if (flags & ImGuiWindowFlags_NoInputs)
- flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
-
// Find or create
ImGuiWindow* window = FindWindowByName(name);
- if (!window)
+ const bool window_just_created = (window == NULL);
+ if (window_just_created)
{
- ImVec2 size_on_first_use = (g.SetNextWindowSizeCond != 0) ? g.SetNextWindowSizeVal : ImVec2(0.0f, 0.0f); // Any condition flag will do since we are creating a new window here.
+ ImVec2 size_on_first_use = (g.NextWindowData.SizeCond != 0) ? g.NextWindowData.SizeVal : ImVec2(0.0f, 0.0f); // Any condition flag will do since we are creating a new window here.
window = CreateNewWindow(name, size_on_first_use, flags);
}
+ // Automatically disable manual moving/resizing when NoInputs is set
+ if (flags & ImGuiWindowFlags_NoInputs)
+ flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
+
+ if (flags & ImGuiWindowFlags_NavFlattened)
+ IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
+
const int current_frame = g.FrameCount;
const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
if (first_begin_of_the_frame)
@@ -4369,7 +5645,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
// Update the Appearing flag
bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
- const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFrames == 1);
+ const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFrames > 0);
if (flags & ImGuiWindowFlags_Popup)
{
ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.CurrentPopupStack.Size];
@@ -4398,53 +5674,57 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
window->PopupId = popup_ref.PopupId;
}
+ if (window_just_appearing_after_hidden_for_resize && !(flags & ImGuiWindowFlags_ChildWindow))
+ window->NavLastIds[0] = 0;
+
// Process SetNextWindow***() calls
bool window_pos_set_by_api = false;
bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
- if (g.SetNextWindowPosCond)
+ if (g.NextWindowData.PosCond)
{
- window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.SetNextWindowPosCond) != 0;
- if (window_pos_set_by_api && ImLengthSqr(g.SetNextWindowPosPivot) > 0.00001f)
+ window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
+ if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
{
// May be processed on the next frame if this is our first frame and we are measuring size
// FIXME: Look into removing the branch so everything can go through this same code path for consistency.
- window->SetWindowPosVal = g.SetNextWindowPosVal;
- window->SetWindowPosPivot = g.SetNextWindowPosPivot;
+ window->SetWindowPosVal = g.NextWindowData.PosVal;
+ window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
}
else
{
- SetWindowPos(window, g.SetNextWindowPosVal, g.SetNextWindowPosCond);
+ SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
}
- g.SetNextWindowPosCond = 0;
+ g.NextWindowData.PosCond = 0;
}
- if (g.SetNextWindowSizeCond)
+ if (g.NextWindowData.SizeCond)
{
- window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.SetNextWindowSizeCond) != 0 && (g.SetNextWindowSizeVal.x > 0.0f);
- window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.SetNextWindowSizeCond) != 0 && (g.SetNextWindowSizeVal.y > 0.0f);
- SetWindowSize(window, g.SetNextWindowSizeVal, g.SetNextWindowSizeCond);
- g.SetNextWindowSizeCond = 0;
+ window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
+ window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
+ SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
+ g.NextWindowData.SizeCond = 0;
}
- if (g.SetNextWindowContentSizeCond)
+ if (g.NextWindowData.ContentSizeCond)
{
// Adjust passed "client size" to become a "window size"
- window->SizeContentsExplicit = g.SetNextWindowContentSizeVal;
- window->SizeContentsExplicit.y += window->TitleBarHeight() + window->MenuBarHeight();
- g.SetNextWindowContentSizeCond = 0;
+ window->SizeContentsExplicit = g.NextWindowData.ContentSizeVal;
+ if (window->SizeContentsExplicit.y != 0.0f)
+ window->SizeContentsExplicit.y += window->TitleBarHeight() + window->MenuBarHeight();
+ g.NextWindowData.ContentSizeCond = 0;
}
else if (first_begin_of_the_frame)
{
window->SizeContentsExplicit = ImVec2(0.0f, 0.0f);
}
- if (g.SetNextWindowCollapsedCond)
+ if (g.NextWindowData.CollapsedCond)
{
- SetWindowCollapsed(window, g.SetNextWindowCollapsedVal, g.SetNextWindowCollapsedCond);
- g.SetNextWindowCollapsedCond = 0;
+ SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
+ g.NextWindowData.CollapsedCond = 0;
}
- if (g.SetNextWindowFocus)
+ if (g.NextWindowData.FocusCond)
{
SetWindowFocus();
- g.SetNextWindowFocus = false;
+ g.NextWindowData.FocusCond = 0;
}
if (window->Appearing)
SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
@@ -4452,16 +5732,17 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
// When reusing window again multiple times a frame, just append content (don't need to setup again)
if (first_begin_of_the_frame)
{
+ const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
+
// Initialize
window->ParentWindow = parent_window;
- window->RootWindow = window->RootNonPopupWindow = window;
- if (parent_window && (flags & ImGuiWindowFlags_ChildWindow))
+ window->RootWindow = window->RootWindowForTitleBarHighlight = window->RootWindowForTabbing = window->RootWindowForNav = window;
+ if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !window_is_child_tooltip)
window->RootWindow = parent_window->RootWindow;
if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)))
- window->RootNonPopupWindow = parent_window->RootNonPopupWindow;
- //window->RootNavWindow = window;
- //while (window->RootNavWindow->Flags & ImGuiWindowFlags_NavFlattened)
- // window->RootNavWindow = window->RootNavWindow->ParentWindow;
+ window->RootWindowForTitleBarHighlight = window->RootWindowForTabbing = parent_window->RootWindowForTitleBarHighlight; // Same value in master branch, will differ for docking
+ while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
+ window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
window->Active = true;
window->BeginOrderWithinParent = 0;
@@ -4471,30 +5752,19 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
window->LastFrameActive = current_frame;
window->IDStack.resize(1);
- // Setup draw list and outer clipping rectangle
- window->DrawList->Clear();
- window->DrawList->Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0);
- window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
- ImRect fullscreen_rect(GetVisibleRect());
- if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup))
- PushClipRect(parent_window->ClipRect.Min, parent_window->ClipRect.Max, true);
- else
- PushClipRect(fullscreen_rect.Min, fullscreen_rect.Max, true);
-
- if (window_just_activated_by_user)
- {
- // Popup first latch mouse position, will position itself when it appears next frame
- window->AutoPosLastDirection = ImGuiDir_None;
- if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api)
- window->PosFloat = g.IO.MousePos;
- }
+ // Lock window rounding, border size and rounding so that altering the border sizes for children doesn't have side-effects.
+ window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
+ window->WindowBorderSize = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildBorderSize : ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
+ window->WindowPadding = style.WindowPadding;
+ if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)
+ window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
// Collapse window by double-clicking on title bar
// At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse))
{
ImRect title_bar_rect = window->TitleBarRect();
- if (g.HoveredWindow == window && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0])
+ if (window->CollapseToggleWanted || (g.HoveredWindow == window && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0]))
{
window->Collapsed = !window->Collapsed;
MarkIniSettingsDirty(window);
@@ -4505,6 +5775,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
{
window->Collapsed = false;
}
+ window->CollapseToggleWanted = false;
// SIZE
@@ -4514,7 +5785,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
// Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
if (window->HiddenFrames > 0)
window->HiddenFrames--;
- if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0 && window_just_activated_by_user)
+ if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
{
window->HiddenFrames = 1;
if (flags & ImGuiWindowFlags_AlwaysAutoResize)
@@ -4527,19 +5798,14 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
}
}
- // Lock window rounding, border size and rounding so that altering the border sizes for children doesn't have side-effects.
- window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
- window->WindowBorderSize = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildBorderSize : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
- window->WindowPadding = style.WindowPadding;
- if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)
- window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
- const float window_rounding = window->WindowRounding;
- const float window_border_size = window->WindowBorderSize;
+ // Hide new windows for one frame until they calculate their size
+ if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
+ window->HiddenFrames = 1;
// Calculate auto-fit size, handle automatic resize
const ImVec2 size_auto_fit = CalcSizeAutoFit(window, window->SizeContents);
ImVec2 size_full_modified(FLT_MAX, FLT_MAX);
- if (flags & ImGuiWindowFlags_AlwaysAutoResize && !window->Collapsed)
+ if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
{
// Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
if (!window_size_x_set_by_api)
@@ -4549,7 +5815,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
}
else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
{
- // Auto-fit only grows during the first few frames
+ // Auto-fit may only grow window during the first few frames
// We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
window->SizeFull.x = size_full_modified.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
@@ -4561,12 +5827,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
// Apply minimum/maximum window size constraints and final size
window->SizeFull = CalcSizeAfterConstraint(window, window->SizeFull);
- window->Size = window->Collapsed ? window->TitleBarRect().GetSize() : window->SizeFull;
- if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup))
- {
- IM_ASSERT(window_size_x_set_by_api && window_size_y_set_by_api); // Submitted by BeginChild()
- window->Size = window->SizeFull;
- }
+ window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
// SCROLLBAR STATUS
@@ -4577,22 +5838,30 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
float size_x_for_scrollbars = size_full_modified.x != FLT_MAX ? window->SizeFull.x : window->SizeFullAtLastBegin.x;
float size_y_for_scrollbars = size_full_modified.y != FLT_MAX ? window->SizeFull.y : window->SizeFullAtLastBegin.y;
window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((window->SizeContents.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
- window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((window->SizeContents.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f) - window->WindowPadding.x) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
+ window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((window->SizeContents.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
if (window->ScrollbarX && !window->ScrollbarY)
- window->ScrollbarY = (window->SizeContents.y > size_y_for_scrollbars + style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar);
+ window->ScrollbarY = (window->SizeContents.y > size_y_for_scrollbars - style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar);
window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
}
// POSITION
+ // Popup latch its initial position, will position itself when it appears next frame
+ if (window_just_activated_by_user)
+ {
+ window->AutoPosLastDirection = ImGuiDir_None;
+ if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api)
+ window->Pos = window->PosFloat = g.CurrentPopupStack.back().OpenPopupPos;
+ }
+
// Position child window
if (flags & ImGuiWindowFlags_ChildWindow)
{
window->BeginOrderWithinParent = 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 = window->PosFloat = parent_window->DC.CursorPos;
}
- if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api)
- window->Pos = window->PosFloat = parent_window->DC.CursorPos;
const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFrames == 0);
if (window_pos_with_pivot)
@@ -4621,10 +5890,15 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
}
// Position tooltip (always follows mouse)
- if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api)
+ if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
{
- ImVec2 ref_pos = g.IO.MousePos;
- ImRect rect_to_avoid(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24, ref_pos.y + 24); // FIXME: Completely hard-coded. Store boxes in mouse cursor data? Scale? Center on cursor hit-point?
+ float sc = g.Style.MouseCursorScale;
+ ImVec2 ref_pos = (!g.NavDisableHighlight && g.NavDisableMouseHover) ? NavCalcPreferredMousePos() : g.IO.MousePos;
+ ImRect rect_to_avoid;
+ if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
+ rect_to_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
+ else
+ rect_to_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * sc, ref_pos.y + 24 * sc); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
window->PosFloat = FindBestWindowPosForPopup(ref_pos, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
if (window->AutoPosLastDirection == ImGuiDir_None)
window->PosFloat = ref_pos + ImVec2(2,2); // If there's not enough room, for tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
@@ -4640,7 +5914,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
window->PosFloat = ImMin(window->PosFloat, g.IO.DisplaySize - padding);
}
}
- window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
+ window->Pos = ImFloor(window->PosFloat);
// Default item width. Make it proportional to window size if window manually resizes
if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
@@ -4664,115 +5938,68 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
if (!(flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) || (flags & ImGuiWindowFlags_Popup))
want_focus = true;
+ // Handle manual resize: Resize Grips, Borders, Gamepad
+ int border_held = -1;
+ ImU32 resize_grip_col[4] = { 0 };
+ const int resize_grip_count = (flags & ImGuiWindowFlags_ResizeFromAnySide) ? 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]);
+
+ // DRAWING
+
+ // Setup draw list and outer clipping rectangle
+ window->DrawList->Clear();
+ window->DrawList->Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0);
+ window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
+ ImRect viewport_rect(GetViewportRect());
+ if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
+ PushClipRect(parent_window->ClipRect.Min, parent_window->ClipRect.Max, true);
+ else
+ PushClipRect(viewport_rect.Min, viewport_rect.Max, true);
+
// Draw modal window background (darkens what is behind them)
if ((flags & ImGuiWindowFlags_Modal) != 0 && window == GetFrontMostModalRootWindow())
- window->DrawList->AddRectFilled(fullscreen_rect.Min, fullscreen_rect.Max, GetColorU32(ImGuiCol_ModalWindowDarkening, g.ModalWindowDarkeningRatio));
+ window->DrawList->AddRectFilled(viewport_rect.Min, viewport_rect.Max, GetColorU32(ImGuiCol_ModalWindowDarkening, g.ModalWindowDarkeningRatio));
+
+ // Draw navigation selection/windowing rectangle background
+ if (g.NavWindowingTarget == window)
+ {
+ ImRect bb = window->Rect();
+ bb.Expand(g.FontSize);
+ if (!bb.Contains(viewport_rect)) // Avoid drawing if the window covers all the viewport anyway
+ window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha * 0.25f), g.Style.WindowRounding);
+ }
// Draw window + handle manual resize
- ImRect title_bar_rect = window->TitleBarRect();
+ const float window_rounding = window->WindowRounding;
+ const float window_border_size = window->WindowBorderSize;
+ const bool title_bar_is_highlight = want_focus || (g.NavWindow && window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
+ const ImRect title_bar_rect = window->TitleBarRect();
if (window->Collapsed)
{
// Title bar only
float backup_border_size = style.FrameBorderSize;
g.Style.FrameBorderSize = window->WindowBorderSize;
- RenderFrame(title_bar_rect.Min, title_bar_rect.Max, GetColorU32(ImGuiCol_TitleBgCollapsed), true, window_rounding);
+ ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
+ RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
g.Style.FrameBorderSize = backup_border_size;
}
else
{
- // Handle resize for: Resize Grips, Borders, Gamepad
- int border_held = -1;
- ImU32 resize_grip_col[4] = { 0 };
- const int resize_grip_count = (flags & ImGuiWindowFlags_ResizeFromAnySide) ? 2 : 1; // 4
- const int resize_border_count = (flags & ImGuiWindowFlags_ResizeFromAnySide) ? 4 : 0;
-
- const float grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window_rounding + 1.0f + g.FontSize * 0.2f);
- const float grip_hover_size = (float)(int)(grip_draw_size * 0.75f);
- if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && !(flags & ImGuiWindowFlags_NoResize))
+ // Window background
+ ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags));
+ if (g.NextWindowData.BgAlphaCond != 0)
{
- ImVec2 pos_target(FLT_MAX, FLT_MAX);
- ImVec2 size_target(FLT_MAX, FLT_MAX);
-
- // Manual resize grips
- PushID("#RESIZE");
- for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
- {
- const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
- const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPos);
-
- // 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);
- resize_rect.FixInverted();
- bool hovered, held;
- ButtonBehavior(resize_rect, window->GetID((void*)(intptr_t)resize_grip_n), &hovered, &held, ImGuiButtonFlags_FlattenChildren);
- if (hovered || held)
- g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
-
- if (g.HoveredWindow == window && held && g.IO.MouseDoubleClicked[0] && resize_grip_n == 0)
- {
- // Manual auto-fit when double-clicking
- size_target = CalcSizeAfterConstraint(window, size_auto_fit);
- ClearActiveID();
- }
- else if (held)
- {
- // Resize from any of the four corners
- // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
- ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + resize_rect.GetSize() * 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)
- resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
- }
- 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 = GetBorderRect(window, border_n, grip_hover_size, BORDER_SIZE);
- ButtonBehavior(border_rect, window->GetID((void*)(intptr_t)(border_n+4)), &hovered, &held, ImGuiButtonFlags_FlattenChildren);
- if ((hovered && g.HoveredIdTimer > BORDER_APPEAR_TIMER) || held)
- {
- g.MouseCursor = (border_n & 1) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
- if (held) border_held = border_n;
- }
- if (held)
- {
- ImVec2 border_target = window->Pos;
- ImVec2 border_posn;
- if (border_n == 0) { border_posn = ImVec2(0, 0); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y); }
- 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); }
- CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target);
- }
- }
- PopID();
-
- // Apply back modified position/size to window
- if (size_target.x != FLT_MAX)
- {
- window->SizeFull = size_target;
- MarkIniSettingsDirty(window);
- }
- if (pos_target.x != FLT_MAX)
- {
- window->Pos = window->PosFloat = ImVec2((float)(int)pos_target.x, (float)(int)pos_target.y);
- MarkIniSettingsDirty(window);
- }
-
- window->Size = window->SizeFull;
- title_bar_rect = window->TitleBarRect();
+ bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(g.NextWindowData.BgAlphaVal) << IM_COL32_A_SHIFT);
+ g.NextWindowData.BgAlphaCond = 0;
}
-
- // Window background, Default Alpha
- ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags));
window->DrawList->AddRectFilled(window->Pos+ImVec2(0,window->TitleBarHeight()), window->Pos+window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Bot);
// Title bar
- const bool window_is_focused = want_focus || (g.NavWindow && window->RootNonPopupWindow == g.NavWindow->RootNonPopupWindow);
+ ImU32 title_bar_col = GetColorU32(window->Collapsed ? ImGuiCol_TitleBgCollapsed : title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
if (!(flags & ImGuiWindowFlags_NoTitleBar))
- window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg), window_rounding, ImDrawCornerFlags_Top);
+ window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawCornerFlags_Top);
// Menu bar
if (flags & ImGuiWindowFlags_MenuBar)
@@ -4816,6 +6043,20 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
window->DrawList->AddLine(title_bar_rect.GetBL() + ImVec2(style.WindowBorderSize, -1), title_bar_rect.GetBR() + ImVec2(-style.WindowBorderSize,-1), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
}
+ // Draw navigation selection/windowing rectangle border
+ if (g.NavWindowingTarget == window)
+ {
+ float rounding = ImMax(window->WindowRounding, g.Style.WindowRounding);
+ ImRect bb = window->Rect();
+ bb.Expand(g.FontSize);
+ if (bb.Contains(viewport_rect)) // If a window fits the entire viewport, adjust its highlight inward
+ {
+ bb.Expand(-g.FontSize - 1.0f);
+ rounding = window->WindowRounding;
+ }
+ window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), rounding, ~0, 3.0f);
+ }
+
// Store a backup of SizeFull which we will use next frame to decide if we need scrollbars.
window->SizeFullAtLastBegin = window->SizeFull;
@@ -4836,11 +6077,16 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
window->DC.CursorMaxPos = window->DC.CursorStartPos;
window->DC.CurrentLineHeight = window->DC.PrevLineHeight = 0.0f;
window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
+ window->DC.NavHideHighlightOneFrame = false;
+ window->DC.NavHasScroll = (GetScrollMaxY() > 0.0f);
+ window->DC.NavLayerActiveMask = window->DC.NavLayerActiveMaskNext;
+ window->DC.NavLayerActiveMaskNext = 0x00;
window->DC.MenuBarAppending = false;
window->DC.MenuBarOffsetX = ImMax(window->WindowPadding.x, style.ItemSpacing.x);
window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f;
window->DC.ChildWindows.resize(0);
window->DC.LayoutType = ImGuiLayoutType_Vertical;
+ window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
window->DC.ItemFlags = ImGuiItemFlags_Default_;
window->DC.ItemWidth = window->ItemWidthDefault;
window->DC.TextWrapPos = -1.0f; // disabled
@@ -4849,6 +6095,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
window->DC.TextWrapPosStack.resize(0);
window->DC.ColumnsSet = NULL;
window->DC.TreeDepth = 0;
+ window->DC.TreeDepthMayJumpToParentOnPop = 0x00;
window->DC.StateStorage = &window->StateStorage;
window->DC.GroupStack.resize(0);
window->MenuColumns.Update(3, style.ItemSpacing.x, window_just_activated_by_user);
@@ -4866,39 +6113,56 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
// Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
if (want_focus)
+ {
FocusWindow(window);
+ NavInitWindow(window, false);
+ }
// Title bar
if (!(flags & ImGuiWindowFlags_NoTitleBar))
{
+ // Close & collapse button are on layer 1 (same as menus) and don't default focus
+ const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags;
+ window->DC.ItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
+ window->DC.NavLayerCurrent++;
+ window->DC.NavLayerCurrentMask <<= 1;
+
// Collapse button
if (!(flags & ImGuiWindowFlags_NoCollapse))
{
- RenderTriangle(window->Pos + style.FramePadding, window->Collapsed ? ImGuiDir_Right : ImGuiDir_Down, 1.0f);
+ ImGuiID id = window->GetID("#COLLAPSE");
+ ImRect bb(window->Pos + style.FramePadding + ImVec2(1,1), window->Pos + style.FramePadding + ImVec2(g.FontSize,g.FontSize) - ImVec2(1,1));
+ ItemAdd(bb, id); // To allow navigation
+ if (ButtonBehavior(bb, id, NULL, NULL))
+ window->CollapseToggleWanted = true; // Defer collapsing to next frame as we are too far in the Begin() function
+ RenderNavHighlight(bb, id);
+ RenderArrow(window->Pos + style.FramePadding, window->Collapsed ? ImGuiDir_Right : ImGuiDir_Down, 1.0f);
}
// Close button
if (p_open != NULL)
{
- const float PAD = 2.0f;
- const float rad = (window->TitleBarHeight() - PAD*2.0f) * 0.5f;
- if (CloseButton(window->GetID("#CLOSE"), window->Rect().GetTR() + ImVec2(-PAD - rad, PAD + rad), rad))
+ const float pad = style.FramePadding.y;
+ const float rad = g.FontSize * 0.5f;
+ if (CloseButton(window->GetID("#CLOSE"), window->Rect().GetTR() + ImVec2(-pad - rad, pad + rad), rad + 1))
*p_open = false;
}
+ window->DC.NavLayerCurrent--;
+ window->DC.NavLayerCurrentMask >>= 1;
+ window->DC.ItemFlags = item_flags_backup;
+
// Title text (FIXME: refactor text alignment facilities along with RenderText helpers)
- const ImVec2 text_size = CalcTextSize(name, NULL, true);
- ImVec2 text_min = window->Pos;
- ImVec2 text_max = window->Pos + ImVec2(window->Size.x, style.FramePadding.y*2 + text_size.y);
- ImRect clip_rect;
- clip_rect.Max = ImVec2(window->Pos.x + window->Size.x - (p_open ? title_bar_rect.GetHeight() - 3 : style.FramePadding.x), text_max.y); // Match the size of CloseWindowButton()
+ ImVec2 text_size = CalcTextSize(name, NULL, true);
+ ImRect text_r = title_bar_rect;
float pad_left = (flags & ImGuiWindowFlags_NoCollapse) == 0 ? (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x) : style.FramePadding.x;
float pad_right = (p_open != NULL) ? (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x) : style.FramePadding.x;
if (style.WindowTitleAlign.x > 0.0f) pad_right = ImLerp(pad_right, pad_left, style.WindowTitleAlign.x);
- text_min.x += pad_left;
- text_max.x -= pad_right;
- clip_rect.Min = ImVec2(text_min.x, window->Pos.y);
- RenderTextClipped(text_min, text_max, name, NULL, &text_size, style.WindowTitleAlign, &clip_rect);
+ text_r.Min.x += pad_left;
+ text_r.Max.x -= pad_right;
+ ImRect clip_rect = text_r;
+ clip_rect.Max.x = window->Pos.x + window->Size.x - (p_open ? title_bar_rect.GetHeight() - 3 : style.FramePadding.x); // Match the size of CloseButton()
+ RenderTextClipped(text_r.Min, text_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_rect);
}
// Save clipped aabb so we can access it in constant-time in FindHoveredWindow()
@@ -4923,28 +6187,27 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->ScrollbarSizes.y - window->WindowBorderSize;
//window->DrawList->AddRect(window->InnerRect.Min, window->InnerRect.Max, IM_COL32_WHITE);
+ // Inner clipping rectangle
+ // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
+ window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(0.0f, ImFloor(window->WindowPadding.x*0.5f - window->WindowBorderSize)));
+ window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y);
+ window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(0.0f, ImFloor(window->WindowPadding.x*0.5f - window->WindowBorderSize)));
+ window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y);
+
// After Begin() we fill the last item / hovered data using the title bar data. Make that a standard behavior (to allow usage of context menus on title bar only, etc.).
window->DC.LastItemId = window->MoveId;
+ window->DC.LastItemStatusFlags = IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0;
window->DC.LastItemRect = title_bar_rect;
- window->DC.LastItemRectHoveredRect = IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false);
}
- // Inner clipping rectangle
- // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
- const float border_size = window->WindowBorderSize;
- ImRect clip_rect;
- clip_rect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(0.0f, ImFloor(window->WindowPadding.x*0.5f - border_size)));
- clip_rect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y);
- clip_rect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(0.0f, ImFloor(window->WindowPadding.x*0.5f - border_size)));
- clip_rect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y);
- PushClipRect(clip_rect.Min, clip_rect.Max, true);
+ PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
// Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
if (first_begin_of_the_frame)
window->WriteAccessed = false;
window->BeginCount++;
- g.SetNextWindowSizeConstraint = false;
+ g.NextWindowData.SizeConstraintCond = 0;
// Child window can be out of sight and have "negative" clip windows.
// Mark them as collapsed so commands are skipped earlier (we can't manually collapse because they have no title bar).
@@ -4969,29 +6232,19 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
return !window->SkipItems;
}
-// Old Begin() API with 5 parameters, avoid calling this version directly! Use SetNextWindowSize()+Begin() instead.
+// Old Begin() API with 5 parameters, avoid calling this version directly! Use SetNextWindowSize()/SetNextWindowBgAlpha() + Begin() instead.
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
-bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_on_first_use, float bg_alpha_override, ImGuiWindowFlags flags)
+bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_first_use, float bg_alpha_override, ImGuiWindowFlags flags)
{
- // Old API feature: we could pass the initial window size as a parameter, however this was very misleading because in most cases it would only affect the window when it didn't have storage in the .ini file.
- if (size_on_first_use.x != 0.0f || size_on_first_use.y != 0.0f)
- SetNextWindowSize(size_on_first_use, ImGuiCond_FirstUseEver);
+ // Old API feature: we could pass the initial window size as a parameter. This was misleading because it only had an effect if the window didn't have data in the .ini file.
+ if (size_first_use.x != 0.0f || size_first_use.y != 0.0f)
+ ImGui::SetNextWindowSize(size_first_use, ImGuiCond_FirstUseEver);
- // Old API feature: we could override the window background alpha with a parameter. This is actually tricky to reproduce manually because:
- // (1) there are multiple variants of WindowBg (popup, tooltip, etc.) and (2) you can't call PushStyleColor before Begin and PopStyleColor just after Begin() because of how CheckStackSizes() behave.
- // The user-side solution is to do backup = GetStyleColorVec4(ImGuiCol_xxxBG), PushStyleColor(ImGuiCol_xxxBg), Begin, PushStyleColor(ImGuiCol_xxxBg, backup), [...], PopStyleColor(), End(); PopStyleColor() - which is super awkward.
- // The alpha override was rarely used but for now we'll leave the Begin() variant around for a bit. We may either lift the constraint on CheckStackSizes() either add a SetNextWindowBgAlpha() helper that does it magically.
- ImGuiContext& g = *GImGui;
- const ImGuiCol bg_color_idx = GetWindowBgColorIdxFromFlags(flags);
- const ImVec4 bg_color_backup = g.Style.Colors[bg_color_idx];
+ // Old API feature: override the window background alpha with a parameter.
if (bg_alpha_override >= 0.0f)
- g.Style.Colors[bg_color_idx].w = bg_alpha_override;
-
- bool ret = Begin(name, p_open, flags);
+ ImGui::SetNextWindowBgAlpha(bg_alpha_override);
- if (bg_alpha_override >= 0.0f)
- g.Style.Colors[bg_color_idx] = bg_color_backup;
- return ret;
+ return ImGui::Begin(name, p_open, flags);
}
#endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS
@@ -5002,14 +6255,13 @@ void ImGui::End()
if (window->DC.ColumnsSet != NULL)
EndColumns();
- PopClipRect(); // inner window clip rectangle
+ PopClipRect(); // Inner window clip rectangle
// Stop logging
if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging
LogFinish();
- // Pop
- // NB: we don't clear 'window->RootWindow'. The pointer is allowed to live until the next call to Begin().
+ // Pop from window stack
g.CurrentWindowStack.pop_back();
if (window->Flags & ImGuiWindowFlags_Popup)
g.CurrentPopupStack.pop_back();
@@ -5069,7 +6321,7 @@ void ImGui::Scrollbar(ImGuiLayoutType direction)
bool held = false;
bool hovered = false;
const bool previously_held = (g.ActiveId == id);
- ButtonBehavior(bb, id, &hovered, &held);
+ ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_NoNavFocus);
float scroll_max = ImMax(1.0f, win_size_contents_v - win_size_avail_v);
float scroll_ratio = ImSaturate(scroll_v / scroll_max);
@@ -5130,12 +6382,13 @@ void ImGui::Scrollbar(ImGuiLayoutType direction)
void ImGui::BringWindowToFront(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
- if (g.Windows.back() == window)
+ ImGuiWindow* current_front_window = g.Windows.back();
+ if (current_front_window == window || current_front_window->RootWindow == window)
return;
- for (int i = 0; i < g.Windows.Size; i++)
+ 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.begin() + i);
+ g.Windows.erase(g.Windows.Data + i);
g.Windows.push_back(window);
break;
}
@@ -5160,8 +6413,17 @@ void ImGui::FocusWindow(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
- // Always mark the window we passed as focused. This is used for keyboard interactions such as tabbing.
- g.NavWindow = window;
+ if (g.NavWindow != window)
+ {
+ g.NavWindow = window;
+ if (window && g.NavDisableMouseHover)
+ g.NavMousePosDirty = true;
+ 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);
+ }
// Passing NULL allow to disable keyboard focus
if (!window)
@@ -5181,13 +6443,14 @@ void ImGui::FocusWindow(ImGuiWindow* window)
BringWindowToFront(window);
}
-void ImGui::FocusPreviousWindow()
+void ImGui::FocusFrontMostActiveWindow(ImGuiWindow* ignore_window)
{
ImGuiContext& g = *GImGui;
for (int i = g.Windows.Size - 1; i >= 0; i--)
- if (g.Windows[i]->WasActive && !(g.Windows[i]->Flags & ImGuiWindowFlags_ChildWindow))
+ if (g.Windows[i] != ignore_window && g.Windows[i]->WasActive && !(g.Windows[i]->Flags & ImGuiWindowFlags_ChildWindow))
{
- FocusWindow(g.Windows[i]);
+ ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(g.Windows[i]);
+ FocusWindow(focus_window);
return;
}
}
@@ -5240,7 +6503,7 @@ static ImFont* GetDefaultFont()
return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0];
}
-static void SetCurrentFont(ImFont* font)
+void ImGui::SetCurrentFont(ImFont* font)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
@@ -5360,41 +6623,47 @@ void ImGui::PopStyleColor(int count)
struct ImGuiStyleVarInfo
{
ImGuiDataType Type;
+ ImU32 Count;
ImU32 Offset;
void* GetVarPtr(ImGuiStyle* style) const { return (void*)((unsigned char*)style + Offset); }
};
-static const ImGuiStyleVarInfo GStyleVarInfo[ImGuiStyleVar_Count_] =
-{
- { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
- { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
- { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
- { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
- { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
- { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
- { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
- { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
- { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
- { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
- { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
- { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
- { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
- { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
- { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
- { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
- { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
+static const ImGuiStyleVarInfo GStyleVarInfo[] =
+{
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
+ { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
+ { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
+ { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
+ { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
+ { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
+ { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
+ { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
};
static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx)
{
- IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_Count_);
+ IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
+ IM_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
return &GStyleVarInfo[idx];
}
void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
{
const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
- if (var_info->Type == ImGuiDataType_Float)
+ if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
{
ImGuiContext& g = *GImGui;
float* pvar = (float*)var_info->GetVarPtr(&g.Style);
@@ -5408,7 +6677,7 @@ void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
{
const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
- if (var_info->Type == ImGuiDataType_Float2)
+ if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
{
ImGuiContext& g = *GImGui;
ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
@@ -5424,11 +6693,12 @@ void ImGui::PopStyleVar(int count)
ImGuiContext& g = *GImGui;
while (count > 0)
{
+ // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
ImGuiStyleMod& backup = g.StyleModifiers.back();
const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx);
- if (info->Type == ImGuiDataType_Float) (*(float*)info->GetVarPtr(&g.Style)) = backup.BackupFloat[0];
- else if (info->Type == ImGuiDataType_Float2) (*(ImVec2*)info->GetVarPtr(&g.Style)) = ImVec2(backup.BackupFloat[0], backup.BackupFloat[1]);
- else if (info->Type == ImGuiDataType_Int) (*(int*)info->GetVarPtr(&g.Style)) = backup.BackupInt[0];
+ void* data = info->GetVarPtr(&g.Style);
+ if (info->Type == ImGuiDataType_Float && info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; }
+ else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
g.StyleModifiers.pop_back();
count--;
}
@@ -5472,9 +6742,6 @@ const char* ImGui::GetStyleColorName(ImGuiCol idx)
case ImGuiCol_ResizeGrip: return "ResizeGrip";
case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
- case ImGuiCol_CloseButton: return "CloseButton";
- case ImGuiCol_CloseButtonHovered: return "CloseButtonHovered";
- case ImGuiCol_CloseButtonActive: return "CloseButtonActive";
case ImGuiCol_PlotLines: return "PlotLines";
case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
case ImGuiCol_PlotHistogram: return "PlotHistogram";
@@ -5482,6 +6749,8 @@ const char* ImGui::GetStyleColorName(ImGuiCol idx)
case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
case ImGuiCol_ModalWindowDarkening: return "ModalWindowDarkening";
case ImGuiCol_DragDropTarget: return "DragDropTarget";
+ case ImGuiCol_NavHighlight: return "NavHighlight";
+ case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
}
IM_ASSERT(0);
return "Unknown";
@@ -5504,24 +6773,33 @@ bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
{
IM_ASSERT((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0); // Flags not supported by this function
ImGuiContext& g = *GImGui;
- switch (flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows))
+
+ if (flags & ImGuiHoveredFlags_AnyWindow)
{
- case ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows:
- if (g.HoveredRootWindow != g.CurrentWindow->RootWindow)
- return false;
- break;
- case ImGuiHoveredFlags_RootWindow:
- if (g.HoveredWindow != g.CurrentWindow->RootWindow)
- return false;
- break;
- case ImGuiHoveredFlags_ChildWindows:
- if (g.HoveredWindow == NULL || !IsWindowChildOf(g.HoveredWindow, g.CurrentWindow))
+ if (g.HoveredWindow == NULL)
return false;
- break;
- default:
- if (g.HoveredWindow != g.CurrentWindow)
- return false;
- break;
+ }
+ else
+ {
+ switch (flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows))
+ {
+ case ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows:
+ if (g.HoveredRootWindow != g.CurrentWindow->RootWindow)
+ return false;
+ break;
+ case ImGuiHoveredFlags_RootWindow:
+ if (g.HoveredWindow != g.CurrentWindow->RootWindow)
+ return false;
+ break;
+ case ImGuiHoveredFlags_ChildWindows:
+ if (g.HoveredWindow == NULL || !IsWindowChildOf(g.HoveredWindow, g.CurrentWindow))
+ return false;
+ break;
+ default:
+ if (g.HoveredWindow != g.CurrentWindow)
+ return false;
+ break;
+ }
}
if (!IsWindowContentHoverable(g.HoveredRootWindow, flags))
@@ -5537,19 +6815,29 @@ 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;
+
switch (flags & (ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows))
{
case ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows:
- return g.NavWindow && g.CurrentWindow->RootWindow == g.NavWindow->RootWindow;
+ return g.NavWindow && g.NavWindow->RootWindow == g.CurrentWindow->RootWindow;
case ImGuiFocusedFlags_RootWindow:
- return g.CurrentWindow->RootWindow == g.NavWindow;
+ return g.NavWindow == g.CurrentWindow->RootWindow;
case ImGuiFocusedFlags_ChildWindows:
return g.NavWindow && IsWindowChildOf(g.NavWindow, g.CurrentWindow);
default:
- return g.CurrentWindow == g.NavWindow;
+ return g.NavWindow == g.CurrentWindow;
}
}
+// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
+bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
+{
+ ImGuiContext& g = *GImGui;
+ return window->Active && window == window->RootWindowForTabbing && (!(window->Flags & ImGuiWindowFlags_NoNavFocus) || window == g.NavWindow);
+}
+
float ImGui::GetWindowWidth()
{
ImGuiWindow* window = GImGui->CurrentWindow;
@@ -5569,6 +6857,13 @@ ImVec2 ImGui::GetWindowPos()
return window->Pos;
}
+static void SetWindowScrollX(ImGuiWindow* window, float new_scroll_x)
+{
+ window->DC.CursorMaxPos.x += window->Scroll.x; // SizeContents is generally computed based on CursorMaxPos which is affected by scroll position, so we need to apply our change to it.
+ window->Scroll.x = new_scroll_x;
+ window->DC.CursorMaxPos.x -= window->Scroll.x;
+}
+
static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y)
{
window->DC.CursorMaxPos.y += window->Scroll.y; // SizeContents is generally computed based on CursorMaxPos which is affected by scroll position, so we need to apply our change to it.
@@ -5581,13 +6876,15 @@ static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
return;
+
+ IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
// Set
const ImVec2 old_pos = window->Pos;
window->PosFloat = pos;
- window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
+ window->Pos = ImFloor(pos);
window->DC.CursorPos += (window->Pos - old_pos); // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
window->DC.CursorMaxPos += (window->Pos - old_pos); // And more importantly we need to adjust this so size calculation doesn't get affected.
}
@@ -5615,6 +6912,8 @@ static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond con
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
return;
+
+ IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
// Set
@@ -5706,45 +7005,55 @@ void ImGui::SetWindowFocus(const char* name)
void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
{
ImGuiContext& g = *GImGui;
- g.SetNextWindowPosVal = pos;
- g.SetNextWindowPosPivot = pivot;
- g.SetNextWindowPosCond = cond ? cond : ImGuiCond_Always;
+ IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
+ g.NextWindowData.PosVal = pos;
+ g.NextWindowData.PosPivotVal = pivot;
+ g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
}
void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
- g.SetNextWindowSizeVal = size;
- g.SetNextWindowSizeCond = cond ? cond : ImGuiCond_Always;
+ IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
+ g.NextWindowData.SizeVal = size;
+ g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
}
-void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeConstraintCallback custom_callback, void* custom_callback_user_data)
+void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
{
ImGuiContext& g = *GImGui;
- g.SetNextWindowSizeConstraint = true;
- g.SetNextWindowSizeConstraintRect = ImRect(size_min, size_max);
- g.SetNextWindowSizeConstraintCallback = custom_callback;
- g.SetNextWindowSizeConstraintCallbackUserData = custom_callback_user_data;
+ g.NextWindowData.SizeConstraintCond = ImGuiCond_Always;
+ g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
+ g.NextWindowData.SizeCallback = custom_callback;
+ g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
}
void ImGui::SetNextWindowContentSize(const ImVec2& size)
{
ImGuiContext& g = *GImGui;
- g.SetNextWindowContentSizeVal = size; // In Begin() we will add the size of window decorations (title bar, menu etc.) to that to form a SizeContents value.
- g.SetNextWindowContentSizeCond = ImGuiCond_Always;
+ g.NextWindowData.ContentSizeVal = size; // In Begin() we will add the size of window decorations (title bar, menu etc.) to that to form a SizeContents value.
+ g.NextWindowData.ContentSizeCond = ImGuiCond_Always;
}
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
- g.SetNextWindowCollapsedVal = collapsed;
- g.SetNextWindowCollapsedCond = cond ? cond : ImGuiCond_Always;
+ IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
+ g.NextWindowData.CollapsedVal = collapsed;
+ g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
}
void ImGui::SetNextWindowFocus()
{
ImGuiContext& g = *GImGui;
- g.SetNextWindowFocus = true;
+ g.NextWindowData.FocusCond = ImGuiCond_Always; // Using a Cond member for consistency (may transition all of them to single flag set for fast Clear() op)
+}
+
+void ImGui::SetNextWindowBgAlpha(float alpha)
+{
+ ImGuiContext& g = *GImGui;
+ g.NextWindowData.BgAlphaVal = alpha;
+ g.NextWindowData.BgAlphaCond = ImGuiCond_Always; // Using a Cond member for consistency (may transition all of them to single flag set for fast Clear() op)
}
// In window space (not screen space!)
@@ -5958,13 +7267,10 @@ void ImGui::SetScrollHere(float center_y_ratio)
SetScrollFromPosY(target_y, center_y_ratio);
}
-// FIXME-NAV: This function is a placeholder for the upcoming Navigation branch + Focusing features.
-// In the current branch this function will only set the scrolling, in the navigation branch it will also set your navigation cursor.
-// Prefer using "SetItemDefaultFocus()" over "if (IsWindowAppearing()) SetScrollHere()" when applicable.
-void ImGui::SetItemDefaultFocus()
+void ImGui::ActivateItem(ImGuiID id)
{
- if (IsWindowAppearing())
- SetScrollHere();
+ ImGuiContext& g = *GImGui;
+ g.NavNextActivateId = id;
}
void ImGui::SetKeyboardFocusHere(int offset)
@@ -5975,6 +7281,23 @@ void ImGui::SetKeyboardFocusHere(int offset)
window->FocusIdxTabRequestNext = INT_MAX;
}
+void ImGui::SetItemDefaultFocus()
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ if (!window->Appearing)
+ return;
+ if (g.NavWindow == window->RootWindowForNav && (g.NavInitRequest || g.NavInitResultId != 0) && g.NavLayer == g.NavWindow->DC.NavLayerCurrent)
+ {
+ g.NavInitRequest = false;
+ g.NavInitResultId = g.NavWindow->DC.LastItemId;
+ g.NavInitResultRectRel = ImRect(g.NavWindow->DC.LastItemRect.Min - g.NavWindow->Pos, g.NavWindow->DC.LastItemRect.Max - g.NavWindow->Pos);
+ NavUpdateAnyRequestFlag();
+ if (!IsItemVisible())
+ SetScrollHere();
+ }
+}
+
void ImGui::SetStateStorage(ImGuiStorage* tree)
{
ImGuiWindow* window = GetCurrentWindow();
@@ -6247,6 +7570,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
if (hovered && (flags & ImGuiButtonFlags_AllowItemOverlap) && (g.HoveredIdPreviousFrame != id && g.HoveredIdPreviousFrame != 0))
hovered = false;
+ // Mouse
if (hovered)
{
if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt))
@@ -6256,24 +7580,21 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
// PressedOnClick | <on click> | <on click> <on repeat> <on repeat> ..
// PressedOnRelease | <on release> | <on repeat> <on repeat> .. (NOT on release)
// PressedOnDoubleClick | <on dclick> | <on dclick> <on repeat> <on repeat> ..
+ // FIXME-NAV: We don't honor those different behaviors.
if ((flags & ImGuiButtonFlags_PressedOnClickRelease) && g.IO.MouseClicked[0])
{
- SetActiveID(id, window); // Hold on ID
+ SetActiveID(id, window);
+ if (!(flags & ImGuiButtonFlags_NoNavFocus))
+ SetFocusID(id, window);
FocusWindow(window);
- g.ActiveIdClickOffset = g.IO.MousePos - bb.Min;
}
if (((flags & ImGuiButtonFlags_PressedOnClick) && g.IO.MouseClicked[0]) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDoubleClicked[0]))
{
pressed = true;
if (flags & ImGuiButtonFlags_NoHoldingActiveID)
- {
ClearActiveID();
- }
else
- {
SetActiveID(id, window); // Hold on ID
- g.ActiveIdClickOffset = g.IO.MousePos - bb.Min;
- }
FocusWindow(window);
}
if ((flags & ImGuiButtonFlags_PressedOnRelease) && g.IO.MouseReleased[0])
@@ -6288,22 +7609,59 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
if ((flags & ImGuiButtonFlags_Repeat) && g.ActiveId == id && g.IO.MouseDownDuration[0] > 0.0f && IsMouseClicked(0, true))
pressed = true;
}
+
+ if (pressed)
+ g.NavDisableHighlight = true;
+ }
+
+ // Gamepad/Keyboard navigation
+ // We report navigated item as hovered but we don't set g.HoveredId to not interfere with mouse.
+ if (g.NavId == id && !g.NavDisableHighlight && g.NavDisableMouseHover && (g.ActiveId == 0 || g.ActiveId == id || g.ActiveId == window->MoveId))
+ hovered = true;
+
+ if (g.NavActivateDownId == id)
+ {
+ bool nav_activated_by_code = (g.NavActivateId == id);
+ bool nav_activated_by_inputs = IsNavInputPressed(ImGuiNavInput_Activate, (flags & ImGuiButtonFlags_Repeat) ? ImGuiInputReadMode_Repeat : ImGuiInputReadMode_Pressed);
+ if (nav_activated_by_code || nav_activated_by_inputs)
+ pressed = true;
+ if (nav_activated_by_code || nav_activated_by_inputs || g.ActiveId == id)
+ {
+ // Set active id so it can be queried by user via IsItemActive(), equivalent of holding the mouse button.
+ g.NavActivateId = id; // This is so SetActiveId assign a Nav source
+ SetActiveID(id, window);
+ if (!(flags & ImGuiButtonFlags_NoNavFocus))
+ SetFocusID(id, window);
+ g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right) | (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down);
+ }
}
bool held = false;
if (g.ActiveId == id)
{
- if (g.IO.MouseDown[0])
+ if (g.ActiveIdSource == ImGuiInputSource_Mouse)
{
- held = true;
+ if (g.ActiveIdIsJustActivated)
+ g.ActiveIdClickOffset = g.IO.MousePos - bb.Min;
+ if (g.IO.MouseDown[0])
+ {
+ held = true;
+ }
+ else
+ {
+ if (hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease))
+ if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps <on release>
+ if (!g.DragDropActive)
+ pressed = true;
+ ClearActiveID();
+ }
+ if (!(flags & ImGuiButtonFlags_NoNavFocus))
+ g.NavDisableHighlight = true;
}
- else
+ else if (g.ActiveIdSource == ImGuiInputSource_Nav)
{
- if (hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease))
- if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps <on release>
- if (!g.DragDropActive)
- pressed = true;
- ClearActiveID();
+ if (g.NavActivateDownId != id)
+ ClearActiveID();
}
}
@@ -6334,12 +7692,14 @@ bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags
if (!ItemAdd(bb, id))
return false;
- if (window->DC.ItemFlags & ImGuiItemFlags_ButtonRepeat) flags |= ImGuiButtonFlags_Repeat;
+ if (window->DC.ItemFlags & ImGuiItemFlags_ButtonRepeat)
+ flags |= ImGuiButtonFlags_Repeat;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
// Render
const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
+ RenderNavHighlight(bb, id);
RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb);
@@ -6366,17 +7726,16 @@ bool ImGui::SmallButton(const char* label)
return pressed;
}
-// Tip: use ImGui::PushID()/PopID() to push indices or pointers in the ID stack.
-// Then you can keep 'str_id' empty or the same for all your buttons (instead of creating a string based on a non-string id)
-bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg)
+bool ImGui::ArrowButton(const char* str_id, ImGuiDir dir)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
+ ImGuiContext& g = *GImGui;
const ImGuiID id = window->GetID(str_id);
- ImVec2 size = CalcItemSize(size_arg, 0.0f, 0.0f);
- const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
+ float sz = ImGui::GetFrameHeight();
+ const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(sz, sz));
ItemSize(bb);
if (!ItemAdd(bb, id))
return false;
@@ -6384,58 +7743,62 @@ bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg)
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held);
+ // Render
+ const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
+ RenderNavHighlight(bb, id);
+ RenderFrame(bb.Min, bb.Max, col, true, g.Style.FrameRounding);
+ RenderArrow(bb.Min + g.Style.FramePadding, dir);
+
return pressed;
}
-// Upper-right button to close a window.
-bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos, float radius)
+// Tip: use ImGui::PushID()/PopID() to push indices or pointers in the ID stack.
+// Then you can keep 'str_id' empty or the same for all your buttons (instead of creating a string based on a non-string id)
+bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg)
{
ImGuiWindow* window = GetCurrentWindow();
+ if (window->SkipItems)
+ return false;
- const ImRect bb(pos - ImVec2(radius,radius), pos + ImVec2(radius,radius));
+ const ImGuiID id = window->GetID(str_id);
+ ImVec2 size = CalcItemSize(size_arg, 0.0f, 0.0f);
+ const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
+ ItemSize(bb);
+ if (!ItemAdd(bb, id))
+ return false;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held);
- // Render
- const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_CloseButtonActive : hovered ? ImGuiCol_CloseButtonHovered : ImGuiCol_CloseButton);
- const ImVec2 center = bb.GetCenter();
- window->DrawList->AddCircleFilled(center, ImMax(2.0f, radius), col, 12);
-
- const float cross_extent = (radius * 0.7071f) - 1.0f;
- if (hovered)
- {
- window->DrawList->AddLine(center + ImVec2(+cross_extent,+cross_extent), center + ImVec2(-cross_extent,-cross_extent), GetColorU32(ImGuiCol_Text));
- window->DrawList->AddLine(center + ImVec2(+cross_extent,-cross_extent), center + ImVec2(-cross_extent,+cross_extent), GetColorU32(ImGuiCol_Text));
- }
-
return pressed;
}
-// [Internal]
-bool ImGui::ArrowButton(ImGuiID id, ImGuiDir dir, ImVec2 padding, ImGuiButtonFlags flags)
+// Button to close a window
+bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos, float radius)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
- if (window->SkipItems)
- return false;
- const ImGuiStyle& style = g.Style;
-
- const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize + padding.x * 2.0f, g.FontSize + padding.y * 2.0f));
- ItemSize(bb, style.FramePadding.y);
- if (!ItemAdd(bb, id))
- return false;
+ // We intentionally allow interaction when clipped so that a mechanical Alt,Right,Validate sequence close a window.
+ // (this isn't the regular behavior of buttons, but it doesn't affect the user much because navigation tends to keep items visible).
+ const ImRect bb(pos - ImVec2(radius,radius), pos + ImVec2(radius,radius));
+ bool is_clipped = !ItemAdd(bb, id);
bool hovered, held;
- bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
+ bool pressed = ButtonBehavior(bb, id, &hovered, &held);
+ if (is_clipped)
+ return pressed;
- const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
-#ifdef IMGUI_HAS_NAV
- RenderNavHighlight(bb, id);
-#endif
- RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
- RenderTriangle(bb.Min + padding, dir, 1.0f);
+ // Render
+ ImVec2 center = bb.GetCenter();
+ if (hovered)
+ window->DrawList->AddCircleFilled(center, ImMax(2.0f, radius), GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : ImGuiCol_ButtonHovered), 9);
+
+ float cross_extent = (radius * 0.7071f) - 1.0f;
+ ImU32 cross_col = GetColorU32(ImGuiCol_Text);
+ center -= ImVec2(0.5f, 0.5f);
+ window->DrawList->AddLine(center + ImVec2(+cross_extent,+cross_extent), center + ImVec2(-cross_extent,-cross_extent), cross_col, 1.0f);
+ window->DrawList->AddLine(center + ImVec2(+cross_extent,-cross_extent), center + ImVec2(-cross_extent,+cross_extent), cross_col, 1.0f);
return pressed;
}
@@ -6495,6 +7858,7 @@ bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const I
// Render
const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
+ RenderNavHighlight(bb, id);
RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, style.FrameRounding));
if (bg_col.w > 0.0f)
window->DrawList->AddRectFilled(image_bb.Min, image_bb.Max, GetColorU32(bg_col));
@@ -6511,8 +7875,9 @@ void ImGui::LogToTTY(int max_depth)
return;
ImGuiWindow* window = g.CurrentWindow;
- g.LogEnabled = true;
+ IM_ASSERT(g.LogFile == NULL);
g.LogFile = stdout;
+ g.LogEnabled = true;
g.LogStartDepth = window->DC.TreeDepth;
if (max_depth >= 0)
g.LogAutoExpandMaxDepth = max_depth;
@@ -6533,6 +7898,7 @@ void ImGui::LogToFile(int max_depth, const char* filename)
return;
}
+ IM_ASSERT(g.LogFile == NULL);
g.LogFile = ImFileOpen(filename, "ab");
if (!g.LogFile)
{
@@ -6553,8 +7919,9 @@ void ImGui::LogToClipboard(int max_depth)
return;
ImGuiWindow* window = g.CurrentWindow;
- g.LogEnabled = true;
+ IM_ASSERT(g.LogFile == NULL);
g.LogFile = NULL;
+ g.LogEnabled = true;
g.LogStartDepth = window->DC.TreeDepth;
if (max_depth >= 0)
g.LogAutoExpandMaxDepth = max_depth;
@@ -6567,7 +7934,6 @@ void ImGui::LogFinish()
return;
LogText(IM_NEWLINE);
- g.LogEnabled = false;
if (g.LogFile != NULL)
{
if (g.LogFile == stdout)
@@ -6581,6 +7947,7 @@ void ImGui::LogFinish()
SetClipboardText(g.LogClipboard->begin());
g.LogClipboard->clear();
}
+ g.LogEnabled = false;
}
// Helper to display logging buttons
@@ -6619,11 +7986,11 @@ bool ImGui::TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags)
ImGuiStorage* storage = window->DC.StateStorage;
bool is_open;
- if (g.SetNextTreeNodeOpenCond != 0)
+ if (g.NextTreeNodeOpenCond != 0)
{
- if (g.SetNextTreeNodeOpenCond & ImGuiCond_Always)
+ if (g.NextTreeNodeOpenCond & ImGuiCond_Always)
{
- is_open = g.SetNextTreeNodeOpenVal;
+ is_open = g.NextTreeNodeOpenVal;
storage->SetInt(id, is_open);
}
else
@@ -6632,7 +7999,7 @@ bool ImGui::TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags)
const int stored_value = storage->GetInt(id, -1);
if (stored_value == -1)
{
- is_open = g.SetNextTreeNodeOpenVal;
+ is_open = g.NextTreeNodeOpenVal;
storage->SetInt(id, is_open);
}
else
@@ -6640,7 +8007,7 @@ bool ImGui::TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags)
is_open = stored_value != 0;
}
}
- g.SetNextTreeNodeOpenCond = 0;
+ g.NextTreeNodeOpenCond = 0;
}
else
{
@@ -6673,12 +8040,12 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l
// We vertically grow up to current line height up the typical widget height.
const float text_base_offset_y = ImMax(padding.y, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it
const float frame_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + style.FramePadding.y*2), label_size.y + padding.y*2);
- ImRect bb = ImRect(window->DC.CursorPos, ImVec2(window->Pos.x + GetContentRegionMax().x, window->DC.CursorPos.y + frame_height));
+ ImRect frame_bb = ImRect(window->DC.CursorPos, ImVec2(window->Pos.x + GetContentRegionMax().x, window->DC.CursorPos.y + frame_height));
if (display_frame)
{
// Framed header expand a little outside the default padding
- bb.Min.x -= (float)(int)(window->WindowPadding.x*0.5f) - 1;
- bb.Max.x += (float)(int)(window->WindowPadding.x*0.5f) - 1;
+ frame_bb.Min.x -= (float)(int)(window->WindowPadding.x*0.5f) - 1;
+ frame_bb.Max.x += (float)(int)(window->WindowPadding.x*0.5f) - 1;
}
const float text_offset_x = (g.FontSize + (display_frame ? padding.x*3 : padding.x*2)); // Collapser arrow width + Spacing
@@ -6687,9 +8054,20 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l
// For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing
// (Ideally we'd want to add a flag for the user to specify if we want the hit test to be done up to the right side of the content or not)
- const ImRect interact_bb = display_frame ? bb : ImRect(bb.Min.x, bb.Min.y, bb.Min.x + text_width + style.ItemSpacing.x*2, bb.Max.y);
+ const ImRect interact_bb = display_frame ? frame_bb : ImRect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + text_width + style.ItemSpacing.x*2, frame_bb.Max.y);
bool is_open = TreeNodeBehaviorIsOpen(id, flags);
- if (!ItemAdd(interact_bb, id))
+
+ // Store a flag for the current depth to tell if we will allow closing this node when navigating one of its child.
+ // For this purpose we essentially compare if g.NavIdIsAlive went from 0 to 1 between TreeNode() and TreePop().
+ // This is currently only support 32 level deep and we are fine with (1 << Depth) overflowing into a zero.
+ if (is_open && !g.NavIdIsAlive && (flags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere) && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
+ window->DC.TreeDepthMayJumpToParentOnPop |= (1 << window->DC.TreeDepth);
+
+ bool item_add = ItemAdd(interact_bb, id);
+ window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HasDisplayRect;
+ window->DC.LastItemDisplayRect = frame_bb;
+
+ if (!item_add)
{
if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
TreePushRawID(id);
@@ -6702,20 +8080,37 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l
// - OpenOnArrow .................... single-click on arrow to open
// - OpenOnDoubleClick|OpenOnArrow .. single-click on arrow or double-click anywhere to open
ImGuiButtonFlags button_flags = ImGuiButtonFlags_NoKeyModifiers | ((flags & ImGuiTreeNodeFlags_AllowItemOverlap) ? ImGuiButtonFlags_AllowItemOverlap : 0);
- button_flags |= ImGuiButtonFlags_PressedOnDragDropHold;
+ if (!(flags & ImGuiTreeNodeFlags_Leaf))
+ button_flags |= ImGuiButtonFlags_PressedOnDragDropHold;
if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
button_flags |= ImGuiButtonFlags_PressedOnDoubleClick | ((flags & ImGuiTreeNodeFlags_OpenOnArrow) ? ImGuiButtonFlags_PressedOnClickRelease : 0);
bool hovered, held, pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags);
- if (pressed && !(flags & ImGuiTreeNodeFlags_Leaf))
- {
- bool toggled = !(flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick));
- if (flags & ImGuiTreeNodeFlags_OpenOnArrow)
- toggled |= IsMouseHoveringRect(interact_bb.Min, ImVec2(interact_bb.Min.x + text_offset_x, interact_bb.Max.y));
- if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
- toggled |= g.IO.MouseDoubleClicked[0];
- if (g.DragDropActive && is_open) // When using Drag and Drop "hold to open" we keep the node highlighted after opening, but never close it again.
- toggled = false;
+ if (!(flags & ImGuiTreeNodeFlags_Leaf))
+ {
+ bool toggled = false;
+ if (pressed)
+ {
+ toggled = !(flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick)) || (g.NavActivateId == id);
+ if (flags & ImGuiTreeNodeFlags_OpenOnArrow)
+ toggled |= IsMouseHoveringRect(interact_bb.Min, ImVec2(interact_bb.Min.x + text_offset_x, interact_bb.Max.y)) && (!g.NavDisableMouseHover);
+ if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
+ toggled |= g.IO.MouseDoubleClicked[0];
+ if (g.DragDropActive && is_open) // When using Drag and Drop "hold to open" we keep the node highlighted after opening, but never close it again.
+ toggled = false;
+ }
+
+ if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Left && is_open)
+ {
+ toggled = true;
+ NavMoveRequestCancel();
+ }
+ if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Right && !is_open) // If there's something upcoming on the line we may want to give it the priority?
+ {
+ toggled = true;
+ NavMoveRequestCancel();
+ }
+
if (toggled)
{
is_open = !is_open;
@@ -6727,36 +8122,40 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l
// Render
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
- const ImVec2 text_pos = bb.Min + ImVec2(text_offset_x, text_base_offset_y);
+ const ImVec2 text_pos = frame_bb.Min + ImVec2(text_offset_x, text_base_offset_y);
if (display_frame)
{
// Framed type
- RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
- RenderTriangle(bb.Min + ImVec2(padding.x, text_base_offset_y), is_open ? ImGuiDir_Down : ImGuiDir_Right, 1.0f);
+ RenderFrame(frame_bb.Min, frame_bb.Max, col, true, style.FrameRounding);
+ RenderNavHighlight(frame_bb, id, ImGuiNavHighlightFlags_TypeThin);
+ RenderArrow(frame_bb.Min + ImVec2(padding.x, text_base_offset_y), is_open ? ImGuiDir_Down : ImGuiDir_Right, 1.0f);
if (g.LogEnabled)
{
// NB: '##' is normally used to hide text (as a library-wide feature), so we need to specify the text range to make sure the ## aren't stripped out here.
const char log_prefix[] = "\n##";
const char log_suffix[] = "##";
LogRenderedText(&text_pos, log_prefix, log_prefix+3);
- RenderTextClipped(text_pos, bb.Max, label, label_end, &label_size);
+ RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size);
LogRenderedText(&text_pos, log_suffix+1, log_suffix+3);
}
else
{
- RenderTextClipped(text_pos, bb.Max, label, label_end, &label_size);
+ RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size);
}
}
else
{
// Unframed typed for tree nodes
if (hovered || (flags & ImGuiTreeNodeFlags_Selected))
- RenderFrame(bb.Min, bb.Max, col, false);
+ {
+ RenderFrame(frame_bb.Min, frame_bb.Max, col, false);
+ RenderNavHighlight(frame_bb, id, ImGuiNavHighlightFlags_TypeThin);
+ }
if (flags & ImGuiTreeNodeFlags_Bullet)
- RenderBullet(bb.Min + ImVec2(text_offset_x * 0.5f, g.FontSize*0.50f + text_base_offset_y));
+ RenderBullet(frame_bb.Min + ImVec2(text_offset_x * 0.5f, g.FontSize*0.50f + text_base_offset_y));
else if (!(flags & ImGuiTreeNodeFlags_Leaf))
- RenderTriangle(bb.Min + ImVec2(padding.x, g.FontSize*0.15f + text_base_offset_y), is_open ? ImGuiDir_Down : ImGuiDir_Right, 0.70f);
+ RenderArrow(frame_bb.Min + ImVec2(padding.x, g.FontSize*0.15f + text_base_offset_y), is_open ? ImGuiDir_Down : ImGuiDir_Right, 0.70f);
if (g.LogEnabled)
LogRenderedText(&text_pos, ">");
RenderText(text_pos, label, label_end, false);
@@ -6906,8 +8305,8 @@ void ImGui::SetNextTreeNodeOpen(bool is_open, ImGuiCond cond)
ImGuiContext& g = *GImGui;
if (g.CurrentWindow->SkipItems)
return;
- g.SetNextTreeNodeOpenVal = is_open;
- g.SetNextTreeNodeOpenCond = cond ? cond : ImGuiCond_Always;
+ g.NextTreeNodeOpenVal = is_open;
+ g.NextTreeNodeOpenCond = cond ? cond : ImGuiCond_Always;
}
void ImGui::PushID(const char* str_id)
@@ -7017,6 +8416,8 @@ static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr,
ImFormatString(buf, buf_size, display_format, *(int*)data_ptr);
else if (data_type == ImGuiDataType_Float)
ImFormatString(buf, buf_size, display_format, *(float*)data_ptr);
+ else if (data_type == ImGuiDataType_Double)
+ ImFormatString(buf, buf_size, display_format, *(double*)data_ptr);
}
static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size)
@@ -7035,30 +8436,47 @@ static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr,
else
ImFormatString(buf, buf_size, "%.*f", decimal_precision, *(float*)data_ptr);
}
+ else if (data_type == ImGuiDataType_Double)
+ {
+ if (decimal_precision < 0)
+ ImFormatString(buf, buf_size, "%f", *(double*)data_ptr);
+ else
+ ImFormatString(buf, buf_size, "%.*f", decimal_precision, *(double*)data_ptr);
+ }
}
-static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* value1, const void* value2)// Store into value1
+static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* arg1, const void* arg2)
{
+ IM_ASSERT(op == '+' || op == '-');
if (data_type == ImGuiDataType_Int)
{
- if (op == '+')
- *(int*)value1 = *(int*)value1 + *(const int*)value2;
- else if (op == '-')
- *(int*)value1 = *(int*)value1 - *(const int*)value2;
+ if (op == '+') *(int*)output = *(int*)arg1 + *(const int*)arg2;
+ else if (op == '-') *(int*)output = *(int*)arg1 - *(const int*)arg2;
}
else if (data_type == ImGuiDataType_Float)
{
- if (op == '+')
- *(float*)value1 = *(float*)value1 + *(const float*)value2;
- else if (op == '-')
- *(float*)value1 = *(float*)value1 - *(const float*)value2;
+ if (op == '+') *(float*)output = *(float*)arg1 + *(const float*)arg2;
+ else if (op == '-') *(float*)output = *(float*)arg1 - *(const float*)arg2;
+ }
+ else if (data_type == ImGuiDataType_Double)
+ {
+ if (op == '+') *(double*)output = *(double*)arg1 + *(const double*)arg2;
+ else if (op == '-') *(double*)output = *(double*)arg1 - *(const double*)arg2;
}
}
+static size_t GDataTypeSize[ImGuiDataType_COUNT] =
+{
+ sizeof(int),
+ sizeof(float),
+ sizeof(double)
+};
+
// User can input math operators (e.g. +100) to edit a numerical values.
+// NB: This is _not_ a full expression evaluator. We should probably add one though..
static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format)
{
- while (ImCharIsSpace(*buf))
+ while (ImCharIsSpace((unsigned int)*buf))
buf++;
// We don't support '-' op because it would conflict with inputing negative value.
@@ -7067,7 +8485,7 @@ static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_b
if (op == '+' || op == '*' || op == '/')
{
buf++;
- while (ImCharIsSpace(*buf))
+ while (ImCharIsSpace((unsigned int)*buf))
buf++;
}
else
@@ -7077,45 +8495,56 @@ static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_b
if (!buf[0])
return false;
+ IM_ASSERT(data_type < ImGuiDataType_COUNT);
+ int data_backup[2];
+ IM_ASSERT(GDataTypeSize[data_type] <= sizeof(data_backup));
+ memcpy(data_backup, data_ptr, GDataTypeSize[data_type]);
+
if (data_type == ImGuiDataType_Int)
{
if (!scalar_format)
scalar_format = "%d";
int* v = (int*)data_ptr;
- const int old_v = *v;
int arg0i = *v;
if (op && sscanf(initial_value_buf, scalar_format, &arg0i) < 1)
return false;
-
// Store operand in a float so we can use fractional value for multipliers (*1.1), but constant always parsed as integer so we can fit big integers (e.g. 2000000003) past float precision
float arg1f = 0.0f;
if (op == '+') { if (sscanf(buf, "%f", &arg1f) == 1) *v = (int)(arg0i + arg1f); } // Add (use "+-" to subtract)
else if (op == '*') { if (sscanf(buf, "%f", &arg1f) == 1) *v = (int)(arg0i * arg1f); } // Multiply
else if (op == '/') { if (sscanf(buf, "%f", &arg1f) == 1 && arg1f != 0.0f) *v = (int)(arg0i / arg1f); }// Divide
- else { if (sscanf(buf, scalar_format, &arg0i) == 1) *v = arg0i; } // Assign constant (read as integer so big values are not lossy)
- return (old_v != *v);
+ else { if (sscanf(buf, scalar_format, &arg0i) == 1) *v = arg0i; } // Assign integer constant
}
else if (data_type == ImGuiDataType_Float)
{
// For floats we have to ignore format with precision (e.g. "%.2f") because sscanf doesn't take them in
scalar_format = "%f";
float* v = (float*)data_ptr;
- const float old_v = *v;
- float arg0f = *v;
+ float arg0f = *v, arg1f = 0.0f;
if (op && sscanf(initial_value_buf, scalar_format, &arg0f) < 1)
return false;
-
- float arg1f = 0.0f;
if (sscanf(buf, scalar_format, &arg1f) < 1)
return false;
if (op == '+') { *v = arg0f + arg1f; } // Add (use "+-" to subtract)
else if (op == '*') { *v = arg0f * arg1f; } // Multiply
else if (op == '/') { if (arg1f != 0.0f) *v = arg0f / arg1f; } // Divide
else { *v = arg1f; } // Assign constant
- return (old_v != *v);
}
-
- return false;
+ else if (data_type == ImGuiDataType_Double)
+ {
+ scalar_format = "%lf";
+ double* v = (double*)data_ptr;
+ double arg0f = *v, arg1f = 0.0f;
+ if (op && sscanf(initial_value_buf, scalar_format, &arg0f) < 1)
+ return false;
+ if (sscanf(buf, scalar_format, &arg1f) < 1)
+ return false;
+ if (op == '+') { *v = arg0f + arg1f; } // Add (use "+-" to subtract)
+ else if (op == '*') { *v = arg0f * arg1f; } // Multiply
+ else if (op == '/') { if (arg1f != 0.0f) *v = arg0f / arg1f; } // Divide
+ else { *v = arg1f; } // Assign constant
+ }
+ return memcmp(data_backup, data_ptr, GDataTypeSize[data_type]) != 0;
}
// Create text input in place of a slider (when CTRL+Clicking on slider)
@@ -7128,6 +8557,7 @@ bool ImGui::InputScalarAsWidgetReplacement(const ImRect& aabb, const char* label
// Our replacement widget will override the focus ID (registered previously to allow for a TAB focus to happen)
// On the first frame, g.ScalarAsInputTextId == 0, then on subsequent frames it becomes == id
SetActiveID(g.ScalarAsInputTextId, window);
+ g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down);
SetHoveredID(0);
FocusableItemUnregister(window);
@@ -7224,7 +8654,9 @@ bool ImGui::SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v
const ImGuiStyle& style = g.Style;
// Draw frame
- RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
+ const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
+ RenderNavHighlight(frame_bb, id);
+ RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding);
const bool is_non_linear = (power < 1.0f-0.00001f) || (power > 1.0f+0.00001f);
const bool is_horizontal = (flags & ImGuiSliderFlags_Vertical) == 0;
@@ -7255,23 +8687,59 @@ bool ImGui::SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v
linear_zero_pos = v_min < 0.0f ? 1.0f : 0.0f;
}
- // Process clicking on the slider
+ // Process interacting with the slider
bool value_changed = false;
if (g.ActiveId == id)
{
bool set_new_value = false;
float clicked_t = 0.0f;
- if (g.IO.MouseDown[0])
+ if (g.ActiveIdSource == ImGuiInputSource_Mouse)
{
- const float mouse_abs_pos = is_horizontal ? g.IO.MousePos.x : g.IO.MousePos.y;
- clicked_t = (slider_usable_sz > 0.0f) ? ImClamp((mouse_abs_pos - slider_usable_pos_min) / slider_usable_sz, 0.0f, 1.0f) : 0.0f;
- if (!is_horizontal)
- clicked_t = 1.0f - clicked_t;
- set_new_value = true;
+ if (!g.IO.MouseDown[0])
+ {
+ ClearActiveID();
+ }
+ else
+ {
+ const float mouse_abs_pos = is_horizontal ? g.IO.MousePos.x : g.IO.MousePos.y;
+ clicked_t = (slider_usable_sz > 0.0f) ? ImClamp((mouse_abs_pos - slider_usable_pos_min) / slider_usable_sz, 0.0f, 1.0f) : 0.0f;
+ if (!is_horizontal)
+ clicked_t = 1.0f - clicked_t;
+ set_new_value = true;
+ }
}
- else
+ else if (g.ActiveIdSource == ImGuiInputSource_Nav)
{
- ClearActiveID();
+ const ImVec2 delta2 = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard | ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_RepeatFast, 0.0f, 0.0f);
+ float delta = is_horizontal ? delta2.x : -delta2.y;
+ if (g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated)
+ {
+ ClearActiveID();
+ }
+ else if (delta != 0.0f)
+ {
+ clicked_t = SliderBehaviorCalcRatioFromValue(*v, v_min, v_max, power, linear_zero_pos);
+ if (decimal_precision == 0 && !is_non_linear)
+ {
+ if (fabsf(v_max - v_min) <= 100.0f || IsNavInputDown(ImGuiNavInput_TweakSlow))
+ delta = ((delta < 0.0f) ? -1.0f : +1.0f) / (v_max - v_min); // Gamepad/keyboard tweak speeds in integer steps
+ else
+ delta /= 100.0f;
+ }
+ else
+ {
+ delta /= 100.0f; // Gamepad/keyboard tweak speeds in % of slider bounds
+ if (IsNavInputDown(ImGuiNavInput_TweakSlow))
+ delta /= 10.0f;
+ }
+ if (IsNavInputDown(ImGuiNavInput_TweakFast))
+ delta *= 10.0f;
+ set_new_value = true;
+ if ((clicked_t >= 1.0f && delta > 0.0f) || (clicked_t <= 0.0f && delta < 0.0f)) // This is to avoid applying the saturation when already past the limits
+ set_new_value = false;
+ else
+ clicked_t = ImSaturate(clicked_t + delta);
+ }
}
if (set_new_value)
@@ -7351,7 +8819,7 @@ bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, c
const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
// NB- we don't call ItemSize() yet because we may turn into a text edit box below
- if (!ItemAdd(total_bb, id))
+ if (!ItemAdd(total_bb, id, &frame_bb))
{
ItemSize(total_bb, style.FramePadding.y);
return false;
@@ -7365,11 +8833,13 @@ bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, c
// Tabbing or CTRL-clicking on Slider turns it into an input box
bool start_text_input = false;
const bool tab_focus_requested = FocusableItemRegister(window, id);
- if (tab_focus_requested || (hovered && g.IO.MouseClicked[0]))
+ if (tab_focus_requested || (hovered && g.IO.MouseClicked[0]) || g.NavActivateId == id || (g.NavInputId == id && g.ScalarAsInputTextId != id))
{
SetActiveID(id, window);
+ SetFocusID(id, window);
FocusWindow(window);
- if (tab_focus_requested || g.IO.KeyCtrl)
+ g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down);
+ if (tab_focus_requested || g.IO.KeyCtrl || g.NavInputId == id)
{
start_text_input = true;
g.ScalarAsInputTextId = 0;
@@ -7416,10 +8886,12 @@ bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float
display_format = "%.3f";
int decimal_precision = ParseFormatPrecision(display_format, 3);
- if (hovered && g.IO.MouseClicked[0])
+ if ((hovered && g.IO.MouseClicked[0]) || g.NavActivateId == id || g.NavInputId == id)
{
SetActiveID(id, window);
+ SetFocusID(id, window);
FocusWindow(window);
+ g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right);
}
// Actual slider behavior + render grab
@@ -7556,73 +9028,81 @@ bool ImGui::DragBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_s
// Draw frame
const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
+ RenderNavHighlight(frame_bb, id);
RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding);
bool value_changed = false;
- // Process clicking on the drag
+ // Process interacting with the drag
if (g.ActiveId == id)
{
- if (g.IO.MouseDown[0])
+ if (g.ActiveIdSource == ImGuiInputSource_Mouse && !g.IO.MouseDown[0])
+ ClearActiveID();
+ else if (g.ActiveIdSource == ImGuiInputSource_Nav && g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated)
+ ClearActiveID();
+ }
+ if (g.ActiveId == id)
+ {
+ if (g.ActiveIdIsJustActivated)
{
- if (g.ActiveIdIsJustActivated)
- {
- // Lock current value on click
- g.DragCurrentValue = *v;
- g.DragLastMouseDelta = ImVec2(0.f, 0.f);
- }
+ // Lock current value on click
+ g.DragCurrentValue = *v;
+ g.DragLastMouseDelta = ImVec2(0.f, 0.f);
+ }
- if (v_speed == 0.0f && (v_max - v_min) != 0.0f && (v_max - v_min) < FLT_MAX)
- v_speed = (v_max - v_min) * g.DragSpeedDefaultRatio;
+ if (v_speed == 0.0f && (v_max - v_min) != 0.0f && (v_max - v_min) < FLT_MAX)
+ v_speed = (v_max - v_min) * g.DragSpeedDefaultRatio;
- float v_cur = g.DragCurrentValue;
- const ImVec2 mouse_drag_delta = GetMouseDragDelta(0, 1.0f);
- float adjust_delta = 0.0f;
- //if (g.ActiveIdSource == ImGuiInputSource_Mouse)
- {
- adjust_delta = mouse_drag_delta.x - g.DragLastMouseDelta.x;
- if (g.IO.KeyShift && g.DragSpeedScaleFast >= 0.0f)
- adjust_delta *= g.DragSpeedScaleFast;
- if (g.IO.KeyAlt && g.DragSpeedScaleSlow >= 0.0f)
- adjust_delta *= g.DragSpeedScaleSlow;
- }
- adjust_delta *= v_speed;
+ float v_cur = g.DragCurrentValue;
+ const ImVec2 mouse_drag_delta = GetMouseDragDelta(0, 1.0f);
+ float adjust_delta = 0.0f;
+ if (g.ActiveIdSource == ImGuiInputSource_Mouse && IsMousePosValid())
+ {
+ adjust_delta = mouse_drag_delta.x - g.DragLastMouseDelta.x;
+ if (g.IO.KeyShift && g.DragSpeedScaleFast >= 0.0f)
+ adjust_delta *= g.DragSpeedScaleFast;
+ if (g.IO.KeyAlt && g.DragSpeedScaleSlow >= 0.0f)
+ adjust_delta *= g.DragSpeedScaleSlow;
g.DragLastMouseDelta.x = mouse_drag_delta.x;
+ }
+ if (g.ActiveIdSource == ImGuiInputSource_Nav)
+ {
+ adjust_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard|ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_RepeatFast, 1.0f/10.0f, 10.0f).x;
+ if (v_min < v_max && ((v_cur >= v_max && adjust_delta > 0.0f) || (v_cur <= v_min && adjust_delta < 0.0f))) // This is to avoid applying the saturation when already past the limits
+ adjust_delta = 0.0f;
+ v_speed = ImMax(v_speed, GetMinimumStepAtDecimalPrecision(decimal_precision));
+ }
+ adjust_delta *= v_speed;
- if (fabsf(adjust_delta) > 0.0f)
+ if (fabsf(adjust_delta) > 0.0f)
+ {
+ if (fabsf(power - 1.0f) > 0.001f)
{
- if (fabsf(power - 1.0f) > 0.001f)
- {
- // Logarithmic curve on both side of 0.0
- float v0_abs = v_cur >= 0.0f ? v_cur : -v_cur;
- float v0_sign = v_cur >= 0.0f ? 1.0f : -1.0f;
- float v1 = powf(v0_abs, 1.0f / power) + (adjust_delta * v0_sign);
- float v1_abs = v1 >= 0.0f ? v1 : -v1;
- float v1_sign = v1 >= 0.0f ? 1.0f : -1.0f; // Crossed sign line
- v_cur = powf(v1_abs, power) * v0_sign * v1_sign; // Reapply sign
- }
- else
- {
- v_cur += adjust_delta;
- }
-
- // Clamp
- if (v_min < v_max)
- v_cur = ImClamp(v_cur, v_min, v_max);
- g.DragCurrentValue = v_cur;
+ // Logarithmic curve on both side of 0.0
+ float v0_abs = v_cur >= 0.0f ? v_cur : -v_cur;
+ float v0_sign = v_cur >= 0.0f ? 1.0f : -1.0f;
+ float v1 = powf(v0_abs, 1.0f / power) + (adjust_delta * v0_sign);
+ float v1_abs = v1 >= 0.0f ? v1 : -v1;
+ float v1_sign = v1 >= 0.0f ? 1.0f : -1.0f; // Crossed sign line
+ v_cur = powf(v1_abs, power) * v0_sign * v1_sign; // Reapply sign
}
-
- // Round to user desired precision, then apply
- v_cur = RoundScalar(v_cur, decimal_precision);
- if (*v != v_cur)
+ else
{
- *v = v_cur;
- value_changed = true;
+ v_cur += adjust_delta;
}
+
+ // Clamp
+ if (v_min < v_max)
+ v_cur = ImClamp(v_cur, v_min, v_max);
+ g.DragCurrentValue = v_cur;
}
- else
+
+ // Round to user desired precision, then apply
+ v_cur = RoundScalar(v_cur, decimal_precision);
+ if (*v != v_cur)
{
- ClearActiveID();
+ *v = v_cur;
+ value_changed = true;
}
}
@@ -7646,7 +9126,7 @@ bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, f
const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
// NB- we don't call ItemSize() yet because we may turn into a text edit box below
- if (!ItemAdd(total_bb, id))
+ if (!ItemAdd(total_bb, id, &frame_bb))
{
ItemSize(total_bb, style.FramePadding.y);
return false;
@@ -7660,11 +9140,13 @@ bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, f
// Tabbing or CTRL-clicking on Drag turns it into an input box
bool start_text_input = false;
const bool tab_focus_requested = FocusableItemRegister(window, id);
- if (tab_focus_requested || (hovered && (g.IO.MouseClicked[0] || g.IO.MouseDoubleClicked[0])))
+ if (tab_focus_requested || (hovered && (g.IO.MouseClicked[0] || g.IO.MouseDoubleClicked[0])) || g.NavActivateId == id || (g.NavInputId == id && g.ScalarAsInputTextId != id))
{
SetActiveID(id, window);
+ SetFocusID(id, window);
FocusWindow(window);
- if (tab_focus_requested || g.IO.KeyCtrl || g.IO.MouseDoubleClicked[0])
+ g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down);
+ if (tab_focus_requested || g.IO.KeyCtrl || g.IO.MouseDoubleClicked[0] || g.NavInputId == id)
{
start_text_input = true;
g.ScalarAsInputTextId = 0;
@@ -7852,7 +9334,7 @@ void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_ge
const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding);
const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0));
ItemSize(total_bb, style.FramePadding.y);
- if (!ItemAdd(total_bb, 0))
+ if (!ItemAdd(total_bb, 0, &frame_bb))
return;
const bool hovered = ItemHoverable(inner_bb, 0);
@@ -7898,11 +9380,12 @@ void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_ge
}
const float t_step = 1.0f / (float)res_w;
+ const float inv_scale = (scale_min == scale_max) ? 0.0f : (1.0f / (scale_max - scale_min));
float v0 = values_getter(data, (0 + values_offset) % values_count);
float t0 = 0.0f;
- ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) / (scale_max - scale_min)) ); // Point in the normalized space of our target rectangle
- float histogram_zero_line_t = (scale_min * scale_max < 0.0f) ? (-scale_min / (scale_max - scale_min)) : (scale_min < 0.0f ? 0.0f : 1.0f); // Where does the zero line stands
+ ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) * inv_scale) ); // Point in the normalized space of our target rectangle
+ float histogram_zero_line_t = (scale_min * scale_max < 0.0f) ? (-scale_min * inv_scale) : (scale_min < 0.0f ? 0.0f : 1.0f); // Where does the zero line stands
const ImU32 col_base = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram);
const ImU32 col_hovered = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered);
@@ -7913,7 +9396,7 @@ void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_ge
const int v1_idx = (int)(t0 * item_count + 0.5f);
IM_ASSERT(v1_idx >= 0 && v1_idx < values_count);
const float v1 = values_getter(data, (v1_idx + values_offset + 1) % values_count);
- const ImVec2 tp1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) / (scale_max - scale_min)) );
+ const ImVec2 tp1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) * inv_scale) );
// NB: Draw calls are merged together by the DrawList system. Still, we should render our batch are lower level to save a bit of CPU.
ImVec2 pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0);
@@ -7953,7 +9436,7 @@ struct ImGuiPlotArrayGetterData
static float Plot_ArrayGetter(void* data, int idx)
{
ImGuiPlotArrayGetterData* plot_data = (ImGuiPlotArrayGetterData*)data;
- const float v = *(float*)(void*)((unsigned char*)plot_data->Values + (size_t)idx * plot_data->Stride);
+ const float v = *(const float*)(const void*)((const unsigned char*)plot_data->Values + (size_t)idx * plot_data->Stride);
return v;
}
@@ -8047,6 +9530,7 @@ bool ImGui::Checkbox(const char* label, bool* v)
if (pressed)
*v = !(*v);
+ RenderNavHighlight(total_bb, id);
RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding);
if (*v)
{
@@ -8113,6 +9597,7 @@ bool ImGui::RadioButton(const char* label, bool active)
bool hovered, held;
bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);
+ RenderNavHighlight(total_bb, id);
window->DrawList->AddCircleFilled(center, radius, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), 16);
if (active)
{
@@ -8360,12 +9845,16 @@ static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags f
if (c >= 0xE000 && c <= 0xF8FF) // Filter private Unicode range. I don't imagine anybody would want to input them. GLFW on OSX seems to send private characters for special keys like arrow keys.
return false;
- if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank))
+ if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_CharsScientific))
{
if (flags & ImGuiInputTextFlags_CharsDecimal)
if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/'))
return false;
+ if (flags & ImGuiInputTextFlags_CharsScientific)
+ if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/') && (c != 'e') && (c != 'E'))
+ return false;
+
if (flags & ImGuiInputTextFlags_CharsHexadecimal)
if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F'))
return false;
@@ -8429,6 +9918,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2
ImGuiWindow* draw_window = window;
if (is_multiline)
{
+ ItemAdd(total_bb, id, &frame_bb);
if (!BeginChildFrame(id, frame_bb.GetSize()))
{
EndChildFrame();
@@ -8441,7 +9931,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2
else
{
ItemSize(total_bb, style.FramePadding.y);
- if (!ItemAdd(total_bb, id))
+ if (!ItemAdd(total_bb, id, &frame_bb))
return false;
}
const bool hovered = ItemHoverable(frame_bb, id);
@@ -8474,11 +9964,12 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2
const bool user_clicked = hovered && io.MouseClicked[0];
const bool user_scrolled = is_multiline && g.ActiveId == 0 && edit_state.Id == id && g.ActiveIdPreviousFrame == draw_window->GetIDNoKeepAlive("#SCROLLY");
+ const bool user_nav_input_start = (g.ActiveId != id) && ((g.NavInputId == id) || (g.NavActivateId == id && g.NavInputSource == ImGuiInputSource_NavKeyboard));
bool clear_active_id = false;
- bool select_all = (g.ActiveId != id) && (flags & ImGuiInputTextFlags_AutoSelectAll) != 0;
- if (focus_requested || user_clicked || user_scrolled)
+ bool select_all = (g.ActiveId != id) && ((flags & ImGuiInputTextFlags_AutoSelectAll) != 0 || user_nav_input_start) && (!is_multiline);
+ if (focus_requested || user_clicked || user_scrolled || user_nav_input_start)
{
if (g.ActiveId != id)
{
@@ -8517,7 +10008,10 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2
select_all = true;
}
SetActiveID(id, window);
+ SetFocusID(id, window);
FocusWindow(window);
+ if (!is_multiline && !(flags & ImGuiInputTextFlags_CallbackHistory))
+ g.ActiveIdAllowNavDirFlags |= ((1 << ImGuiDir_Up) | (1 << ImGuiDir_Down));
}
else if (io.MouseClicked[0])
{
@@ -8565,8 +10059,11 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2
}
else if (io.MouseClicked[0] && !edit_state.SelectedAllMouseLock)
{
- stb_textedit_click(&edit_state, &edit_state.StbState, mouse_x, mouse_y);
- edit_state.CursorAnimReset();
+ if (hovered)
+ {
+ stb_textedit_click(&edit_state, &edit_state.StbState, mouse_x, mouse_y);
+ edit_state.CursorAnimReset();
+ }
}
else if (io.MouseDown[0] && !edit_state.SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f))
{
@@ -8580,18 +10077,15 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2
if (io.InputCharacters[0])
{
// Process text input (before we check for Return because using some IME will effectively send a Return?)
- // We ignore CTRL inputs, but need to allow CTRL+ALT as some keyboards (e.g. German) use AltGR - which is Alt+Ctrl - to input certain characters.
- if (!(io.KeyCtrl && !io.KeyAlt) && is_editable)
- {
+ // We ignore CTRL inputs, but need to allow ALT+CTRL as some keyboards (e.g. German) use AltGR (which _is_ Alt+Ctrl) to input certain characters.
+ if (!(io.KeyCtrl && !io.KeyAlt) && is_editable && !user_nav_input_start)
for (int n = 0; n < IM_ARRAYSIZE(io.InputCharacters) && io.InputCharacters[n]; n++)
- if (unsigned int c = (unsigned int)io.InputCharacters[n])
- {
- // Insert character if they pass filtering
- if (!InputTextFilterCharacter(&c, flags, callback, user_data))
- continue;
+ {
+ // Insert character if they pass filtering
+ unsigned int c = (unsigned int)io.InputCharacters[n];
+ if (InputTextFilterCharacter(&c, flags, callback, user_data))
edit_state.OnKeyPressed((int)c);
- }
- }
+ }
// Consume characters
memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters));
@@ -8606,6 +10100,12 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2
const bool is_shortcut_key_only = (io.OptMacOSXBehaviors ? (io.KeySuper && !io.KeyCtrl) : (io.KeyCtrl && !io.KeySuper)) && !io.KeyAlt && !io.KeyShift; // OS X style: Shortcuts using Cmd/Super instead of Ctrl
const bool is_wordmove_key_down = io.OptMacOSXBehaviors ? io.KeyAlt : io.KeyCtrl; // OS X style: Text editing cursor movement using Alt instead of Ctrl
const bool is_startend_key_down = io.OptMacOSXBehaviors && io.KeySuper && !io.KeyCtrl && !io.KeyAlt; // OS X style: Line/Text Start and End using Cmd+Arrows instead of Home/End
+ const bool is_ctrl_key_only = io.KeyCtrl && !io.KeyShift && !io.KeyAlt && !io.KeySuper;
+ const bool is_shift_key_only = io.KeyShift && !io.KeyCtrl && !io.KeyAlt && !io.KeySuper;
+
+ const bool is_cut = ((is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_X)) || (is_shift_key_only && IsKeyPressedMap(ImGuiKey_Delete))) && is_editable && !is_password && (!is_multiline || edit_state.HasSelection());
+ const bool is_copy = ((is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_C)) || (is_ctrl_key_only && IsKeyPressedMap(ImGuiKey_Insert))) && !is_password && (!is_multiline || edit_state.HasSelection());
+ const bool is_paste = ((is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_V)) || (is_shift_key_only && IsKeyPressedMap(ImGuiKey_Insert))) && is_editable;
if (IsKeyPressedMap(ImGuiKey_LeftArrow)) { edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINESTART : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDLEFT : STB_TEXTEDIT_K_LEFT) | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_RightArrow)) { edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINEEND : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDRIGHT : STB_TEXTEDIT_K_RIGHT) | k_mask); }
@@ -8647,13 +10147,9 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2
else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Z) && is_editable && is_undoable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_UNDO); edit_state.ClearSelection(); }
else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Y) && is_editable && is_undoable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_REDO); edit_state.ClearSelection(); }
else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_A)) { edit_state.SelectAll(); edit_state.CursorFollow = true; }
- else if (is_shortcut_key_only && !is_password && ((IsKeyPressedMap(ImGuiKey_X) && is_editable) || IsKeyPressedMap(ImGuiKey_C)) && (!is_multiline || edit_state.HasSelection()))
+ else if (is_cut || is_copy)
{
// Cut, Copy
- const bool cut = IsKeyPressedMap(ImGuiKey_X);
- if (cut && !edit_state.HasSelection())
- edit_state.SelectAll();
-
if (io.SetClipboardTextFn)
{
const int ib = edit_state.HasSelection() ? ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end) : 0;
@@ -8663,13 +10159,15 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2
SetClipboardText(edit_state.TempTextBuffer.Data);
}
- if (cut)
+ if (is_cut)
{
+ if (!edit_state.HasSelection())
+ edit_state.SelectAll();
edit_state.CursorFollow = true;
stb_textedit_cut(&edit_state, &edit_state.StbState);
}
}
- else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_V) && is_editable)
+ else if (is_paste)
{
// Paste
if (const char* clipboard = GetClipboardText())
@@ -8810,6 +10308,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2
// Select which buffer we are going to display. When ImGuiInputTextFlags_NoLiveEdit is set 'buf' might still be the old value. We set buf to NULL to prevent accidental usage from now on.
const char* buf_display = (g.ActiveId == id && is_editable) ? edit_state.TempTextBuffer.Data : buf; buf = NULL;
+ RenderNavHighlight(frame_bb, id);
if (!is_multiline)
RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
@@ -9017,7 +10516,7 @@ bool ImGui::InputScalarEx(const char* label, ImGuiDataType data_type, void* data
DataTypeFormatString(data_type, data_ptr, scalar_format, buf, IM_ARRAYSIZE(buf));
bool value_changed = false;
- if (!(extra_flags & ImGuiInputTextFlags_CharsHexadecimal))
+ if ((extra_flags & (ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsScientific)) == 0)
extra_flags |= ImGuiInputTextFlags_CharsDecimal;
extra_flags |= ImGuiInputTextFlags_AutoSelectAll;
if (InputText("", buf, IM_ARRAYSIZE(buf), extra_flags)) // PushId(label) + "" gives us the expected ID from outside point of view
@@ -9030,13 +10529,13 @@ bool ImGui::InputScalarEx(const char* label, ImGuiDataType data_type, void* data
SameLine(0, style.ItemInnerSpacing.x);
if (ButtonEx("-", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups))
{
- DataTypeApplyOp(data_type, '-', data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr);
+ DataTypeApplyOp(data_type, '-', data_ptr, data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr);
value_changed = true;
}
SameLine(0, style.ItemInnerSpacing.x);
if (ButtonEx("+", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups))
{
- DataTypeApplyOp(data_type, '+', data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr);
+ DataTypeApplyOp(data_type, '+', data_ptr, data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr);
value_changed = true;
}
}
@@ -9055,19 +10554,31 @@ bool ImGui::InputScalarEx(const char* label, ImGuiDataType data_type, void* data
bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags extra_flags)
{
- char display_format[16];
+ extra_flags |= ImGuiInputTextFlags_CharsScientific;
if (decimal_precision < 0)
- strcpy(display_format, "%f"); // Ideally we'd have a minimum decimal precision of 1 to visually denote that this is a float, while hiding non-significant digits? %f doesn't have a minimum of 1
+ {
+ // Ideally we'd have a minimum decimal precision of 1 to visually denote that this is a float, while hiding non-significant digits? %f doesn't have a minimum of 1
+ return InputScalarEx(label, ImGuiDataType_Float, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), "%f", extra_flags);
+ }
else
+ {
+ char display_format[16];
ImFormatString(display_format, IM_ARRAYSIZE(display_format), "%%.%df", decimal_precision);
- return InputScalarEx(label, ImGuiDataType_Float, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), display_format, extra_flags);
+ return InputScalarEx(label, ImGuiDataType_Float, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), display_format, extra_flags);
+ }
+}
+
+bool ImGui::InputDouble(const char* label, double* v, double step, double step_fast, const char* display_format, ImGuiInputTextFlags extra_flags)
+{
+ extra_flags |= ImGuiInputTextFlags_CharsScientific;
+ return InputScalarEx(label, ImGuiDataType_Double, (void*)v, (void*)(step>0.0 ? &step : NULL), (void*)(step_fast>0.0 ? &step_fast : NULL), display_format, extra_flags);
}
bool ImGui::InputInt(const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags extra_flags)
{
// Hexadecimal input provided as a convenience but the flag name is awkward. Typically you'd use InputText() to parse your own data, if you want to handle prefixes.
const char* scalar_format = (extra_flags & ImGuiInputTextFlags_CharsHexadecimal) ? "%08X" : "%d";
- return InputScalarEx(label, ImGuiDataType_Int, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), scalar_format, extra_flags);
+ return InputScalarEx(label, ImGuiDataType_Int, (void*)v, (void*)(step>0 ? &step : NULL), (void*)(step_fast>0 ? &step_fast : NULL), scalar_format, extra_flags);
}
bool ImGui::InputFloatN(const char* label, float* v, int components, int decimal_precision, ImGuiInputTextFlags extra_flags)
@@ -9166,51 +10677,62 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF
{
// Always consume the SetNextWindowSizeConstraint() call in our early return paths
ImGuiContext& g = *GImGui;
- bool backup_has_next_window_size_constraint = g.SetNextWindowSizeConstraint;
- g.SetNextWindowSizeConstraint = false;
-
+ ImGuiCond backup_next_window_size_constraint = g.NextWindowData.SizeConstraintCond;
+ g.NextWindowData.SizeConstraintCond = 0;
+
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
+ IM_ASSERT((flags & (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)) != (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)); // Can't use both flags together
+
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
- const float w = CalcItemWidth();
+ const float arrow_size = (flags & ImGuiComboFlags_NoArrowButton) ? 0.0f : GetFrameHeight();
const ImVec2 label_size = CalcTextSize(label, NULL, true);
+ const float w = (flags & ImGuiComboFlags_NoPreview) ? arrow_size : CalcItemWidth();
const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));
const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
ItemSize(total_bb, style.FramePadding.y);
- if (!ItemAdd(total_bb, id))
+ if (!ItemAdd(total_bb, id, &frame_bb))
return false;
bool hovered, held;
bool pressed = ButtonBehavior(frame_bb, id, &hovered, &held);
bool popup_open = IsPopupOpen(id);
- const float arrow_size = GetFrameHeight();
const ImRect value_bb(frame_bb.Min, frame_bb.Max - ImVec2(arrow_size, 0.0f));
- RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
- RenderFrame(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y), frame_bb.Max, GetColorU32(popup_open || hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button), true, style.FrameRounding); // FIXME-ROUNDING
- RenderTriangle(ImVec2(frame_bb.Max.x - arrow_size + style.FramePadding.y, frame_bb.Min.y + style.FramePadding.y), ImGuiDir_Down);
- if (preview_value != NULL)
+ const ImU32 frame_col = GetColorU32(hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
+ RenderNavHighlight(frame_bb, id);
+ if (!(flags & ImGuiComboFlags_NoPreview))
+ window->DrawList->AddRectFilled(frame_bb.Min, ImVec2(frame_bb.Max.x - arrow_size, frame_bb.Max.y), frame_col, style.FrameRounding, ImDrawCornerFlags_Left);
+ if (!(flags & ImGuiComboFlags_NoArrowButton))
+ {
+ window->DrawList->AddRectFilled(ImVec2(frame_bb.Max.x - arrow_size, frame_bb.Min.y), frame_bb.Max, GetColorU32((popup_open || hovered) ? ImGuiCol_ButtonHovered : ImGuiCol_Button), style.FrameRounding, (w <= arrow_size) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Right);
+ RenderArrow(ImVec2(frame_bb.Max.x - arrow_size + style.FramePadding.y, frame_bb.Min.y + style.FramePadding.y), ImGuiDir_Down);
+ }
+ RenderFrameBorder(frame_bb.Min, frame_bb.Max, style.FrameRounding);
+ if (preview_value != NULL && !(flags & ImGuiComboFlags_NoPreview))
RenderTextClipped(frame_bb.Min + style.FramePadding, value_bb.Max, preview_value, NULL, NULL, ImVec2(0.0f,0.0f));
if (label_size.x > 0)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
- if (pressed && !popup_open)
+ if ((pressed || g.NavActivateId == id) && !popup_open)
{
- OpenPopupEx(id, false);
+ if (window->DC.NavLayerCurrent == 0)
+ window->NavLastIds[0] = id;
+ OpenPopupEx(id);
popup_open = true;
}
if (!popup_open)
return false;
- if (backup_has_next_window_size_constraint)
+ if (backup_next_window_size_constraint)
{
- g.SetNextWindowSizeConstraint = true;
- g.SetNextWindowSizeConstraintRect.Min.x = ImMax(g.SetNextWindowSizeConstraintRect.Min.x, w);
+ g.NextWindowData.SizeConstraintCond = backup_next_window_size_constraint;
+ g.NextWindowData.SizeConstraintRect.Min.x = ImMax(g.NextWindowData.SizeConstraintRect.Min.x, w);
}
else
{
@@ -9229,14 +10751,15 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF
// Peak into expected window size so we can position it
if (ImGuiWindow* popup_window = FindWindowByName(name))
- {
- ImVec2 size_contents = CalcSizeContents(popup_window);
- ImVec2 size_expected = CalcSizeAfterConstraint(popup_window, CalcSizeAutoFit(popup_window, size_contents));
- if (flags & ImGuiComboFlags_PopupAlignLeft)
- popup_window->AutoPosLastDirection = ImGuiDir_Left;
- ImVec2 pos = FindBestWindowPosForPopup(frame_bb.GetBL(), size_expected, &popup_window->AutoPosLastDirection, frame_bb, ImGuiPopupPositionPolicy_ComboBox);
- SetNextWindowPos(pos);
- }
+ if (popup_window->WasActive)
+ {
+ ImVec2 size_contents = CalcSizeContents(popup_window);
+ ImVec2 size_expected = CalcSizeAfterConstraint(popup_window, CalcSizeAutoFit(popup_window, size_contents));
+ if (flags & ImGuiComboFlags_PopupAlignLeft)
+ popup_window->AutoPosLastDirection = ImGuiDir_Left;
+ ImVec2 pos = FindBestWindowPosForPopup(frame_bb.GetBL(), size_expected, &popup_window->AutoPosLastDirection, frame_bb, ImGuiPopupPositionPolicy_ComboBox);
+ SetNextWindowPos(pos);
+ }
ImGuiWindowFlags window_flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings;
if (!Begin(name, NULL, window_flags))
@@ -9271,7 +10794,7 @@ bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(voi
items_getter(data, *current_item, &preview_text);
// The old Combo() API exposed "popup_max_height_in_items", however the new more general BeginCombo() API doesn't, so we emulate it here.
- if (popup_max_height_in_items != -1 && !g.SetNextWindowSizeConstraint)
+ if (popup_max_height_in_items != -1 && !g.NextWindowData.SizeConstraintCond)
{
float popup_max_height = CalcMaxPopupHeightFromItemCount(popup_max_height_in_items);
SetNextWindowSizeConstraints(ImVec2(0,0), ImVec2(FLT_MAX, popup_max_height));
@@ -9393,7 +10916,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl
bb_with_spacing.Min.y -= spacing_U;
bb_with_spacing.Max.x += spacing_R;
bb_with_spacing.Max.y += spacing_D;
- if (!ItemAdd(bb_with_spacing, id))
+ if (!ItemAdd(bb_with_spacing, (flags & ImGuiSelectableFlags_Disabled) ? 0 : id))
{
if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsSet)
PushColumnClipRect();
@@ -9410,11 +10933,20 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl
if (flags & ImGuiSelectableFlags_Disabled)
selected = false;
+ // Hovering selectable with mouse updates NavId accordingly so navigation can be resumed with gamepad/keyboard (this doesn't happen on most widgets)
+ if (pressed || hovered)// && (g.IO.MouseDelta.x != 0.0f || g.IO.MouseDelta.y != 0.0f))
+ if (!g.NavDisableMouseHover && g.NavWindow == window && g.NavLayer == window->DC.NavLayerActiveMask)
+ {
+ g.NavDisableHighlight = true;
+ SetNavID(id, window->DC.NavLayerCurrent);
+ }
+
// Render
if (hovered || selected)
{
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
RenderFrame(bb_with_spacing.Min, bb_with_spacing.Max, col, false, 0.0f);
+ RenderNavHighlight(bb_with_spacing, id, ImGuiNavHighlightFlags_TypeThin | ImGuiNavHighlightFlags_NoRounding);
}
if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsSet)
@@ -9460,7 +10992,7 @@ bool ImGui::ListBoxHeader(const char* label, const ImVec2& size_arg)
ImVec2 frame_size = ImVec2(size.x, ImMax(size.y, label_size.y));
ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size);
ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
- window->DC.LastItemRect = bb;
+ window->DC.LastItemRect = bb; // Forward storage for ListBoxFooter.. dodgy.
BeginGroup();
if (label_size.x > 0)
@@ -9502,7 +11034,7 @@ void ImGui::ListBoxFooter()
EndGroup();
}
-bool ImGui::ListBox(const char* label, int* current_item, const char* const* items, int items_count, int height_items)
+bool ImGui::ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_items)
{
const bool value_changed = ListBox(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_items);
return value_changed;
@@ -9530,6 +11062,8 @@ bool ImGui::ListBox(const char* label, int* current_item, bool (*items_getter)(v
*current_item = i;
value_changed = true;
}
+ if (item_selected)
+ SetItemDefaultFocus();
PopID();
}
ListBoxFooter();
@@ -9610,6 +11144,12 @@ bool ImGui::BeginMainMenuBar()
void ImGui::EndMainMenuBar()
{
EndMenuBar();
+
+ // When the user has left the menu layer (typically: closed menus through activation of an item), we restore focus to the previous window
+ ImGuiContext& g = *GImGui;
+ if (g.CurrentWindow == g.NavWindow && g.NavLayer == 0)
+ FocusFrontMostActiveWindow(g.NavWindow);
+
End();
PopStyleVar(2);
}
@@ -9630,11 +11170,13 @@ bool ImGui::BeginMenuBar()
// We remove 1 worth of rounding to Max.x to that text in long menus don't tend to display over the lower-right rounded area, which looks particularly glitchy.
ImRect bar_rect = window->MenuBarRect();
ImRect clip_rect(ImFloor(bar_rect.Min.x + 0.5f), ImFloor(bar_rect.Min.y + window->WindowBorderSize + 0.5f), ImFloor(ImMax(bar_rect.Min.x, bar_rect.Max.x - window->WindowRounding) + 0.5f), ImFloor(bar_rect.Max.y + 0.5f));
- clip_rect.ClipWith(window->Rect());
+ clip_rect.ClipWith(window->WindowRectClipped);
PushClipRect(clip_rect.Min, clip_rect.Max, false);
window->DC.CursorPos = ImVec2(bar_rect.Min.x + window->DC.MenuBarOffsetX, bar_rect.Min.y);// + g.Style.FramePadding.y);
window->DC.LayoutType = ImGuiLayoutType_Horizontal;
+ window->DC.NavLayerCurrent++;
+ window->DC.NavLayerCurrentMask <<= 1;
window->DC.MenuBarAppending = true;
AlignTextToFramePadding();
return true;
@@ -9645,6 +11187,27 @@ void ImGui::EndMenuBar()
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
+ ImGuiContext& g = *GImGui;
+
+ // Nav: When a move request within one of our child menu failed, capture the request to navigate among our siblings.
+ if (NavMoveRequestButNoResultYet() && (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right) && (g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
+ {
+ ImGuiWindow* nav_earliest_child = g.NavWindow;
+ while (nav_earliest_child->ParentWindow && (nav_earliest_child->ParentWindow->Flags & ImGuiWindowFlags_ChildMenu))
+ nav_earliest_child = nav_earliest_child->ParentWindow;
+ if (nav_earliest_child->ParentWindow == window && nav_earliest_child->DC.ParentLayoutType == ImGuiLayoutType_Horizontal && g.NavMoveRequestForward == ImGuiNavForward_None)
+ {
+ // To do so we claim focus back, restore NavId and then process the movement request for yet another frame.
+ // This involve a one-frame delay which isn't very problematic in this situation. We could remove it by scoring in advance for multiple window (probably not worth the hassle/cost)
+ IM_ASSERT(window->DC.NavLayerActiveMaskNext & 0x02); // Sanity check
+ FocusWindow(window);
+ SetNavIDWithRectRel(window->NavLastIds[1], 1, window->NavRectRel[1]);
+ g.NavLayer = 1;
+ g.NavDisableHighlight = true; // Hide highlight for the current frame so we don't see the intermediary selection.
+ g.NavMoveRequestForward = ImGuiNavForward_ForwardQueued;
+ NavMoveRequestCancel();
+ }
+ }
IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar);
IM_ASSERT(window->DC.MenuBarAppending);
@@ -9654,6 +11217,8 @@ void ImGui::EndMenuBar()
window->DC.GroupStack.back().AdvanceCursor = false;
EndGroup();
window->DC.LayoutType = ImGuiLayoutType_Vertical;
+ window->DC.NavLayerCurrent--;
+ window->DC.NavLayerCurrentMask >>= 1;
window->DC.MenuBarAppending = false;
}
@@ -9671,7 +11236,7 @@ bool ImGui::BeginMenu(const char* label, bool enabled)
bool pressed;
bool menu_is_open = IsPopupOpen(id);
- bool menuset_is_open = !(window->Flags & ImGuiWindowFlags_Popup) && (g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].ParentMenuSet == window->GetID("##Menus"));
+ bool menuset_is_open = !(window->Flags & ImGuiWindowFlags_Popup) && (g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].OpenParentId == window->IDStack.back());
ImGuiWindow* backed_nav_window = g.NavWindow;
if (menuset_is_open)
g.NavWindow = window; // Odd hack to allow hovering across menus of a same menu-set (otherwise we wouldn't be able to hover parent)
@@ -9699,7 +11264,7 @@ bool ImGui::BeginMenu(const char* label, bool enabled)
float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w);
pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_Menu | ImGuiSelectableFlags_DontClosePopups | ImGuiSelectableFlags_DrawFillAvailWidth | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f));
if (!enabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
- RenderTriangle(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.30f, 0.0f), ImGuiDir_Right);
+ RenderArrow(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.30f, 0.0f), ImGuiDir_Right);
if (!enabled) PopStyleColor();
}
@@ -9708,11 +11273,11 @@ bool ImGui::BeginMenu(const char* label, bool enabled)
g.NavWindow = backed_nav_window;
bool want_open = false, want_close = false;
- if (window->DC.LayoutType != ImGuiLayoutType_Horizontal) // (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu))
+ if (window->DC.LayoutType == ImGuiLayoutType_Vertical) // (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu))
{
// Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive.
bool moving_within_opened_triangle = false;
- if (g.HoveredWindow == window && g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].ParentWindow == window)
+ if (g.HoveredWindow == window && g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].ParentWindow == window && !(window->Flags & ImGuiWindowFlags_MenuBar))
{
if (ImGuiWindow* next_window = g.OpenPopupStack[g.CurrentPopupStack.Size].Window)
{
@@ -9731,6 +11296,17 @@ bool ImGui::BeginMenu(const char* label, bool enabled)
want_close = (menu_is_open && !hovered && g.HoveredWindow == window && g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrame != id && !moving_within_opened_triangle);
want_open = (!menu_is_open && hovered && !moving_within_opened_triangle) || (!menu_is_open && hovered && pressed);
+
+ if (g.NavActivateId == id)
+ {
+ want_close = menu_is_open;
+ want_open = !menu_is_open;
+ }
+ if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Right) // Nav-Right to open
+ {
+ want_open = true;
+ NavMoveRequestCancel();
+ }
}
else
{
@@ -9744,12 +11320,17 @@ bool ImGui::BeginMenu(const char* label, bool enabled)
{
want_open = true;
}
+ else if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Down) // Nav-Down to open
+ {
+ want_open = true;
+ NavMoveRequestCancel();
+ }
}
if (!enabled) // explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu("options", has_object)) { ..use object.. }'
want_close = true;
if (want_close && IsPopupOpen(id))
- ClosePopupToLevel(GImGui->CurrentPopupStack.Size);
+ ClosePopupToLevel(g.CurrentPopupStack.Size);
if (!menu_is_open && want_open && g.OpenPopupStack.Size > g.CurrentPopupStack.Size)
{
@@ -9774,6 +11355,17 @@ bool ImGui::BeginMenu(const char* label, bool enabled)
void ImGui::EndMenu()
{
+ // Nav: When a left move request _within our child menu_ failed, close the menu.
+ // A menu doesn't close itself because EndMenuBar() wants the catch the last Left<>Right inputs.
+ // However it means that with the current code, a BeginMenu() from outside another menu or a menu-bar won't be closable with the Left direction.
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ if (g.NavWindow && g.NavWindow->ParentWindow == window && g.NavMoveDir == ImGuiDir_Left && NavMoveRequestButNoResultYet() && window->DC.LayoutType == ImGuiLayoutType_Vertical)
+ {
+ ClosePopupToLevel(g.OpenPopupStack.Size - 1);
+ NavMoveRequestCancel();
+ }
+
EndPopup();
}
@@ -9910,6 +11502,7 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl
else
window->DrawList->AddRectFilled(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), rounding, ImDrawCornerFlags_All);
}
+ RenderNavHighlight(bb, id);
if (g.Style.FrameBorderSize > 0.0f)
RenderFrameBorder(bb.Min, bb.Max, rounding);
else
@@ -10129,7 +11722,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag
{
value_changed = true;
char* p = buf;
- while (*p == '#' || ImCharIsSpace(*p))
+ while (*p == '#' || ImCharIsSpace((unsigned int)*p))
p++;
i[0] = i[1] = i[2] = i[3] = 0;
if (alpha)
@@ -10207,7 +11800,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag
EndGroup();
// Drag and Drop Target
- if (window->DC.LastItemRectHoveredRect && BeginDragDropTarget()) // NB: The LastItemRectHoveredRect test is merely an optional micro-optimization
+ if ((window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) && BeginDragDropTarget()) // NB: The flag test is merely an optional micro-optimization, BeginDragDropTarget() does the same test.
{
if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F))
{
@@ -10247,7 +11840,7 @@ static void RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, ImGui
case ImGuiDir_Right: draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), pos, col); return;
case ImGuiDir_Up: draw_list->AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), pos, col); return;
case ImGuiDir_Down: draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), pos, col); return;
- case ImGuiDir_None: case ImGuiDir_Count_: break; // Fix warnings
+ case ImGuiDir_None: case ImGuiDir_COUNT: break; // Fix warnings
}
}
@@ -10318,6 +11911,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl
bool value_changed = false, value_changed_h = false, value_changed_sv = false;
+ PushItemFlag(ImGuiItemFlags_NoNav, true);
if (flags & ImGuiColorEditFlags_PickerHueWheel)
{
// Hue wheel + SV triangle logic
@@ -10387,6 +11981,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl
value_changed = true;
}
}
+ PopItemFlag(); // ImGuiItemFlags_NoNav
if (!(flags & ImGuiColorEditFlags_NoSidePreview))
{
@@ -10407,6 +12002,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl
if (!(flags & ImGuiColorEditFlags_NoSidePreview))
{
+ PushItemFlag(ImGuiItemFlags_NoNavDefaultFocus, true);
ImVec4 col_v4(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);
if ((flags & ImGuiColorEditFlags_NoLabel))
Text("Current");
@@ -10421,6 +12017,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl
value_changed = true;
}
}
+ PopItemFlag();
EndGroup();
}
@@ -10558,7 +12155,7 @@ void ImGui::Separator()
return;
ImGuiContext& g = *GImGui;
- ImGuiWindowFlags flags = 0;
+ ImGuiSeparatorFlags flags = 0;
if ((flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical)) == 0)
flags |= (window->DC.LayoutType == ImGuiLayoutType_Horizontal) ? ImGuiSeparatorFlags_Vertical : ImGuiSeparatorFlags_Horizontal;
IM_ASSERT(ImIsPowerOfTwo((int)(flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical)))); // Check that only 1 option is selected
@@ -10594,7 +12191,7 @@ void ImGui::Separator()
if (window->DC.ColumnsSet)
{
PushColumnClipRect();
- window->DC.ColumnsSet->CellMinY = window->DC.CursorPos.y;
+ window->DC.ColumnsSet->LineMinY = window->DC.CursorPos.y;
}
}
@@ -10623,12 +12220,10 @@ bool ImGui::SplitterBehavior(ImGuiID id, const ImRect& bb, ImGuiAxis axis, float
ImGuiWindow* window = g.CurrentWindow;
const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags;
-#ifdef IMGUI_HAS_NAV
window->DC.ItemFlags |= ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus;
-#endif
- bool add = ItemAdd(bb, id);
+ bool item_add = ItemAdd(bb, id);
window->DC.ItemFlags = item_flags_backup;
- if (!add)
+ if (!item_add)
return false;
bool hovered, held;
@@ -10815,7 +12410,7 @@ void ImGui::NextColumn()
PopClipRect();
ImGuiColumnsSet* columns = window->DC.ColumnsSet;
- columns->CellMaxY = ImMax(columns->CellMaxY, window->DC.CursorPos.y);
+ columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);
if (++columns->Current < columns->Count)
{
// Columns 1+ cancel out IndentX
@@ -10827,10 +12422,10 @@ void ImGui::NextColumn()
window->DC.ColumnsOffsetX = 0.0f;
window->DrawList->ChannelsSetCurrent(0);
columns->Current = 0;
- columns->CellMinY = columns->CellMaxY;
+ columns->LineMinY = columns->LineMaxY;
}
window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX);
- window->DC.CursorPos.y = columns->CellMinY;
+ window->DC.CursorPos.y = columns->LineMinY;
window->DC.CurrentLineHeight = 0.0f;
window->DC.CurrentLineTextBaseOffset = 0.0f;
@@ -10868,7 +12463,7 @@ static float GetDraggedColumnOffset(ImGuiColumnsSet* columns, int column_index)
// window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning.
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
- IM_ASSERT(column_index > 0); // We cannot drag column 0. If you get this assert you may have a conflict between the ID of your columns and another widgets.
+ IM_ASSERT(column_index > 0); // We are not supposed to drag column 0.
IM_ASSERT(g.ActiveId == columns->ID + ImGuiID(column_index));
float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x + GetColumnsRectHalfWidth() - window->Pos.x;
@@ -10889,16 +12484,6 @@ float ImGui::GetColumnOffset(int column_index)
column_index = columns->Current;
IM_ASSERT(column_index < columns->Columns.Size);
- /*
- if (g.ActiveId)
- {
- ImGuiContext& g = *GImGui;
- const ImGuiID column_id = columns->ColumnsSetId + ImGuiID(column_index);
- if (g.ActiveId == column_id)
- return GetDraggedColumnOffset(columns, column_index);
- }
- */
-
const float t = columns->Columns[column_index].OffsetNorm;
const float x_offset = ImLerp(columns->MinX, columns->MaxX, t);
return x_offset;
@@ -11006,16 +12591,19 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag
window->DC.ColumnsSet = columns;
// Set state for first column
- const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? (window->SizeContentsExplicit.x) : (window->Size.x -window->ScrollbarSizes.x);
+ const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? (window->SizeContentsExplicit.x) : (window->InnerClipRect.Max.x - window->Pos.x);
columns->MinX = window->DC.IndentX - g.Style.ItemSpacing.x; // Lock our horizontal range
- //column->MaxX = content_region_width - window->Scroll.x - ((window->Flags & ImGuiWindowFlags_NoScrollbar) ? 0 : g.Style.ScrollbarSize);// - window->WindowPadding().x;
- columns->MaxX = content_region_width - window->Scroll.x;
+ columns->MaxX = ImMax(content_region_width - window->Scroll.x, columns->MinX + 1.0f);
columns->StartPosY = window->DC.CursorPos.y;
columns->StartMaxPosX = window->DC.CursorMaxPos.x;
- columns->CellMinY = columns->CellMaxY = window->DC.CursorPos.y;
+ columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y;
window->DC.ColumnsOffsetX = 0.0f;
window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX);
+ // Clear data if columns count changed
+ if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1)
+ columns->Columns.resize(0);
+
// Initialize defaults
columns->IsFirstFrame = (columns->Columns.Size == 0);
if (columns->Columns.Size == 0)
@@ -11028,21 +12616,11 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag
columns->Columns.push_back(column);
}
}
- IM_ASSERT(columns->Columns.Size == columns_count + 1);
- for (int n = 0; n < columns_count + 1; n++)
+ for (int n = 0; n < columns_count; n++)
{
- // Clamp position
- ImGuiColumnData* column = &columns->Columns[n];
- float t = column->OffsetNorm;
- if (!(columns->Flags & ImGuiColumnsFlags_NoForceWithinWindow))
- t = ImMin(t, PixelsToOffsetNorm(columns, (columns->MaxX - columns->MinX) - g.Style.ColumnsMinSpacing * (columns->Count - n)));
- column->OffsetNorm = t;
-
- if (n == columns_count)
- continue;
-
// Compute clipping rectangle
+ ImGuiColumnData* column = &columns->Columns[n];
float clip_x1 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n) - 1.0f);
float clip_x2 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n + 1) - 1.0f);
column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX);
@@ -11065,8 +12643,8 @@ void ImGui::EndColumns()
PopClipRect();
window->DrawList->ChannelsMerge();
- columns->CellMaxY = ImMax(columns->CellMaxY, window->DC.CursorPos.y);
- window->DC.CursorPos.y = columns->CellMaxY;
+ columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);
+ window->DC.CursorPos.y = columns->LineMaxY;
if (!(columns->Flags & ImGuiColumnsFlags_GrowParentContentsSize))
window->DC.CursorMaxPos.x = ImMax(columns->StartMaxPosX, columns->MaxX); // Restore cursor max pos, as columns don't grow parent
@@ -11121,16 +12699,20 @@ void ImGui::EndColumns()
window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX);
}
-// [2017/12: This is currently the only public API, while we are working on making BeginColumns/EndColumns user-facing]
+// [2018-03: This is currently the only public API, while we are working on making BeginColumns/EndColumns user-facing]
void ImGui::Columns(int columns_count, const char* id, bool border)
{
ImGuiWindow* window = GetCurrentWindow();
IM_ASSERT(columns_count >= 1);
- if (window->DC.ColumnsSet != NULL && window->DC.ColumnsSet->Count != columns_count)
- EndColumns();
-
+
ImGuiColumnsFlags flags = (border ? 0 : ImGuiColumnsFlags_NoBorder);
//flags |= ImGuiColumnsFlags_NoPreserveWidths; // NB: Legacy behavior
+ if (window->DC.ColumnsSet != NULL && window->DC.ColumnsSet->Count == columns_count && window->DC.ColumnsSet->Flags == flags)
+ return;
+
+ if (window->DC.ColumnsSet != NULL)
+ EndColumns();
+
if (columns_count != 1)
BeginColumns(id, columns_count, flags);
}
@@ -11177,9 +12759,19 @@ void ImGui::TreePushRawID(ImGuiID id)
void ImGui::TreePop()
{
- ImGuiWindow* window = GetCurrentWindow();
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
Unindent();
+
window->DC.TreeDepth--;
+ if (g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet())
+ if (g.NavIdIsAlive && (window->DC.TreeDepthMayJumpToParentOnPop & (1 << window->DC.TreeDepth)))
+ {
+ SetNavID(window->IDStack.back(), g.NavLayer);
+ NavMoveRequestCancel();
+ }
+ window->DC.TreeDepthMayJumpToParentOnPop &= (1 << window->DC.TreeDepth) - 1;
+
PopID();
}
@@ -11228,7 +12820,7 @@ void ImGui::ClearDragDrop()
// Call when current ID is active.
// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
-bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags, int mouse_button)
+bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
@@ -11236,6 +12828,7 @@ bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags, int mouse_button)
bool source_drag_active = false;
ImGuiID source_id = 0;
ImGuiID source_parent_id = 0;
+ int mouse_button = 0;
if (!(flags & ImGuiDragDropFlags_SourceExtern))
{
source_id = window->DC.LastItemId;
@@ -11258,7 +12851,7 @@ bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags, int mouse_button)
// We build a throwaway ID based on current ID stack + relative AABB of items in window.
// THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
// We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
- bool is_hovered = window->DC.LastItemRectHoveredRect;
+ bool is_hovered = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) != 0;
if (!is_hovered && (g.ActiveId == 0 || g.ActiveIdWindow != window))
return false;
source_id = window->DC.LastItemId = window->GetIDFromRectangle(window->DC.LastItemRect);
@@ -11305,11 +12898,11 @@ bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags, int mouse_button)
//PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This is better but e.g ColorButton with checkboard has issue with transparent colors :(
SetNextWindowPos(g.IO.MousePos);
PushStyleColor(ImGuiCol_PopupBg, GetStyleColorVec4(ImGuiCol_PopupBg) * ImVec4(1.0f, 1.0f, 1.0f, 0.6f));
- BeginTooltipEx(ImGuiWindowFlags_NoInputs);
+ BeginTooltip();
}
if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
- window->DC.LastItemRectHoveredRect = false;
+ window->DC.LastItemStatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
return true;
}
@@ -11342,7 +12935,7 @@ bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_s
cond = ImGuiCond_Always;
IM_ASSERT(type != NULL);
- IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType)); // Payload type can be at most 8 characters longs
+ IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 12 characters long");
IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
@@ -11357,14 +12950,14 @@ bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_s
// Store in heap
g.DragDropPayloadBufHeap.resize((int)data_size);
payload.Data = g.DragDropPayloadBufHeap.Data;
- memcpy((void*)payload.Data, data, data_size);
+ memcpy((void*)(intptr_t)payload.Data, data, data_size);
}
else if (data_size > 0)
{
// Store locally
memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
payload.Data = g.DragDropPayloadBufLocal;
- memcpy((void*)payload.Data, data, data_size);
+ memcpy((void*)(intptr_t)payload.Data, data, data_size);
}
else
{
@@ -11406,18 +12999,19 @@ bool ImGui::BeginDragDropTarget()
return false;
ImGuiWindow* window = g.CurrentWindow;
- if (!window->DC.LastItemRectHoveredRect)
+ if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect))
return false;
if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow)
return false;
+ const ImRect& display_rect = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? window->DC.LastItemDisplayRect : window->DC.LastItemRect;
ImGuiID id = window->DC.LastItemId;
if (id == 0)
- id = window->GetIDFromRectangle(window->DC.LastItemRect);
+ id = window->GetIDFromRectangle(display_rect);
if (g.DragDropPayload.SourceId == id)
return false;
- g.DragDropTargetRect = window->DC.LastItemRect;
+ g.DragDropTargetRect = display_rect;
g.DragDropTargetId = id;
return true;
}
@@ -11484,7 +13078,11 @@ void ImGui::EndDragDropTarget()
#if defined(_WIN32) && !defined(_WINDOWS_) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS))
#undef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
+#ifndef __MINGW32__
#include <Windows.h>
+#else
+#include <windows.h>
+#endif
#endif
// Win32 API clipboard implementation
@@ -11594,17 +13192,17 @@ void ImGui::ShowMetricsWindow(bool* p_open)
{
if (ImGui::Begin("ImGui Metrics", p_open))
{
- ImGui::Text("ImGui %s", ImGui::GetVersion());
+ ImGui::Text("Dear ImGui %s", ImGui::GetVersion());
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::Text("%d vertices, %d indices (%d triangles)", ImGui::GetIO().MetricsRenderVertices, ImGui::GetIO().MetricsRenderIndices, ImGui::GetIO().MetricsRenderIndices / 3);
- ImGui::Text("%d allocations", ImGui::GetIO().MetricsAllocs);
+ ImGui::Text("%d allocations", (int)GImAllocatorActiveAllocationsCount);
static bool show_clip_rects = true;
- ImGui::Checkbox("Show clipping rectangles when hovering an ImDrawCmd", &show_clip_rects);
+ ImGui::Checkbox("Show clipping rectangles when hovering draw commands", &show_clip_rects);
ImGui::Separator();
struct Funcs
{
- static void NodeDrawList(ImDrawList* draw_list, const char* label)
+ static void NodeDrawList(ImGuiWindow* window, ImDrawList* draw_list, const char* label)
{
bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, draw_list->CmdBuffer.Size);
if (draw_list == ImGui::GetWindowDrawList())
@@ -11614,10 +13212,13 @@ void ImGui::ShowMetricsWindow(bool* p_open)
if (node_open) ImGui::TreePop();
return;
}
+
+ ImDrawList* overlay_draw_list = ImGui::GetOverlayDrawList(); // Render additional visuals into the top-most draw list
+ if (window && ImGui::IsItemHovered())
+ overlay_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
if (!node_open)
return;
- ImDrawList* overlay_draw_list = &GImGui->OverlayDrawList; // Render additional visuals into the top-most draw list
int elem_offset = 0;
for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.begin(); pcmd < draw_list->CmdBuffer.end(); elem_offset += pcmd->ElemCount, pcmd++)
{
@@ -11629,7 +13230,7 @@ void ImGui::ShowMetricsWindow(bool* p_open)
continue;
}
ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
- bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "Draw %-4d %s vtx, tex = %p, clip_rect = (%.0f,%.0f)..(%.0f,%.0f)", pcmd->ElemCount, draw_list->IdxBuffer.Size > 0 ? "indexed" : "non-indexed", pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
+ bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "Draw %4d %s vtx, tex 0x%p, clip_rect (%4.0f,%4.0f)-(%4.0f,%4.0f)", pcmd->ElemCount, draw_list->IdxBuffer.Size > 0 ? "indexed" : "non-indexed", pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
if (show_clip_rects && ImGui::IsItemHovered())
{
ImRect clip_rect = pcmd->ClipRect;
@@ -11654,7 +13255,7 @@ void ImGui::ShowMetricsWindow(bool* p_open)
{
ImDrawVert& v = draw_list->VtxBuffer[idx_buffer ? idx_buffer[vtx_i] : vtx_i];
triangles_pos[n] = v.pos;
- buf_p += ImFormatString(buf_p, (int)(buf_end - buf_p), "%s %04d { pos = (%8.2f,%8.2f), uv = (%.6f,%.6f), col = %08X }\n", (n == 0) ? "vtx" : " ", vtx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
+ buf_p += ImFormatString(buf_p, (int)(buf_end - buf_p), "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n", (n == 0) ? "vtx" : " ", vtx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
}
ImGui::Selectable(buf, false);
if (ImGui::IsItemHovered())
@@ -11683,26 +13284,49 @@ void ImGui::ShowMetricsWindow(bool* p_open)
{
if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, window->Active || window->WasActive, window))
return;
- NodeDrawList(window->DrawList, "DrawList");
+ 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);
- if (ImGui::IsItemHovered())
- GImGui->OverlayDrawList.AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255,255,0,255));
+ ImGui::BulletText("Flags: 0x%08X (%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 " : "");
ImGui::BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f)", window->Scroll.x, GetScrollMaxX(window), window->Scroll.y, GetScrollMaxY(window));
ImGui::BulletText("Active: %d, WriteAccessed: %d", window->Active, window->WriteAccessed);
+ ImGui::BulletText("NavLastIds: 0x%08X,0x%08X, NavLayerActiveMask: %X", window->NavLastIds[0], window->NavLastIds[1], window->DC.NavLayerActiveMask);
+ ImGui::BulletText("NavLastChildNavWindow: %s", window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
+ if (window->NavRectRel[0].IsInverted())
+ ImGui::BulletText("NavRectRel[0]: (%.1f,%.1f)(%.1f,%.1f)", window->NavRectRel[0].Min.x, window->NavRectRel[0].Min.y, window->NavRectRel[0].Max.x, window->NavRectRel[0].Max.y);
+ else
+ ImGui::BulletText("NavRectRel[0]: <None>");
if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow");
if (window->DC.ChildWindows.Size > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows");
+ if (window->ColumnsStorage.Size > 0 && ImGui::TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
+ {
+ for (int n = 0; n < window->ColumnsStorage.Size; n++)
+ {
+ const ImGuiColumnsSet* columns = &window->ColumnsStorage[n];
+ if (ImGui::TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
+ {
+ ImGui::BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->MaxX - columns->MinX, columns->MinX, columns->MaxX);
+ for (int column_n = 0; column_n < columns->Columns.Size; column_n++)
+ ImGui::BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, OffsetNormToPixels(columns, columns->Columns[column_n].OffsetNorm));
+ ImGui::TreePop();
+ }
+ }
+ ImGui::TreePop();
+ }
ImGui::BulletText("Storage: %d bytes", window->StateStorage.Data.Size * (int)sizeof(ImGuiStorage::Pair));
ImGui::TreePop();
}
};
- ImGuiContext& g = *GImGui; // Access private state
+ // Access private state, we are going to display the draw lists from last frame
+ ImGuiContext& g = *GImGui;
Funcs::NodeWindows(g.Windows, "Windows");
- if (ImGui::TreeNode("DrawList", "Active DrawLists (%d)", g.RenderDrawLists[0].Size))
+ if (ImGui::TreeNode("DrawList", "Active DrawLists (%d)", g.DrawDataBuilder.Layers[0].Size))
{
- for (int layer = 0; layer < IM_ARRAYSIZE(g.RenderDrawLists); layer++)
- for (int i = 0; i < g.RenderDrawLists[layer].Size; i++)
- Funcs::NodeDrawList(g.RenderDrawLists[0][i], "DrawList");
+ for (int i = 0; i < g.DrawDataBuilder.Layers[0].Size; i++)
+ Funcs::NodeDrawList(NULL, g.DrawDataBuilder.Layers[0][i], "DrawList");
ImGui::TreePop();
}
if (ImGui::TreeNode("Popups", "Open Popups Stack (%d)", g.OpenPopupStack.Size))
@@ -11714,14 +13338,22 @@ void ImGui::ShowMetricsWindow(bool* p_open)
}
ImGui::TreePop();
}
- if (ImGui::TreeNode("Basic state"))
+ if (ImGui::TreeNode("Internal state"))
{
+ const char* input_source_names[] = { "None", "Mouse", "Nav", "NavKeyboard", "NavGamepad" }; IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT);
ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL");
ImGui::Text("HoveredId: 0x%08X/0x%08X (%.2f sec)", g.HoveredId, g.HoveredIdPreviousFrame, g.HoveredIdTimer); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not
- ImGui::Text("ActiveId: 0x%08X/0x%08X (%.2f sec)", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer);
+ ImGui::Text("ActiveId: 0x%08X/0x%08X (%.2f sec), ActiveIdSource: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, input_source_names[g.ActiveIdSource]);
ImGui::Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
+ ImGui::Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
ImGui::Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
+ ImGui::Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
+ ImGui::Text("NavInputSource: %s", input_source_names[g.NavInputSource]);
+ ImGui::Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
+ ImGui::Text("NavActivateId: 0x%08X, NavInputId: 0x%08X", g.NavActivateId, g.NavInputId);
+ ImGui::Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
+ ImGui::Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
ImGui::TreePop();
}
}
diff --git a/imgui/imgui.h b/imgui/imgui.h
index 22e21398..d1174bd3 100644
--- a/imgui/imgui.h
+++ b/imgui/imgui.h
@@ -1,4 +1,4 @@
-// dear imgui, v1.53
+// dear imgui, v1.60
// (headers)
// See imgui.cpp file for documentation.
@@ -8,15 +8,20 @@
#pragma once
+// Configuration file (edit imconfig.h or define IMGUI_USER_CONFIG to set your own filename)
+#ifdef IMGUI_USER_CONFIG
+#include IMGUI_USER_CONFIG
+#endif
#if !defined(IMGUI_DISABLE_INCLUDE_IMCONFIG_H) || defined(IMGUI_INCLUDE_IMCONFIG_H)
-#include "imconfig.h" // User-editable configuration file
+#include "imconfig.h"
#endif
+
#include <float.h> // FLT_MAX
#include <stdarg.h> // va_list
#include <stddef.h> // ptrdiff_t, NULL
#include <string.h> // memset, memmove, memcpy, strlen, strchr, strcpy, strcmp
-#define IMGUI_VERSION "1.53"
+#define IMGUI_VERSION "1.60"
// Define attributes of all API symbols declarations, e.g. for DLL under Windows.
#ifndef IMGUI_API
@@ -30,15 +35,15 @@
#endif
// Helpers
-// Some compilers support applying printf-style warnings to user functions.
#if defined(__clang__) || defined(__GNUC__)
-#define IM_FMTARGS(FMT) __attribute__((format(printf, FMT, FMT+1)))
+#define IM_FMTARGS(FMT) __attribute__((format(printf, FMT, FMT+1))) // Apply printf-style warnings to user functions.
#define IM_FMTLIST(FMT) __attribute__((format(printf, FMT, 0)))
#else
#define IM_FMTARGS(FMT)
#define IM_FMTLIST(FMT)
#endif
-#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR)))
+#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR))) // Size of a static C-style array. Don't use on pointers!
+#define IM_OFFSETOF(_TYPE,_MEMBER) ((size_t)&(((_TYPE*)0)->_MEMBER)) // Offset of _MEMBER within _TYPE. Standardized as offsetof() in modern C++.
#if defined(__clang__)
#pragma clang diagnostic push
@@ -63,25 +68,33 @@ struct ImGuiStyle; // Runtime data for styling/colors
struct ImGuiTextFilter; // Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
struct ImGuiTextBuffer; // Text buffer for logging/accumulating text
struct ImGuiTextEditCallbackData; // Shared state of ImGui::InputText() when using custom ImGuiTextEditCallback (rare/advanced use)
-struct ImGuiSizeConstraintCallbackData;// Structure used to constraint window size in custom ways when using custom ImGuiSizeConstraintCallback (rare/advanced use)
+struct ImGuiSizeCallbackData; // Structure used to constraint window size in custom ways when using custom ImGuiSizeCallback (rare/advanced use)
struct ImGuiListClipper; // Helper to manually clip large list of items
struct ImGuiPayload; // User data payload for drag and drop operations
struct ImGuiContext; // ImGui context (opaque)
-// Typedefs and Enumerations (declared as int for compatibility and to not pollute the top of this file)
+#ifndef ImTextureID
+typedef void* ImTextureID; // User data to identify a texture (this is whatever to you want it to be! read the FAQ about ImTextureID in imgui.cpp)
+#endif
+
+// Typedefs and Enumerations (declared as int for compatibility with old C++ and to not pollute the top of this file)
typedef unsigned int ImU32; // 32-bit unsigned integer (typically used to store packed colors)
-typedef unsigned int ImGuiID; // unique ID used by widgets (typically hashed from a stack of string)
-typedef unsigned short ImWchar; // character for keyboard input/display
-typedef void* ImTextureID; // user data to identify a texture (this is whatever to you want it to be! read the FAQ about ImTextureID in imgui.cpp)
+typedef unsigned int ImGuiID; // Unique ID used by widgets (typically hashed from a stack of string)
+typedef unsigned short ImWchar; // Character for keyboard input/display
typedef int ImGuiCol; // enum: a color identifier for styling // enum ImGuiCol_
+typedef int ImGuiDir; // enum: a cardinal direction // enum ImGuiDir_
typedef int ImGuiCond; // enum: a condition for Set*() // enum ImGuiCond_
typedef int ImGuiKey; // enum: a key identifier (ImGui-side enum) // enum ImGuiKey_
+typedef int ImGuiNavInput; // enum: an input identifier for navigation // enum ImGuiNavInput_
typedef int ImGuiMouseCursor; // enum: a mouse cursor identifier // enum ImGuiMouseCursor_
typedef int ImGuiStyleVar; // enum: a variable identifier for styling // enum ImGuiStyleVar_
typedef int ImDrawCornerFlags; // flags: for ImDrawList::AddRect*() etc. // enum ImDrawCornerFlags_
typedef int ImDrawListFlags; // flags: for ImDrawList // enum ImDrawListFlags_
+typedef int ImFontAtlasFlags; // flags: for ImFontAtlas // enum ImFontAtlasFlags_
+typedef int ImGuiBackendFlags; // flags: for io.BackendFlags // enum ImGuiBackendFlags_
typedef int ImGuiColorEditFlags; // flags: for ColorEdit*(), ColorPicker*() // enum ImGuiColorEditFlags_
typedef int ImGuiColumnsFlags; // flags: for *Columns*() // enum ImGuiColumnsFlags_
+typedef int ImGuiConfigFlags; // flags: for io.ConfigFlags // enum ImGuiConfigFlags_
typedef int ImGuiDragDropFlags; // flags: for *DragDrop*() // enum ImGuiDragDropFlags_
typedef int ImGuiComboFlags; // flags: for BeginCombo() // enum ImGuiComboFlags_
typedef int ImGuiFocusedFlags; // flags: for IsWindowFocused() // enum ImGuiFocusedFlags_
@@ -91,22 +104,19 @@ typedef int ImGuiSelectableFlags; // flags: for Selectable()
typedef int ImGuiTreeNodeFlags; // flags: for TreeNode*(),CollapsingHeader()// enum ImGuiTreeNodeFlags_
typedef int ImGuiWindowFlags; // flags: for Begin*() // enum ImGuiWindowFlags_
typedef int (*ImGuiTextEditCallback)(ImGuiTextEditCallbackData *data);
-typedef void (*ImGuiSizeConstraintCallback)(ImGuiSizeConstraintCallbackData* data);
+typedef void (*ImGuiSizeCallback)(ImGuiSizeCallbackData* data);
#if defined(_MSC_VER) && !defined(__clang__)
typedef unsigned __int64 ImU64; // 64-bit unsigned integer
#else
typedef unsigned long long ImU64; // 64-bit unsigned integer
#endif
-// Others helpers at bottom of the file:
-// class ImVector<> // Lightweight std::vector like class.
-// IMGUI_ONCE_UPON_A_FRAME // Execute a block of code once per frame only (convenient for creating UI within deep-nested code that runs multiple times)
-
struct ImVec2
{
float x, y;
ImVec2() { x = y = 0.0f; }
ImVec2(float _x, float _y) { x = _x; y = _y; }
+ float operator[] (size_t idx) const { IM_ASSERT(idx <= 1); return (&x)[idx]; } // We very rarely use this [] operator, the assert overhead is fine.
#ifdef IM_VEC2_CLASS_EXTRA // Define constructor and implicit cast operators in imconfig.h to convert back<>forth from your math types and ImVec2.
IM_VEC2_CLASS_EXTRA
#endif
@@ -126,72 +136,94 @@ struct ImVec4
// In a namespace so that user can add extra functions in a separate file (e.g. Value() helpers for your vector or common types)
namespace ImGui
{
+ // Context creation and access
+ // All contexts share a same ImFontAtlas by default. If you want different font atlas, you can new() them and overwrite the GetIO().Fonts variable of an ImGui context.
+ // All those functions are not reliant on the current context.
+ IMGUI_API ImGuiContext* CreateContext(ImFontAtlas* shared_font_atlas = NULL);
+ IMGUI_API void DestroyContext(ImGuiContext* ctx = NULL); // NULL = destroy current context
+ IMGUI_API ImGuiContext* GetCurrentContext();
+ IMGUI_API void SetCurrentContext(ImGuiContext* ctx);
+
// Main
IMGUI_API ImGuiIO& GetIO();
IMGUI_API ImGuiStyle& GetStyle();
- IMGUI_API ImDrawData* GetDrawData(); // same value as passed to your io.RenderDrawListsFn() function. valid after Render() and until the next call to NewFrame()
IMGUI_API void NewFrame(); // start a new ImGui frame, you can submit any command from this point until Render()/EndFrame().
- IMGUI_API void Render(); // ends the ImGui frame, finalize the draw data, then call your io.RenderDrawListsFn() function if set.
+ IMGUI_API void Render(); // ends the ImGui frame, finalize the draw data. (Obsolete: optionally call io.RenderDrawListsFn if set. Nowadays, prefer calling your render function yourself.)
+ IMGUI_API ImDrawData* GetDrawData(); // valid after Render() and until the next call to NewFrame(). this is what you have to render. (Obsolete: this used to be passed to your io.RenderDrawListsFn() function.)
IMGUI_API void EndFrame(); // ends the ImGui frame. automatically called by Render(), so most likely don't need to ever call that yourself directly. If you don't need to render you may call EndFrame() but you'll have wasted CPU already. If you don't need to render, better to not create any imgui windows instead!
- IMGUI_API void Shutdown();
- // Demo, Debug, Informations
+ // Demo, Debug, Information
IMGUI_API void ShowDemoWindow(bool* p_open = NULL); // create demo/test window (previously called ShowTestWindow). demonstrate most ImGui features. call this to learn about the library! try to make it always available in your application!
IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // create metrics window. display ImGui internals: draw commands (with individual draw calls and vertices), window list, basic internal state, etc.
IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // add style editor block (not a window). you can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default style)
- IMGUI_API bool ShowStyleSelector(const char* label);
- IMGUI_API void ShowFontSelector(const char* label);
+ IMGUI_API bool ShowStyleSelector(const char* label); // add style selector block (not a window), essentially a combo listing the default styles.
+ IMGUI_API void ShowFontSelector(const char* label); // add font selector block (not a window), essentially a combo listing the loaded fonts.
IMGUI_API void ShowUserGuide(); // add basic help/info block (not a window): how to manipulate ImGui as a end-user (mouse/keyboard controls).
+ IMGUI_API const char* GetVersion(); // get a version string e.g. "1.23"
- // Window
- IMGUI_API bool Begin(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // push window to the stack and start appending to it. see .cpp for details. return false when window is collapsed, so you can early out in your code. 'bool* p_open' creates a widget on the upper-right to close the window (which sets your bool to false).
- IMGUI_API void End(); // finish appending to current window, pop it off the window stack.
- IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags extra_flags = 0); // begin a scrolling region. size==0.0f: use remaining window size, size<0.0f: use remaining window size minus abs(size). size>0.0f: fixed size. each axis can use a different mode, e.g. ImVec2(0,400).
- IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags extra_flags = 0); // "
+ // Styles
+ IMGUI_API void StyleColorsDark(ImGuiStyle* dst = NULL); // new, recommended style (default)
+ IMGUI_API void StyleColorsClassic(ImGuiStyle* dst = NULL); // classic imgui style
+ IMGUI_API void StyleColorsLight(ImGuiStyle* dst = NULL); // best used with borders and a custom, thicker font
+
+ // Windows
+ // (Begin = push window to the stack and start appending to it. End = pop window from the stack. You may append multiple times to the same window during the same frame)
+ // Begin()/BeginChild() return false to indicate the window being collapsed or fully clipped, so you may early out and omit submitting anything to the window.
+ // However you need to always call a matching End()/EndChild() for a Begin()/BeginChild() call, regardless of its return value (this is due to legacy reason and is inconsistent with BeginMenu/EndMenu, BeginPopup/EndPopup and other functions where the End call should only be called if the corresponding Begin function returned true.)
+ // Passing 'bool* p_open != NULL' shows a close widget in the upper-right corner of the window, which when clicking will set the boolean to false.
+ // Use child windows to introduce independent scrolling/clipping regions within a host window. Child windows can embed their own child.
+ IMGUI_API bool Begin(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0);
+ IMGUI_API void End();
+ IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags flags = 0); // Begin a scrolling region. size==0.0f: use remaining window size, size<0.0f: use remaining window size minus abs(size). size>0.0f: fixed size. each axis can use a different mode, e.g. ImVec2(0,400).
+ IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags flags = 0);
IMGUI_API void EndChild();
- IMGUI_API ImVec2 GetContentRegionMax(); // current content boundaries (typically window boundaries including scrolling, or current column boundaries), in windows coordinates
- IMGUI_API ImVec2 GetContentRegionAvail(); // == GetContentRegionMax() - GetCursorPos()
- IMGUI_API float GetContentRegionAvailWidth(); //
- IMGUI_API ImVec2 GetWindowContentRegionMin(); // content boundaries min (roughly (0,0)-Scroll), in window coordinates
- IMGUI_API ImVec2 GetWindowContentRegionMax(); // content boundaries max (roughly (0,0)+Size-Scroll) where Size can be override with SetNextWindowContentSize(), in window coordinates
- IMGUI_API float GetWindowContentRegionWidth(); //
- IMGUI_API ImDrawList* GetWindowDrawList(); // get rendering command-list if you want to append your own draw primitives
- IMGUI_API ImVec2 GetWindowPos(); // get current window position in screen space (useful if you want to do your own drawing via the DrawList api)
- IMGUI_API ImVec2 GetWindowSize(); // get current window size
- IMGUI_API float GetWindowWidth();
- IMGUI_API float GetWindowHeight();
- IMGUI_API bool IsWindowCollapsed();
+
+ // Windows Utilities
IMGUI_API bool IsWindowAppearing();
- IMGUI_API void SetWindowFontScale(float scale); // per-window font scale. Adjust IO.FontGlobalScale if you want to scale all windows
+ IMGUI_API bool IsWindowCollapsed();
+ IMGUI_API bool IsWindowFocused(ImGuiFocusedFlags flags=0); // is current window focused? or its root/child, depending on flags. see flags for options.
+ IMGUI_API bool IsWindowHovered(ImGuiHoveredFlags flags=0); // is current window hovered (and typically: not blocked by a popup/modal)? see flags for options. NB: If you are trying to check whether your mouse should be dispatched to imgui or to your app, you should use the 'io.WantCaptureMouse' boolean for that! Please read the FAQ!
+ IMGUI_API ImDrawList* GetWindowDrawList(); // get draw list associated to the window, to append your own drawing primitives
+ IMGUI_API ImVec2 GetWindowPos(); // get current window position in screen space (useful if you want to do your own drawing via the DrawList API)
+ IMGUI_API ImVec2 GetWindowSize(); // get current window size
+ IMGUI_API float GetWindowWidth(); // get current window width (shortcut for GetWindowSize().x)
+ IMGUI_API float GetWindowHeight(); // get current window height (shortcut for GetWindowSize().y)
+ IMGUI_API ImVec2 GetContentRegionMax(); // current content boundaries (typically window boundaries including scrolling, or current column boundaries), in windows coordinates
+ IMGUI_API ImVec2 GetContentRegionAvail(); // == GetContentRegionMax() - GetCursorPos()
+ IMGUI_API float GetContentRegionAvailWidth(); //
+ IMGUI_API ImVec2 GetWindowContentRegionMin(); // content boundaries min (roughly (0,0)-Scroll), in window coordinates
+ IMGUI_API ImVec2 GetWindowContentRegionMax(); // content boundaries max (roughly (0,0)+Size-Scroll) where Size can be override with SetNextWindowContentSize(), in window coordinates
+ IMGUI_API float GetWindowContentRegionWidth(); //
IMGUI_API void SetNextWindowPos(const ImVec2& pos, ImGuiCond cond = 0, const ImVec2& pivot = ImVec2(0,0)); // set next window position. call before Begin(). use pivot=(0.5f,0.5f) to center on given point, etc.
- IMGUI_API void SetNextWindowSize(const ImVec2& size, ImGuiCond cond = 0); // set next window size. set axis to 0.0f to force an auto-fit on this axis. call before Begin()
- IMGUI_API void SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeConstraintCallback custom_callback = NULL, void* custom_callback_data = NULL); // set next window size limits. use -1,-1 on either X/Y axis to preserve the current size. Use callback to apply non-trivial programmatic constraints.
- IMGUI_API void SetNextWindowContentSize(const ImVec2& size); // set next window content size (~ enforce the range of scrollbars). not including window decorations (title bar, menu bar, etc.). set an axis to 0.0f to leave it automatic. call before Begin()
- IMGUI_API void SetNextWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // set next window collapsed state. call before Begin()
- IMGUI_API void SetNextWindowFocus(); // set next window to be focused / front-most. call before Begin()
- IMGUI_API void SetWindowPos(const ImVec2& pos, ImGuiCond cond = 0); // (not recommended) set current window position - call within Begin()/End(). prefer using SetNextWindowPos(), as this may incur tearing and side-effects.
- IMGUI_API void SetWindowSize(const ImVec2& size, ImGuiCond cond = 0); // (not recommended) set current window size - call within Begin()/End(). set to ImVec2(0,0) to force an auto-fit. prefer using SetNextWindowSize(), as this may incur tearing and minor side-effects.
- IMGUI_API void SetWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed().
- IMGUI_API void SetWindowFocus(); // (not recommended) set current window to be focused / front-most. prefer using SetNextWindowFocus().
+ IMGUI_API void SetNextWindowSize(const ImVec2& size, ImGuiCond cond = 0); // set next window size. set axis to 0.0f to force an auto-fit on this axis. call before Begin()
+ IMGUI_API void SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback = NULL, void* custom_callback_data = NULL); // set next window size limits. use -1,-1 on either X/Y axis to preserve the current size. Use callback to apply non-trivial programmatic constraints.
+ IMGUI_API void SetNextWindowContentSize(const ImVec2& size); // set next window content size (~ enforce the range of scrollbars). not including window decorations (title bar, menu bar, etc.). set an axis to 0.0f to leave it automatic. call before Begin()
+ IMGUI_API void SetNextWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // set next window collapsed state. call before Begin()
+ IMGUI_API void SetNextWindowFocus(); // set next window to be focused / front-most. call before Begin()
+ IMGUI_API void SetNextWindowBgAlpha(float alpha); // set next window background color alpha. helper to easily modify ImGuiCol_WindowBg/ChildBg/PopupBg.
+ IMGUI_API void SetWindowPos(const ImVec2& pos, ImGuiCond cond = 0); // (not recommended) set current window position - call within Begin()/End(). prefer using SetNextWindowPos(), as this may incur tearing and side-effects.
+ IMGUI_API void SetWindowSize(const ImVec2& size, ImGuiCond cond = 0); // (not recommended) set current window size - call within Begin()/End(). set to ImVec2(0,0) to force an auto-fit. prefer using SetNextWindowSize(), as this may incur tearing and minor side-effects.
+ IMGUI_API void SetWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed().
+ IMGUI_API void SetWindowFocus(); // (not recommended) set current window to be focused / front-most. prefer using SetNextWindowFocus().
+ IMGUI_API void SetWindowFontScale(float scale); // set font scale. Adjust IO.FontGlobalScale if you want to scale all windows
IMGUI_API void SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond = 0); // set named window position.
IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond = 0); // set named window size. set axis to 0.0f to force an auto-fit on this axis.
IMGUI_API void SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond = 0); // set named window collapsed state
IMGUI_API void SetWindowFocus(const char* name); // set named window to be focused / front-most. use NULL to remove focus.
- IMGUI_API float GetScrollX(); // get scrolling amount [0..GetScrollMaxX()]
- IMGUI_API float GetScrollY(); // get scrolling amount [0..GetScrollMaxY()]
- IMGUI_API float GetScrollMaxX(); // get maximum scrolling amount ~~ ContentSize.X - WindowSize.X
- IMGUI_API float GetScrollMaxY(); // get maximum scrolling amount ~~ ContentSize.Y - WindowSize.Y
- IMGUI_API void SetScrollX(float scroll_x); // set scrolling amount [0..GetScrollMaxX()]
- IMGUI_API void SetScrollY(float scroll_y); // set scrolling amount [0..GetScrollMaxY()]
- IMGUI_API void SetScrollHere(float center_y_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_y_ratio=0.0: top, 0.5: center, 1.0: bottom. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead.
- IMGUI_API void SetScrollFromPosY(float pos_y, float center_y_ratio = 0.5f); // adjust scrolling amount to make given position valid. use GetCursorPos() or GetCursorStartPos()+offset to get valid positions.
- IMGUI_API void SetStateStorage(ImGuiStorage* tree); // replace tree state storage with our own (if you want to manipulate it yourself, typically clear subsection of it)
- IMGUI_API ImGuiStorage* GetStateStorage();
+ // Windows Scrolling
+ IMGUI_API float GetScrollX(); // get scrolling amount [0..GetScrollMaxX()]
+ IMGUI_API float GetScrollY(); // get scrolling amount [0..GetScrollMaxY()]
+ IMGUI_API float GetScrollMaxX(); // get maximum scrolling amount ~~ ContentSize.X - WindowSize.X
+ IMGUI_API float GetScrollMaxY(); // get maximum scrolling amount ~~ ContentSize.Y - WindowSize.Y
+ IMGUI_API void SetScrollX(float scroll_x); // set scrolling amount [0..GetScrollMaxX()]
+ IMGUI_API void SetScrollY(float scroll_y); // set scrolling amount [0..GetScrollMaxY()]
+ IMGUI_API void SetScrollHere(float center_y_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_y_ratio=0.0: top, 0.5: center, 1.0: bottom. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead.
+ IMGUI_API void SetScrollFromPosY(float pos_y, float center_y_ratio = 0.5f); // adjust scrolling amount to make given position valid. use GetCursorPos() or GetCursorStartPos()+offset to get valid positions.
// Parameters stacks (shared)
- IMGUI_API void PushFont(ImFont* font); // use NULL as a shortcut to push default font
+ IMGUI_API void PushFont(ImFont* font); // use NULL as a shortcut to push default font
IMGUI_API void PopFont();
IMGUI_API void PushStyleColor(ImGuiCol idx, ImU32 col);
IMGUI_API void PushStyleColor(ImGuiCol idx, const ImVec4& col);
@@ -199,93 +231,85 @@ namespace ImGui
IMGUI_API void PushStyleVar(ImGuiStyleVar idx, float val);
IMGUI_API void PushStyleVar(ImGuiStyleVar idx, const ImVec2& val);
IMGUI_API void PopStyleVar(int count = 1);
- IMGUI_API const ImVec4& GetStyleColorVec4(ImGuiCol idx); // retrieve style color as stored in ImGuiStyle structure. use to feed back into PushStyleColor(), otherwhise use GetColorU32() to get style color + style alpha.
- IMGUI_API ImFont* GetFont(); // get current font
- IMGUI_API float GetFontSize(); // get current font size (= height in pixels) of current font with current scale applied
- IMGUI_API ImVec2 GetFontTexUvWhitePixel(); // get UV coordinate for a while pixel, useful to draw custom shapes via the ImDrawList API
- IMGUI_API ImU32 GetColorU32(ImGuiCol idx, float alpha_mul = 1.0f); // retrieve given style color with style alpha applied and optional extra alpha multiplier
- IMGUI_API ImU32 GetColorU32(const ImVec4& col); // retrieve given color with style alpha applied
- IMGUI_API ImU32 GetColorU32(ImU32 col); // retrieve given color with style alpha applied
+ IMGUI_API const ImVec4& GetStyleColorVec4(ImGuiCol idx); // retrieve style color as stored in ImGuiStyle structure. use to feed back into PushStyleColor(), otherwhise use GetColorU32() to get style color with style alpha baked in.
+ IMGUI_API ImFont* GetFont(); // get current font
+ IMGUI_API float GetFontSize(); // get current font size (= height in pixels) of current font with current scale applied
+ IMGUI_API ImVec2 GetFontTexUvWhitePixel(); // get UV coordinate for a while pixel, useful to draw custom shapes via the ImDrawList API
+ IMGUI_API ImU32 GetColorU32(ImGuiCol idx, float alpha_mul = 1.0f); // retrieve given style color with style alpha applied and optional extra alpha multiplier
+ IMGUI_API ImU32 GetColorU32(const ImVec4& col); // retrieve given color with style alpha applied
+ IMGUI_API ImU32 GetColorU32(ImU32 col); // retrieve given color with style alpha applied
// Parameters stacks (current window)
- IMGUI_API void PushItemWidth(float item_width); // width of items for the common item+label case, pixels. 0.0f = default to ~2/3 of windows width, >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -1.0f always align width to the right side)
+ IMGUI_API void PushItemWidth(float item_width); // width of items for the common item+label case, pixels. 0.0f = default to ~2/3 of windows width, >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -1.0f always align width to the right side)
IMGUI_API void PopItemWidth();
- IMGUI_API float CalcItemWidth(); // width of item given pushed settings and current cursor position
- IMGUI_API void PushTextWrapPos(float wrap_pos_x = 0.0f); // word-wrapping for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at 'wrap_pos_x' position in window local space
+ IMGUI_API float CalcItemWidth(); // width of item given pushed settings and current cursor position
+ IMGUI_API void PushTextWrapPos(float wrap_pos_x = 0.0f); // word-wrapping for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at 'wrap_pos_x' position in window local space
IMGUI_API void PopTextWrapPos();
- IMGUI_API void PushAllowKeyboardFocus(bool allow_keyboard_focus); // allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets
+ IMGUI_API void PushAllowKeyboardFocus(bool allow_keyboard_focus); // allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets
IMGUI_API void PopAllowKeyboardFocus();
- IMGUI_API void PushButtonRepeat(bool repeat); // in 'repeat' mode, Button*() functions return repeated true in a typematic manner (using io.KeyRepeatDelay/io.KeyRepeatRate setting). Note that you can call IsItemActive() after any Button() to tell if the button is held in the current frame.
+ IMGUI_API void PushButtonRepeat(bool repeat); // in 'repeat' mode, Button*() functions return repeated true in a typematic manner (using io.KeyRepeatDelay/io.KeyRepeatRate setting). Note that you can call IsItemActive() after any Button() to tell if the button is held in the current frame.
IMGUI_API void PopButtonRepeat();
// Cursor / Layout
- IMGUI_API void Separator(); // separator, generally horizontal. inside a menu bar or in horizontal layout mode, this becomes a vertical separator.
- IMGUI_API void SameLine(float pos_x = 0.0f, float spacing_w = -1.0f); // call between widgets or groups to layout them horizontally
- IMGUI_API void NewLine(); // undo a SameLine()
- IMGUI_API void Spacing(); // add vertical spacing
- IMGUI_API void Dummy(const ImVec2& size); // add a dummy item of given size
- IMGUI_API void Indent(float indent_w = 0.0f); // move content position toward the right, by style.IndentSpacing or indent_w if != 0
- IMGUI_API void Unindent(float indent_w = 0.0f); // move content position back to the left, by style.IndentSpacing or indent_w if != 0
- IMGUI_API void BeginGroup(); // lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
+ IMGUI_API void Separator(); // separator, generally horizontal. inside a menu bar or in horizontal layout mode, this becomes a vertical separator.
+ IMGUI_API void SameLine(float pos_x = 0.0f, float spacing_w = -1.0f); // call between widgets or groups to layout them horizontally
+ IMGUI_API void NewLine(); // undo a SameLine()
+ IMGUI_API void Spacing(); // add vertical spacing
+ IMGUI_API void Dummy(const ImVec2& size); // add a dummy item of given size
+ IMGUI_API void Indent(float indent_w = 0.0f); // move content position toward the right, by style.IndentSpacing or indent_w if != 0
+ IMGUI_API void Unindent(float indent_w = 0.0f); // move content position back to the left, by style.IndentSpacing or indent_w if != 0
+ IMGUI_API void BeginGroup(); // lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
IMGUI_API void EndGroup();
- IMGUI_API ImVec2 GetCursorPos(); // cursor position is relative to window position
- IMGUI_API float GetCursorPosX(); // "
- IMGUI_API float GetCursorPosY(); // "
- IMGUI_API void SetCursorPos(const ImVec2& local_pos); // "
- IMGUI_API void SetCursorPosX(float x); // "
- IMGUI_API void SetCursorPosY(float y); // "
- IMGUI_API ImVec2 GetCursorStartPos(); // initial cursor position
- IMGUI_API ImVec2 GetCursorScreenPos(); // cursor position in absolute screen coordinates [0..io.DisplaySize] (useful to work with ImDrawList API)
- IMGUI_API void SetCursorScreenPos(const ImVec2& pos); // cursor position in absolute screen coordinates [0..io.DisplaySize]
- IMGUI_API void AlignTextToFramePadding(); // vertically align/lower upcoming text to FramePadding.y so that it will aligns to upcoming widgets (call if you have text on a line before regular widgets)
- IMGUI_API float GetTextLineHeight(); // ~ FontSize
- IMGUI_API float GetTextLineHeightWithSpacing(); // ~ FontSize + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of text)
- IMGUI_API float GetFrameHeight(); // ~ FontSize + style.FramePadding.y * 2
- IMGUI_API float GetFrameHeightWithSpacing(); // ~ FontSize + style.FramePadding.y * 2 + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of framed widgets)
-
- // Columns
- // You can also use SameLine(pos_x) for simplified columns. The columns API is still work-in-progress and rather lacking.
- IMGUI_API void Columns(int count = 1, const char* id = NULL, bool border = true);
- IMGUI_API void NextColumn(); // next column, defaults to current row or next row if the current row is finished
- IMGUI_API int GetColumnIndex(); // get current column index
- IMGUI_API float GetColumnWidth(int column_index = -1); // get column width (in pixels). pass -1 to use current column
- IMGUI_API void SetColumnWidth(int column_index, float width); // set column width (in pixels). pass -1 to use current column
- IMGUI_API float GetColumnOffset(int column_index = -1); // get position of column line (in pixels, from the left side of the contents region). pass -1 to use current column, otherwise 0..GetColumnsCount() inclusive. column 0 is typically 0.0f
- IMGUI_API void SetColumnOffset(int column_index, float offset_x); // set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column
- IMGUI_API int GetColumnsCount();
-
- // ID scopes
- // If you are creating widgets in a loop you most likely want to push a unique identifier (e.g. object pointer, loop index) so ImGui can differentiate them.
- // You can also use the "##foobar" syntax within widget label to distinguish them from each others. Read "A primer on the use of labels/IDs" in the FAQ for more details.
- IMGUI_API void PushID(const char* str_id); // push identifier into the ID stack. IDs are hash of the entire stack!
+ IMGUI_API ImVec2 GetCursorPos(); // cursor position is relative to window position
+ IMGUI_API float GetCursorPosX(); // "
+ IMGUI_API float GetCursorPosY(); // "
+ IMGUI_API void SetCursorPos(const ImVec2& local_pos); // "
+ IMGUI_API void SetCursorPosX(float x); // "
+ IMGUI_API void SetCursorPosY(float y); // "
+ IMGUI_API ImVec2 GetCursorStartPos(); // initial cursor position
+ IMGUI_API ImVec2 GetCursorScreenPos(); // cursor position in absolute screen coordinates [0..io.DisplaySize] (useful to work with ImDrawList API)
+ IMGUI_API void SetCursorScreenPos(const ImVec2& screen_pos); // cursor position in absolute screen coordinates [0..io.DisplaySize]
+ IMGUI_API void AlignTextToFramePadding(); // vertically align upcoming text baseline to FramePadding.y so that it will align properly to regularly framed items (call if you have text on a line before a framed item)
+ IMGUI_API float GetTextLineHeight(); // ~ FontSize
+ IMGUI_API float GetTextLineHeightWithSpacing(); // ~ FontSize + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of text)
+ IMGUI_API float GetFrameHeight(); // ~ FontSize + style.FramePadding.y * 2
+ IMGUI_API float GetFrameHeightWithSpacing(); // ~ FontSize + style.FramePadding.y * 2 + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of framed widgets)
+
+ // ID stack/scopes
+ // Read the FAQ for more details about how ID are handled in dear imgui. If you are creating widgets in a loop you most
+ // likely want to push a unique identifier (e.g. object pointer, loop index) to uniquely differentiate them.
+ // You can also use the "##foobar" syntax within widget label to distinguish them from each others.
+ // In this header file we use the "label"/"name" terminology to denote a string that will be displayed and used as an ID,
+ // whereas "str_id" denote a string that is only used as an ID and not aimed to be displayed.
+ IMGUI_API void PushID(const char* str_id); // push identifier into the ID stack. IDs are hash of the entire stack!
IMGUI_API void PushID(const char* str_id_begin, const char* str_id_end);
IMGUI_API void PushID(const void* ptr_id);
IMGUI_API void PushID(int int_id);
IMGUI_API void PopID();
- IMGUI_API ImGuiID GetID(const char* str_id); // calculate unique ID (hash of whole ID stack + given parameter). e.g. if you want to query into ImGuiStorage yourself
+ IMGUI_API ImGuiID GetID(const char* str_id); // calculate unique ID (hash of whole ID stack + given parameter). e.g. if you want to query into ImGuiStorage yourself
IMGUI_API ImGuiID GetID(const char* str_id_begin, const char* str_id_end);
IMGUI_API ImGuiID GetID(const void* ptr_id);
// Widgets: Text
- IMGUI_API void TextUnformatted(const char* text, const char* text_end = NULL); // raw text without formatting. Roughly equivalent to Text("%s", text) but: A) doesn't require null terminated string if 'text_end' is specified, B) it's faster, no memory copy is done, no buffer size limits, recommended for long chunks of text.
- IMGUI_API void Text(const char* fmt, ...) IM_FMTARGS(1); // simple formatted text
- IMGUI_API void TextV(const char* fmt, va_list args) IM_FMTLIST(1);
- IMGUI_API void TextColored(const ImVec4& col, const char* fmt, ...) IM_FMTARGS(2); // shortcut for PushStyleColor(ImGuiCol_Text, col); Text(fmt, ...); PopStyleColor();
- IMGUI_API void TextColoredV(const ImVec4& col, const char* fmt, va_list args) IM_FMTLIST(2);
- IMGUI_API void TextDisabled(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); Text(fmt, ...); PopStyleColor();
- IMGUI_API void TextDisabledV(const char* fmt, va_list args) IM_FMTLIST(1);
- IMGUI_API void TextWrapped(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushTextWrapPos(0.0f); Text(fmt, ...); PopTextWrapPos();. Note that this won't work on an auto-resizing window if there's no other widgets to extend the window width, yoy may need to set a size using SetNextWindowSize().
- IMGUI_API void TextWrappedV(const char* fmt, va_list args) IM_FMTLIST(1);
- IMGUI_API void LabelText(const char* label, const char* fmt, ...) IM_FMTARGS(2); // display text+label aligned the same way as value+label widgets
- IMGUI_API void LabelTextV(const char* label, const char* fmt, va_list args) IM_FMTLIST(2);
- IMGUI_API void BulletText(const char* fmt, ...) IM_FMTARGS(1); // shortcut for Bullet()+Text()
- IMGUI_API void BulletTextV(const char* fmt, va_list args) IM_FMTLIST(1);
- IMGUI_API void Bullet(); // draw a small circle and keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses
+ IMGUI_API void TextUnformatted(const char* text, const char* text_end = NULL); // raw text without formatting. Roughly equivalent to Text("%s", text) but: A) doesn't require null terminated string if 'text_end' is specified, B) it's faster, no memory copy is done, no buffer size limits, recommended for long chunks of text.
+ IMGUI_API void Text(const char* fmt, ...) IM_FMTARGS(1); // simple formatted text
+ IMGUI_API void TextV(const char* fmt, va_list args) IM_FMTLIST(1);
+ IMGUI_API void TextColored(const ImVec4& col, const char* fmt, ...) IM_FMTARGS(2); // shortcut for PushStyleColor(ImGuiCol_Text, col); Text(fmt, ...); PopStyleColor();
+ IMGUI_API void TextColoredV(const ImVec4& col, const char* fmt, va_list args) IM_FMTLIST(2);
+ IMGUI_API void TextDisabled(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); Text(fmt, ...); PopStyleColor();
+ IMGUI_API void TextDisabledV(const char* fmt, va_list args) IM_FMTLIST(1);
+ IMGUI_API void TextWrapped(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushTextWrapPos(0.0f); Text(fmt, ...); PopTextWrapPos();. Note that this won't work on an auto-resizing window if there's no other widgets to extend the window width, yoy may need to set a size using SetNextWindowSize().
+ IMGUI_API void TextWrappedV(const char* fmt, va_list args) IM_FMTLIST(1);
+ IMGUI_API void LabelText(const char* label, const char* fmt, ...) IM_FMTARGS(2); // display text+label aligned the same way as value+label widgets
+ IMGUI_API void LabelTextV(const char* label, const char* fmt, va_list args) IM_FMTLIST(2);
+ IMGUI_API void BulletText(const char* fmt, ...) IM_FMTARGS(1); // shortcut for Bullet()+Text()
+ IMGUI_API void BulletTextV(const char* fmt, va_list args) IM_FMTLIST(1);
// Widgets: Main
- IMGUI_API bool Button(const char* label, const ImVec2& size = ImVec2(0,0)); // button
- IMGUI_API bool SmallButton(const char* label); // button with FramePadding=(0,0) to easily embed within text
- IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size); // button behavior without the visuals, useful to build custom behaviors using the public api (along with IsItemActive, IsItemHovered, etc.)
+ IMGUI_API bool Button(const char* label, const ImVec2& size = ImVec2(0,0)); // button
+ IMGUI_API bool SmallButton(const char* label); // button with FramePadding=(0,0) to easily embed within text
+ IMGUI_API bool ArrowButton(const char* str_id, ImGuiDir dir);
+ IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size); // button behavior without the visuals, useful to build custom behaviors using the public api (along with IsItemActive, IsItemHovered, etc.)
IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), const ImVec4& tint_col = ImVec4(1,1,1,1), const ImVec4& border_col = ImVec4(0,0,0,0));
IMGUI_API bool ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0,0,0,0), const ImVec4& tint_col = ImVec4(1,1,1,1)); // <0 frame_padding uses default frame padding settings. 0 for no padding
IMGUI_API bool Checkbox(const char* label, bool* v);
@@ -297,18 +321,20 @@ namespace ImGui
IMGUI_API void PlotHistogram(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0), int stride = sizeof(float));
IMGUI_API void PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0));
IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-1,0), const char* overlay = NULL);
+ IMGUI_API void Bullet(); // draw a small circle and keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses
// Widgets: Combo Box
// The new BeginCombo()/EndCombo() api allows you to manage your contents and selection state however you want it.
// The old Combo() api are helpers over BeginCombo()/EndCombo() which are kept available for convenience purpose.
IMGUI_API bool BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags = 0);
- IMGUI_API void EndCombo();
+ IMGUI_API void EndCombo(); // only call EndCombo() if BeginCombo() returns true!
IMGUI_API bool Combo(const char* label, int* current_item, const char* const items[], int items_count, int popup_max_height_in_items = -1);
IMGUI_API bool Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int popup_max_height_in_items = -1); // Separate items with \0 within a string, end item-list with \0\0. e.g. "One\0Two\0Three\0"
IMGUI_API bool Combo(const char* label, int* current_item, bool(*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int popup_max_height_in_items = -1);
// Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can go off-bounds)
// For all the Float2/Float3/Float4/Int2/Int3/Int4 versions of every functions, note that a 'float v[X]' function argument is the same as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. You can pass address of your first element out of a contiguous set, e.g. &myvector.x
+ // Speed are per-pixel of mouse movement (v_speed=0.2f: mouse needs to move by 5 pixels to increase value by 1). For gamepad/keyboard navigation, minimum speed is Max(v_speed, minimum_step_at_given_precision).
IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f); // If v_min >= v_max we have no bound
IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f);
IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f);
@@ -331,6 +357,7 @@ namespace ImGui
IMGUI_API bool InputInt2(const char* label, int v[2], ImGuiInputTextFlags extra_flags = 0);
IMGUI_API bool InputInt3(const char* label, int v[3], ImGuiInputTextFlags extra_flags = 0);
IMGUI_API bool InputInt4(const char* label, int v[4], ImGuiInputTextFlags extra_flags = 0);
+ IMGUI_API bool InputDouble(const char* label, double* v, double step = 0.0f, double step_fast = 0.0f, const char* display_format = "%.6f", ImGuiInputTextFlags extra_flags = 0);
// Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can go off-bounds)
IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); // adjust display_format to decorate the value with a prefix or a suffix for in-slider labels or unit display. Use power!=1.0 for logarithmic sliders
@@ -352,12 +379,12 @@ namespace ImGui
IMGUI_API bool ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags = 0);
IMGUI_API bool ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags = 0, const float* ref_col = NULL);
IMGUI_API bool ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0,0)); // display a colored square/button, hover for details, return true when pressed.
- IMGUI_API void SetColorEditOptions(ImGuiColorEditFlags flags); // initialize current options (generally on application startup) if you want to select a default format, picker type, etc. User will be able to change many settings, unless you pass the _NoOptions flag to your calls.
+ IMGUI_API void SetColorEditOptions(ImGuiColorEditFlags flags); // initialize current options (generally on application startup) if you want to select a default format, picker type, etc. User will be able to change many settings, unless you pass the _NoOptions flag to your calls.
// Widgets: Trees
- IMGUI_API bool TreeNode(const char* label); // if returning 'true' the node is open and the tree id is pushed into the id stack. user is responsible for calling TreePop().
- IMGUI_API bool TreeNode(const char* str_id, const char* fmt, ...) IM_FMTARGS(2); // read the FAQ about why and how to use ID. to align arbitrary text at the same level as a TreeNode() you can use Bullet().
- IMGUI_API bool TreeNode(const void* ptr_id, const char* fmt, ...) IM_FMTARGS(2); // "
+ IMGUI_API bool TreeNode(const char* label); // if returning 'true' the node is open and the tree id is pushed into the id stack. user is responsible for calling TreePop().
+ IMGUI_API bool TreeNode(const char* str_id, const char* fmt, ...) IM_FMTARGS(2); // read the FAQ about why and how to use ID. to align arbitrary text at the same level as a TreeNode() you can use Bullet().
+ IMGUI_API bool TreeNode(const void* ptr_id, const char* fmt, ...) IM_FMTARGS(2); // "
IMGUI_API bool TreeNodeV(const char* str_id, const char* fmt, va_list args) IM_FMTLIST(2);
IMGUI_API bool TreeNodeV(const void* ptr_id, const char* fmt, va_list args) IM_FMTLIST(2);
IMGUI_API bool TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags = 0);
@@ -365,23 +392,23 @@ namespace ImGui
IMGUI_API bool TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3);
IMGUI_API bool TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3);
IMGUI_API bool TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3);
- IMGUI_API void TreePush(const char* str_id); // ~ Indent()+PushId(). Already called by TreeNode() when returning true, but you can call Push/Pop yourself for layout purpose
- IMGUI_API void TreePush(const void* ptr_id = NULL); // "
- IMGUI_API void TreePop(); // ~ Unindent()+PopId()
- IMGUI_API void TreeAdvanceToLabelPos(); // advance cursor x position by GetTreeNodeToLabelSpacing()
- IMGUI_API float GetTreeNodeToLabelSpacing(); // horizontal distance preceding label when using TreeNode*() or Bullet() == (g.FontSize + style.FramePadding.x*2) for a regular unframed TreeNode
- IMGUI_API void SetNextTreeNodeOpen(bool is_open, ImGuiCond cond = 0); // set next TreeNode/CollapsingHeader open state.
- IMGUI_API bool CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags = 0); // if returning 'true' the header is open. doesn't indent nor push on ID stack. user doesn't have to call TreePop().
+ IMGUI_API void TreePush(const char* str_id); // ~ Indent()+PushId(). Already called by TreeNode() when returning true, but you can call Push/Pop yourself for layout purpose
+ IMGUI_API void TreePush(const void* ptr_id = NULL); // "
+ IMGUI_API void TreePop(); // ~ Unindent()+PopId()
+ IMGUI_API void TreeAdvanceToLabelPos(); // advance cursor x position by GetTreeNodeToLabelSpacing()
+ IMGUI_API float GetTreeNodeToLabelSpacing(); // horizontal distance preceding label when using TreeNode*() or Bullet() == (g.FontSize + style.FramePadding.x*2) for a regular unframed TreeNode
+ IMGUI_API void SetNextTreeNodeOpen(bool is_open, ImGuiCond cond = 0); // set next TreeNode/CollapsingHeader open state.
+ IMGUI_API bool CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags = 0); // if returning 'true' the header is open. doesn't indent nor push on ID stack. user doesn't have to call TreePop().
IMGUI_API bool CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags = 0); // when 'p_open' isn't NULL, display an additional small close button on upper right of the header
// Widgets: Selectable / Lists
- IMGUI_API bool Selectable(const char* label, bool selected = false, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0)); // size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use label height, size.y>0.0: specify height
- IMGUI_API bool Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0));
- IMGUI_API bool ListBox(const char* label, int* current_item, const char* const* items, int items_count, int height_in_items = -1);
+ IMGUI_API bool Selectable(const char* label, bool selected = false, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0)); // "bool selected" carry the selection state (read-only). Selectable() is clicked is returns true so you can modify your selection state. size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use label height, size.y>0.0: specify height
+ IMGUI_API bool Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0)); // "bool* p_selected" point to the selection state (read-write), as a convenient helper.
+ IMGUI_API bool ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items = -1);
IMGUI_API bool ListBox(const char* label, int* current_item, bool (*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items = -1);
- IMGUI_API bool ListBoxHeader(const char* label, const ImVec2& size = ImVec2(0,0)); // use if you want to reimplement ListBox() will custom data or interactions. make sure to call ListBoxFooter() afterwards.
+ IMGUI_API bool ListBoxHeader(const char* label, const ImVec2& size = ImVec2(0,0)); // use if you want to reimplement ListBox() will custom data or interactions. make sure to call ListBoxFooter() afterwards.
IMGUI_API bool ListBoxHeader(const char* label, int items_count, int height_in_items = -1); // "
- IMGUI_API void ListBoxFooter(); // terminate the scrolling region
+ IMGUI_API void ListBoxFooter(); // terminate the scrolling region
// Widgets: Value() Helpers. Output single value in "name: value" format (tip: freely declare more in your code to handle your types. you can add functions to the ImGui namespace)
IMGUI_API void Value(const char* prefix, bool b);
@@ -396,27 +423,38 @@ namespace ImGui
IMGUI_API void EndTooltip();
// Menus
- IMGUI_API bool BeginMainMenuBar(); // create and append to a full screen menu-bar. only call EndMainMenuBar() if this returns true!
- IMGUI_API void EndMainMenuBar();
- IMGUI_API bool BeginMenuBar(); // append to menu-bar of current window (requires ImGuiWindowFlags_MenuBar flag set on parent window). only call EndMenuBar() if this returns true!
- IMGUI_API void EndMenuBar();
+ IMGUI_API bool BeginMainMenuBar(); // create and append to a full screen menu-bar.
+ IMGUI_API void EndMainMenuBar(); // only call EndMainMenuBar() if BeginMainMenuBar() returns true!
+ IMGUI_API bool BeginMenuBar(); // append to menu-bar of current window (requires ImGuiWindowFlags_MenuBar flag set on parent window).
+ IMGUI_API void EndMenuBar(); // only call EndMenuBar() if BeginMenuBar() returns true!
IMGUI_API bool BeginMenu(const char* label, bool enabled = true); // create a sub-menu entry. only call EndMenu() if this returns true!
- IMGUI_API void EndMenu();
+ IMGUI_API void EndMenu(); // only call EndMenu() if BeginMenu() returns true!
IMGUI_API bool MenuItem(const char* label, const char* shortcut = NULL, bool selected = false, bool enabled = true); // return true when activated. shortcuts are displayed for convenience but not processed by ImGui at the moment
IMGUI_API bool MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled = true); // return true when activated + toggle (*p_selected) if p_selected != NULL
// Popups
IMGUI_API void OpenPopup(const char* str_id); // call to mark popup as open (don't call every frame!). popups are closed when user click outside, or if CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. By default, Selectable()/MenuItem() are calling CloseCurrentPopup(). Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
- IMGUI_API bool OpenPopupOnItemClick(const char* str_id = NULL, int mouse_button = 1); // helper to open popup when clicked on last item. return true when just opened.
- IMGUI_API bool BeginPopup(const char* str_id); // return true if the popup is open, and you can start outputting to it. only call EndPopup() if BeginPopup() returned true!
- IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags extra_flags = 0); // modal dialog (block interactions behind the modal window, can't close the modal window by clicking outside)
+ IMGUI_API bool BeginPopup(const char* str_id, ImGuiWindowFlags flags = 0); // return true if the popup is open, and you can start outputting to it. only call EndPopup() if BeginPopup() returns true!
IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, int mouse_button = 1); // helper to open and begin popup when clicked on last item. if you can pass a NULL str_id only if the previous item had an id. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp!
IMGUI_API bool BeginPopupContextWindow(const char* str_id = NULL, int mouse_button = 1, bool also_over_items = true); // helper to open and begin popup when clicked on current window.
IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, int mouse_button = 1); // helper to open and begin popup when clicked in void (where there are no imgui windows).
- IMGUI_API void EndPopup();
+ IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // modal dialog (regular window with title bar, block interactions behind the modal window, can't close the modal window by clicking outside)
+ IMGUI_API void EndPopup(); // only call EndPopup() if BeginPopupXXX() returns true!
+ IMGUI_API bool OpenPopupOnItemClick(const char* str_id = NULL, int mouse_button = 1); // helper to open popup when clicked on last item. return true when just opened.
IMGUI_API bool IsPopupOpen(const char* str_id); // return true if the popup is open
IMGUI_API void CloseCurrentPopup(); // close the popup we have begin-ed into. clicking on a MenuItem or Selectable automatically close the current popup.
+ // Columns
+ // You can also use SameLine(pos_x) for simplified columns. The columns API is still work-in-progress and rather lacking.
+ IMGUI_API void Columns(int count = 1, const char* id = NULL, bool border = true);
+ IMGUI_API void NextColumn(); // next column, defaults to current row or next row if the current row is finished
+ IMGUI_API int GetColumnIndex(); // get current column index
+ IMGUI_API float GetColumnWidth(int column_index = -1); // get column width (in pixels). pass -1 to use current column
+ IMGUI_API void SetColumnWidth(int column_index, float width); // set column width (in pixels). pass -1 to use current column
+ IMGUI_API float GetColumnOffset(int column_index = -1); // get position of column line (in pixels, from the left side of the contents region). pass -1 to use current column, otherwise 0..GetColumnsCount() inclusive. column 0 is typically 0.0f
+ IMGUI_API void SetColumnOffset(int column_index, float offset_x); // set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column
+ IMGUI_API int GetColumnsCount();
+
// Logging/Capture: all text output from interface is captured to tty/file/clipboard. By default, tree nodes are automatically opened during logging.
IMGUI_API void LogToTTY(int max_depth = -1); // start logging to tty
IMGUI_API void LogToFile(int max_depth = -1, const char* filename = NULL); // start logging to file
@@ -427,56 +465,49 @@ namespace ImGui
// Drag and Drop
// [BETA API] Missing Demo code. API may evolve.
- IMGUI_API bool BeginDragDropSource(ImGuiDragDropFlags flags = 0, int mouse_button = 0); // call when the current item is active. If this return true, you can call SetDragDropPayload() + EndDragDropSource()
- IMGUI_API bool SetDragDropPayload(const char* type, const void* data, size_t size, ImGuiCond cond = 0);// type is a user defined string of maximum 8 characters. Strings starting with '_' are reserved for dear imgui internal types. Data is copied and held by imgui.
- IMGUI_API void EndDragDropSource();
+ IMGUI_API bool BeginDragDropSource(ImGuiDragDropFlags flags = 0); // call when the current item is active. If this return true, you can call SetDragDropPayload() + EndDragDropSource()
+ IMGUI_API bool SetDragDropPayload(const char* type, const void* data, size_t size, ImGuiCond cond = 0);// type is a user defined string of maximum 32 characters. Strings starting with '_' are reserved for dear imgui internal types. Data is copied and held by imgui.
+ IMGUI_API void EndDragDropSource(); // only call EndDragDropSource() if BeginDragDropSource() returns true!
IMGUI_API bool BeginDragDropTarget(); // call after submitting an item that may receive an item. If this returns true, you can call AcceptDragDropPayload() + EndDragDropTarget()
IMGUI_API const ImGuiPayload* AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags = 0); // accept contents of a given type. If ImGuiDragDropFlags_AcceptBeforeDelivery is set you can peek into the payload before the mouse button is released.
- IMGUI_API void EndDragDropTarget();
+ IMGUI_API void EndDragDropTarget(); // only call EndDragDropTarget() if BeginDragDropTarget() returns true!
// Clipping
IMGUI_API void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect);
IMGUI_API void PopClipRect();
- // Styles
- IMGUI_API void StyleColorsClassic(ImGuiStyle* dst = NULL);
- IMGUI_API void StyleColorsDark(ImGuiStyle* dst = NULL);
- IMGUI_API void StyleColorsLight(ImGuiStyle* dst = NULL);
-
- // Focus
- // (FIXME: Those functions will be reworked after we merge the navigation branch + have a pass at focusing/tabbing features.)
+ // Focus, Activation
// (Prefer using "SetItemDefaultFocus()" over "if (IsWindowAppearing()) SetScrollHere()" when applicable, to make your code more forward compatible when navigation branch is merged)
- IMGUI_API void SetItemDefaultFocus(); // make last item the default focused item of a window (WIP navigation branch only). Pleaase use instead of SetScrollHere().
+ IMGUI_API void SetItemDefaultFocus(); // make last item the default focused item of a window. Please use instead of "if (IsWindowAppearing()) SetScrollHere()" to signify "default item".
IMGUI_API void SetKeyboardFocusHere(int offset = 0); // focus keyboard on the next widget. Use positive 'offset' to access sub components of a multiple component widget. Use -1 to access previous widget.
// Utilities
IMGUI_API bool IsItemHovered(ImGuiHoveredFlags flags = 0); // is the last item hovered? (and usable, aka not blocked by a popup, etc.). See ImGuiHoveredFlags for more options.
IMGUI_API bool IsItemActive(); // is the last item active? (e.g. button being held, text field being edited- items that don't interact will always return false)
+ IMGUI_API bool IsItemFocused(); // is the last item focused for keyboard/gamepad navigation?
IMGUI_API bool IsItemClicked(int mouse_button = 0); // is the last item clicked? (e.g. button/node just clicked on)
IMGUI_API bool IsItemVisible(); // is the last item visible? (aka not out of sight due to clipping/scrolling.)
IMGUI_API bool IsAnyItemHovered();
IMGUI_API bool IsAnyItemActive();
+ IMGUI_API bool IsAnyItemFocused();
IMGUI_API ImVec2 GetItemRectMin(); // get bounding rectangle of last item, in screen space
IMGUI_API ImVec2 GetItemRectMax(); // "
IMGUI_API ImVec2 GetItemRectSize(); // get size of last item, in screen space
IMGUI_API void SetItemAllowOverlap(); // allow last item to be overlapped by a subsequent item. sometimes useful with invisible buttons, selectables, etc. to catch unused area.
- IMGUI_API bool IsWindowFocused(ImGuiFocusedFlags flags = 0); // is current window focused? or its root/child, depending on flags. see flags for options.
- IMGUI_API bool IsWindowHovered(ImGuiHoveredFlags flags = 0); // is current window hovered (and typically: not blocked by a popup/modal)? see flags for options.
- IMGUI_API bool IsAnyWindowFocused();
- IMGUI_API bool IsAnyWindowHovered(); // is mouse hovering any visible window
IMGUI_API bool IsRectVisible(const ImVec2& size); // test if rectangle (of given size, starting from cursor position) is visible / not clipped.
IMGUI_API bool IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max); // test if rectangle (in screen space) is visible / not clipped. to perform coarse clipping on user's side.
IMGUI_API float GetTime();
IMGUI_API int GetFrameCount();
IMGUI_API ImDrawList* GetOverlayDrawList(); // this draw list will be the last rendered one, useful to quickly draw overlays shapes/text
- IMGUI_API ImDrawListSharedData* GetDrawListSharedData();
+ IMGUI_API ImDrawListSharedData* GetDrawListSharedData(); // you may use this when creating your own ImDrawList instances
IMGUI_API const char* GetStyleColorName(ImGuiCol idx);
- IMGUI_API ImVec2 CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge = false, float outward = +0.0f); // utility to find the closest point the last item bounding rectangle edge. useful to visually link items
+ IMGUI_API void SetStateStorage(ImGuiStorage* storage); // replace current window storage with our own (if you want to manipulate it yourself, typically clear subsection of it)
+ IMGUI_API ImGuiStorage* GetStateStorage();
IMGUI_API ImVec2 CalcTextSize(const char* text, const char* text_end = NULL, bool hide_text_after_double_hash = false, float wrap_width = -1.0f);
IMGUI_API void CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end); // calculate coarse clipping for large list of evenly sized items. Prefer using the ImGuiListClipper higher-level helper if you can.
- IMGUI_API bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags = 0); // helper to create a child window / scrolling region that looks like a normal widget frame
- IMGUI_API void EndChildFrame();
+ IMGUI_API bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags flags = 0); // helper to create a child window / scrolling region that looks like a normal widget frame
+ IMGUI_API void EndChildFrame(); // always call EndChildFrame() regardless of BeginChildFrame() return values (which indicates a collapsed/clipped window)
IMGUI_API ImVec4 ColorConvertU32ToFloat4(ImU32 in);
IMGUI_API ImU32 ColorConvertFloat4ToU32(const ImVec4& in);
@@ -490,6 +521,7 @@ namespace ImGui
IMGUI_API bool IsKeyReleased(int user_key_index); // was key released (went from Down to !Down)..
IMGUI_API int GetKeyPressedAmount(int key_index, float repeat_delay, float rate); // uses provided repeat rate/delay. return a count, most often 0 or 1 but might be >1 if RepeatRate is small enough that DeltaTime > RepeatRate
IMGUI_API bool IsMouseDown(int button); // is mouse button held
+ IMGUI_API bool IsAnyMouseDown(); // is any mouse button held
IMGUI_API bool IsMouseClicked(int button, bool repeat = false); // did mouse button clicked (went from !Down to Down)
IMGUI_API bool IsMouseDoubleClicked(int button); // did mouse button double-clicked. a double-click returns false in IsMouseClicked(). uses io.MouseDoubleClickTime.
IMGUI_API bool IsMouseReleased(int button); // did mouse button released (went from Down to !Down)
@@ -497,27 +529,24 @@ namespace ImGui
IMGUI_API bool IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip = true); // is mouse hovering given bounding rect (in screen space). clipped by current clipping settings. disregarding of consideration of focus/window ordering/blocked by a popup.
IMGUI_API bool IsMousePosValid(const ImVec2* mouse_pos = NULL); //
IMGUI_API ImVec2 GetMousePos(); // shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls
- IMGUI_API ImVec2 GetMousePosOnOpeningCurrentPopup(); // retrieve backup of mouse positioning at the time of opening popup we have BeginPopup() into
+ IMGUI_API ImVec2 GetMousePosOnOpeningCurrentPopup(); // retrieve backup of mouse position at the time of opening popup we have BeginPopup() into
IMGUI_API ImVec2 GetMouseDragDelta(int button = 0, float lock_threshold = -1.0f); // dragging amount since clicking. if lock_threshold < -1.0f uses io.MouseDraggingThreshold
IMGUI_API void ResetMouseDragDelta(int button = 0); //
IMGUI_API ImGuiMouseCursor GetMouseCursor(); // get desired cursor type, reset in ImGui::NewFrame(), this is updated during the frame. valid before Render(). If you use software rendering by setting io.MouseDrawCursor ImGui will render those for you
IMGUI_API void SetMouseCursor(ImGuiMouseCursor type); // set desired cursor type
- IMGUI_API void CaptureKeyboardFromApp(bool capture = true); // manually override io.WantCaptureKeyboard flag next frame (said flag is entirely left for your application handle). e.g. force capture keyboard when your widget is being hovered.
- IMGUI_API void CaptureMouseFromApp(bool capture = true); // manually override io.WantCaptureMouse flag next frame (said flag is entirely left for your application handle).
+ IMGUI_API void CaptureKeyboardFromApp(bool capture = true); // manually override io.WantCaptureKeyboard flag next frame (said flag is entirely left for your application to handle). e.g. force capture keyboard when your widget is being hovered.
+ IMGUI_API void CaptureMouseFromApp(bool capture = true); // manually override io.WantCaptureMouse flag next frame (said flag is entirely left for your application to handle).
- // Helpers functions to access functions pointers in ImGui::GetIO()
- IMGUI_API void* MemAlloc(size_t sz);
- IMGUI_API void MemFree(void* ptr);
+ // Clipboard Utilities (also see the LogToClipboard() function to capture or output text data to the clipboard)
IMGUI_API const char* GetClipboardText();
IMGUI_API void SetClipboardText(const char* text);
- // Internal context access - if you want to use multiple context, share context between modules (e.g. DLL). There is a default context created and active by default.
- // All contexts share a same ImFontAtlas by default. If you want different font atlas, you can new() them and overwrite the GetIO().Fonts variable of an ImGui context.
- IMGUI_API const char* GetVersion();
- IMGUI_API ImGuiContext* CreateContext(void* (*malloc_fn)(size_t) = NULL, void (*free_fn)(void*) = NULL);
- IMGUI_API void DestroyContext(ImGuiContext* ctx);
- IMGUI_API ImGuiContext* GetCurrentContext();
- IMGUI_API void SetCurrentContext(ImGuiContext* ctx);
+ // Memory Utilities
+ // All those functions are not reliant on the current context.
+ // If you reload the contents of imgui.cpp at runtime, you may need to call SetCurrentContext() + SetAllocatorFunctions() again.
+ IMGUI_API void SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void(*free_func)(void* ptr, void* user_data), void* user_data = NULL);
+ IMGUI_API void* MemAlloc(size_t size);
+ IMGUI_API void MemFree(void* ptr);
} // namespace ImGui
@@ -541,9 +570,13 @@ enum ImGuiWindowFlags_
ImGuiWindowFlags_AlwaysVerticalScrollbar= 1 << 14, // Always show vertical scrollbar (even if ContentSize.y < Size.y)
ImGuiWindowFlags_AlwaysHorizontalScrollbar=1<< 15, // Always show horizontal scrollbar (even if ContentSize.x < Size.x)
ImGuiWindowFlags_AlwaysUseWindowPadding = 1 << 16, // Ensure child windows without border uses style.WindowPadding (ignored by default for non-bordered child windows, because more convenient)
- ImGuiWindowFlags_ResizeFromAnySide = 1 << 17, // (WIP) Enable resize from any corners and borders. Your back-end needs to honor the different values of io.MouseCursor set by imgui.
+ ImGuiWindowFlags_ResizeFromAnySide = 1 << 17, // [BETA] Enable resize from any corners and borders. Your back-end needs to honor the different values of io.MouseCursor set by imgui.
+ ImGuiWindowFlags_NoNavInputs = 1 << 18, // No gamepad/keyboard navigation within the window
+ ImGuiWindowFlags_NoNavFocus = 1 << 19, // No focusing toward this window with gamepad/keyboard navigation (e.g. skipped by CTRL+TAB)
+ ImGuiWindowFlags_NoNav = ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus,
// [Internal]
+ ImGuiWindowFlags_NavFlattened = 1 << 23, // [BETA] Allow gamepad/keyboard navigation to cross over parent border to this child (only use on child that have no scrolling!)
ImGuiWindowFlags_ChildWindow = 1 << 24, // Don't use! For internal use by BeginChild()
ImGuiWindowFlags_Tooltip = 1 << 25, // Don't use! For internal use by BeginTooltip()
ImGuiWindowFlags_Popup = 1 << 26, // Don't use! For internal use by BeginPopup()
@@ -571,6 +604,7 @@ enum ImGuiInputTextFlags_
ImGuiInputTextFlags_ReadOnly = 1 << 14, // Read-only mode
ImGuiInputTextFlags_Password = 1 << 15, // Password mode, display all characters as '*'
ImGuiInputTextFlags_NoUndoRedo = 1 << 16, // Disable undo/redo. Note that input text owns the text data while active, if you want to provide your own undo/redo stack you need e.g. to call ClearActiveID().
+ ImGuiInputTextFlags_CharsScientific = 1 << 17, // Allow 0123456789.+-*/eE (Scientific notation input)
// [Internal]
ImGuiInputTextFlags_Multiline = 1 << 20 // For internal use by InputTextMultiline()
};
@@ -591,6 +625,7 @@ enum ImGuiTreeNodeFlags_
ImGuiTreeNodeFlags_FramePadding = 1 << 10, // Use FramePadding (even for an unframed text node) to vertically align text baseline to regular widget height. Equivalent to calling AlignTextToFramePadding().
//ImGuITreeNodeFlags_SpanAllAvailWidth = 1 << 11, // FIXME: TODO: Extend hit box horizontally even if not framed
//ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 12, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible
+ ImGuiTreeNodeFlags_NavLeftJumpsBackHere = 1 << 13, // (WIP) Nav: left direction may move to this TreeNode() from any of its child (items submitted between TreeNode and TreePop)
ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoAutoOpenOnLog
// Obsolete names (will be removed)
@@ -615,6 +650,8 @@ enum ImGuiComboFlags_
ImGuiComboFlags_HeightRegular = 1 << 2, // Max ~8 items visible (default)
ImGuiComboFlags_HeightLarge = 1 << 3, // Max ~20 items visible
ImGuiComboFlags_HeightLargest = 1 << 4, // As many fitting items as possible
+ ImGuiComboFlags_NoArrowButton = 1 << 5, // Display on the preview box without the square arrow button
+ ImGuiComboFlags_NoPreview = 1 << 6, // Display only a square arrow button
ImGuiComboFlags_HeightMask_ = ImGuiComboFlags_HeightSmall | ImGuiComboFlags_HeightRegular | ImGuiComboFlags_HeightLarge | ImGuiComboFlags_HeightLargest
};
@@ -623,19 +660,22 @@ enum ImGuiFocusedFlags_
{
ImGuiFocusedFlags_ChildWindows = 1 << 0, // IsWindowFocused(): Return true if any children of the window is focused
ImGuiFocusedFlags_RootWindow = 1 << 1, // IsWindowFocused(): Test from root window (top most parent of the current hierarchy)
+ ImGuiFocusedFlags_AnyWindow = 1 << 2, // IsWindowFocused(): Return true if any window is focused
ImGuiFocusedFlags_RootAndChildWindows = ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows
};
// Flags for ImGui::IsItemHovered(), ImGui::IsWindowHovered()
+// Note: If you are trying to check whether your mouse should be dispatched to imgui or to your app, you should use the 'io.WantCaptureMouse' boolean for that. Please read the FAQ!
enum ImGuiHoveredFlags_
{
ImGuiHoveredFlags_Default = 0, // Return true if directly over the item/window, not obstructed by another window, not obstructed by an active popup or modal blocking inputs under them.
ImGuiHoveredFlags_ChildWindows = 1 << 0, // IsWindowHovered() only: Return true if any children of the window is hovered
ImGuiHoveredFlags_RootWindow = 1 << 1, // IsWindowHovered() only: Test from root window (top most parent of the current hierarchy)
- ImGuiHoveredFlags_AllowWhenBlockedByPopup = 1 << 2, // Return true even if a popup window is normally blocking access to this item/window
- //ImGuiHoveredFlags_AllowWhenBlockedByModal = 1 << 3, // Return true even if a modal popup window is normally blocking access to this item/window. FIXME-TODO: Unavailable yet.
- ImGuiHoveredFlags_AllowWhenBlockedByActiveItem = 1 << 4, // Return true even if an active item is blocking access to this item/window. Useful for Drag and Drop patterns.
- ImGuiHoveredFlags_AllowWhenOverlapped = 1 << 5, // Return true even if the position is overlapped by another window
+ ImGuiHoveredFlags_AnyWindow = 1 << 2, // IsWindowHovered() only: Return true if any window is hovered
+ ImGuiHoveredFlags_AllowWhenBlockedByPopup = 1 << 3, // Return true even if a popup window is normally blocking access to this item/window
+ //ImGuiHoveredFlags_AllowWhenBlockedByModal = 1 << 4, // Return true even if a modal popup window is normally blocking access to this item/window. FIXME-TODO: Unavailable yet.
+ ImGuiHoveredFlags_AllowWhenBlockedByActiveItem = 1 << 5, // Return true even if an active item is blocking access to this item/window. Useful for Drag and Drop patterns.
+ ImGuiHoveredFlags_AllowWhenOverlapped = 1 << 6, // Return true even if the position is overlapped by another window
ImGuiHoveredFlags_RectOnly = ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenOverlapped,
ImGuiHoveredFlags_RootAndChildWindows = ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows
};
@@ -644,37 +684,50 @@ enum ImGuiHoveredFlags_
enum ImGuiDragDropFlags_
{
// BeginDragDropSource() flags
- ImGuiDragDropFlags_SourceNoPreviewTooltip = 1 << 0, // By default, a successful call to BeginDragDropSource opens a tooltip so you can display a preview or description of the source contents. This flag disable this behavior.
- ImGuiDragDropFlags_SourceNoDisableHover = 1 << 1, // By default, when dragging we clear data so that IsItemHovered() will return true, to avoid subsequent user code submitting tooltips. This flag disable this behavior so you can still call IsItemHovered() on the source item.
- ImGuiDragDropFlags_SourceNoHoldToOpenOthers = 1 << 2, // Disable the behavior that allows to open tree nodes and collapsing header by holding over them while dragging a source item.
- ImGuiDragDropFlags_SourceAllowNullID = 1 << 3, // Allow items such as Text(), Image() that have no unique identifier to be used as drag source, by manufacturing a temporary identifier based on their window-relative position. This is extremely unusual within the dear imgui ecosystem and so we made it explicit.
- ImGuiDragDropFlags_SourceExtern = 1 << 4, // External source (from outside of imgui), won't attempt to read current item/window info. Will always return true. Only one Extern source can be active simultaneously.
+ ImGuiDragDropFlags_SourceNoPreviewTooltip = 1 << 0, // By default, a successful call to BeginDragDropSource opens a tooltip so you can display a preview or description of the source contents. This flag disable this behavior.
+ ImGuiDragDropFlags_SourceNoDisableHover = 1 << 1, // By default, when dragging we clear data so that IsItemHovered() will return true, to avoid subsequent user code submitting tooltips. This flag disable this behavior so you can still call IsItemHovered() on the source item.
+ ImGuiDragDropFlags_SourceNoHoldToOpenOthers = 1 << 2, // Disable the behavior that allows to open tree nodes and collapsing header by holding over them while dragging a source item.
+ ImGuiDragDropFlags_SourceAllowNullID = 1 << 3, // Allow items such as Text(), Image() that have no unique identifier to be used as drag source, by manufacturing a temporary identifier based on their window-relative position. This is extremely unusual within the dear imgui ecosystem and so we made it explicit.
+ ImGuiDragDropFlags_SourceExtern = 1 << 4, // External source (from outside of imgui), won't attempt to read current item/window info. Will always return true. Only one Extern source can be active simultaneously.
// AcceptDragDropPayload() flags
- ImGuiDragDropFlags_AcceptBeforeDelivery = 1 << 10, // AcceptDragDropPayload() will returns true even before the mouse button is released. You can then call IsDelivery() to test if the payload needs to be delivered.
- ImGuiDragDropFlags_AcceptNoDrawDefaultRect = 1 << 11, // Do not draw the default highlight rectangle when hovering over target.
+ ImGuiDragDropFlags_AcceptBeforeDelivery = 1 << 10, // AcceptDragDropPayload() will returns true even before the mouse button is released. You can then call IsDelivery() to test if the payload needs to be delivered.
+ ImGuiDragDropFlags_AcceptNoDrawDefaultRect = 1 << 11, // Do not draw the default highlight rectangle when hovering over target.
ImGuiDragDropFlags_AcceptPeekOnly = ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect // For peeking ahead and inspecting the payload before delivery.
};
-// Standard Drag and Drop payload types. You can define you own payload types using 8-characters long strings. Types starting with '_' are defined by Dear ImGui.
-#define IMGUI_PAYLOAD_TYPE_COLOR_3F "_COL3F" // float[3] // Standard type for colors, without alpha. User code may use this type.
-#define IMGUI_PAYLOAD_TYPE_COLOR_4F "_COL4F" // float[4] // Standard type for colors. User code may use this type.
+// Standard Drag and Drop payload types. You can define you own payload types using 12-characters long strings. Types starting with '_' are defined by Dear ImGui.
+#define IMGUI_PAYLOAD_TYPE_COLOR_3F "_COL3F" // float[3]: Standard type for colors, without alpha. User code may use this type.
+#define IMGUI_PAYLOAD_TYPE_COLOR_4F "_COL4F" // float[4]: Standard type for colors. User code may use this type.
+
+// A cardinal direction
+enum ImGuiDir_
+{
+ ImGuiDir_None = -1,
+ ImGuiDir_Left = 0,
+ ImGuiDir_Right = 1,
+ ImGuiDir_Up = 2,
+ ImGuiDir_Down = 3,
+ ImGuiDir_COUNT
+};
// User fill ImGuiIO.KeyMap[] array with indices into the ImGuiIO.KeysDown[512] array
enum ImGuiKey_
{
- ImGuiKey_Tab, // for tabbing through fields
- ImGuiKey_LeftArrow, // for text edit
- ImGuiKey_RightArrow,// for text edit
- ImGuiKey_UpArrow, // for text edit
- ImGuiKey_DownArrow, // for text edit
+ ImGuiKey_Tab,
+ ImGuiKey_LeftArrow,
+ ImGuiKey_RightArrow,
+ ImGuiKey_UpArrow,
+ ImGuiKey_DownArrow,
ImGuiKey_PageUp,
ImGuiKey_PageDown,
- ImGuiKey_Home, // for text edit
- ImGuiKey_End, // for text edit
- ImGuiKey_Delete, // for text edit
- ImGuiKey_Backspace, // for text edit
- ImGuiKey_Enter, // for text edit
- ImGuiKey_Escape, // for text edit
+ ImGuiKey_Home,
+ ImGuiKey_End,
+ ImGuiKey_Insert,
+ ImGuiKey_Delete,
+ ImGuiKey_Backspace,
+ ImGuiKey_Space,
+ ImGuiKey_Enter,
+ ImGuiKey_Escape,
ImGuiKey_A, // for text edit CTRL+A: select all
ImGuiKey_C, // for text edit CTRL+C: copy
ImGuiKey_V, // for text edit CTRL+V: paste
@@ -684,6 +737,64 @@ enum ImGuiKey_
ImGuiKey_COUNT
};
+// [BETA] Gamepad/Keyboard directional navigation
+// Keyboard: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable. NewFrame() will automatically fill io.NavInputs[] based on your io.KeyDown[] + io.KeyMap[] arrays.
+// Gamepad: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable. Back-end: set ImGuiBackendFlags_HasGamepad and fill the io.NavInputs[] fields before calling NewFrame(). Note that io.NavInputs[] is cleared by EndFrame().
+// Read instructions in imgui.cpp for more details. Download PNG/PSD at goo.gl/9LgVZW.
+enum ImGuiNavInput_
+{
+ // Gamepad Mapping
+ ImGuiNavInput_Activate, // activate / open / toggle / tweak value // e.g. Cross (PS4), A (Xbox), A (Switch), Space (Keyboard)
+ ImGuiNavInput_Cancel, // cancel / close / exit // e.g. Circle (PS4), B (Xbox), B (Switch), Escape (Keyboard)
+ ImGuiNavInput_Input, // text input / on-screen keyboard // e.g. Triang.(PS4), Y (Xbox), X (Switch), Return (Keyboard)
+ ImGuiNavInput_Menu, // tap: toggle menu / hold: focus, move, resize // e.g. Square (PS4), X (Xbox), Y (Switch), Alt (Keyboard)
+ ImGuiNavInput_DpadLeft, // move / tweak / resize window (w/ PadMenu) // e.g. D-pad Left/Right/Up/Down (Gamepads), Arrow keys (Keyboard)
+ ImGuiNavInput_DpadRight, //
+ ImGuiNavInput_DpadUp, //
+ ImGuiNavInput_DpadDown, //
+ ImGuiNavInput_LStickLeft, // scroll / move window (w/ PadMenu) // e.g. Left Analog Stick Left/Right/Up/Down
+ ImGuiNavInput_LStickRight, //
+ ImGuiNavInput_LStickUp, //
+ ImGuiNavInput_LStickDown, //
+ ImGuiNavInput_FocusPrev, // next window (w/ PadMenu) // e.g. L1 or L2 (PS4), LB or LT (Xbox), L or ZL (Switch)
+ ImGuiNavInput_FocusNext, // prev window (w/ PadMenu) // e.g. R1 or R2 (PS4), RB or RT (Xbox), R or ZL (Switch)
+ ImGuiNavInput_TweakSlow, // slower tweaks // e.g. L1 or L2 (PS4), LB or LT (Xbox), L or ZL (Switch)
+ ImGuiNavInput_TweakFast, // faster tweaks // e.g. R1 or R2 (PS4), RB or RT (Xbox), R or ZL (Switch)
+
+ // [Internal] Don't use directly! This is used internally to differentiate keyboard from gamepad inputs for behaviors that require to differentiate them.
+ // Keyboard behavior that have no corresponding gamepad mapping (e.g. CTRL+TAB) will be directly reading from io.KeyDown[] instead of io.NavInputs[].
+ ImGuiNavInput_KeyMenu_, // toggle menu // = io.KeyAlt
+ ImGuiNavInput_KeyLeft_, // move left // = Arrow keys
+ ImGuiNavInput_KeyRight_, // move right
+ ImGuiNavInput_KeyUp_, // move up
+ ImGuiNavInput_KeyDown_, // move down
+ ImGuiNavInput_COUNT,
+ ImGuiNavInput_InternalStart_ = ImGuiNavInput_KeyMenu_
+};
+
+// Configuration flags stored in io.ConfigFlags. Set by user/application.
+enum ImGuiConfigFlags_
+{
+ ImGuiConfigFlags_NavEnableKeyboard = 1 << 0, // Master keyboard navigation enable flag. NewFrame() will automatically fill io.NavInputs[] based on io.KeyDown[].
+ ImGuiConfigFlags_NavEnableGamepad = 1 << 1, // Master gamepad navigation enable flag. This is mostly to instruct your imgui back-end to fill io.NavInputs[]. Back-end also needs to set ImGuiBackendFlags_HasGamepad.
+ ImGuiConfigFlags_NavEnableSetMousePos = 1 << 2, // Instruct navigation to move the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is awkward. Will update io.MousePos and set io.WantSetMousePos=true. If enabled you MUST honor io.WantSetMousePos requests in your binding, otherwise ImGui will react as if the mouse is jumping around back and forth.
+ ImGuiConfigFlags_NavNoCaptureKeyboard = 1 << 3, // Instruct navigation to not set the io.WantCaptureKeyboard flag with io.NavActive is set.
+ ImGuiConfigFlags_NoMouse = 1 << 4, // Instruct imgui to clear mouse position/buttons in NewFrame(). This allows ignoring the mouse information back-end
+ ImGuiConfigFlags_NoMouseCursorChange = 1 << 5, // Instruct back-end to not alter mouse cursor shape and visibility.
+
+ // User storage (to allow your back-end/engine to communicate to code that may be shared between multiple projects. Those flags are not used by core ImGui)
+ ImGuiConfigFlags_IsSRGB = 1 << 20, // Application is SRGB-aware.
+ ImGuiConfigFlags_IsTouchScreen = 1 << 21 // Application is using a touch screen instead of a mouse.
+};
+
+// Back-end capabilities flags stored in io.BackendFlags. Set by imgui_impl_xxx or custom back-end.
+enum ImGuiBackendFlags_
+{
+ ImGuiBackendFlags_HasGamepad = 1 << 0, // Back-end has a connected gamepad.
+ ImGuiBackendFlags_HasMouseCursors = 1 << 1, // Back-end can honor GetMouseCursor() values and change the OS cursor shape.
+ ImGuiBackendFlags_HasSetMousePos = 1 << 2 // Back-end can honor io.WantSetMousePos and reposition the mouse (only used if ImGuiConfigFlags_NavEnableSetMousePos is set).
+};
+
// Enumeration for PushStyleColor() / PopStyleColor()
enum ImGuiCol_
{
@@ -720,22 +831,22 @@ enum ImGuiCol_
ImGuiCol_ResizeGrip,
ImGuiCol_ResizeGripHovered,
ImGuiCol_ResizeGripActive,
- ImGuiCol_CloseButton,
- ImGuiCol_CloseButtonHovered,
- ImGuiCol_CloseButtonActive,
ImGuiCol_PlotLines,
ImGuiCol_PlotLinesHovered,
ImGuiCol_PlotHistogram,
ImGuiCol_PlotHistogramHovered,
ImGuiCol_TextSelectedBg,
- ImGuiCol_ModalWindowDarkening, // darken entire screen when a modal window is active
+ ImGuiCol_ModalWindowDarkening, // darken/colorize entire screen behind a modal window, when one is active
ImGuiCol_DragDropTarget,
+ ImGuiCol_NavHighlight, // gamepad/keyboard: current highlighted item
+ ImGuiCol_NavWindowingHighlight, // gamepad/keyboard: when holding NavMenu to focus/move/resize windows
ImGuiCol_COUNT
// Obsolete names (will be removed)
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
- //, ImGuiCol_ComboBg = ImGuiCol_PopupBg // ComboBg has been merged with PopupBg, so a redirect isn't accurate.
, ImGuiCol_ChildWindowBg = ImGuiCol_ChildBg, ImGuiCol_Column = ImGuiCol_Separator, ImGuiCol_ColumnHovered = ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive = ImGuiCol_SeparatorActive
+ //ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered, // [unused since 1.60+] the close button now uses regular button colors.
+ //ImGuiCol_ComboBg, // [unused since 1.53+] ComboBg has been merged with PopupBg, so a redirect isn't accurate.
#endif
};
@@ -750,6 +861,7 @@ enum ImGuiStyleVar_
ImGuiStyleVar_WindowRounding, // float WindowRounding
ImGuiStyleVar_WindowBorderSize, // float WindowBorderSize
ImGuiStyleVar_WindowMinSize, // ImVec2 WindowMinSize
+ ImGuiStyleVar_WindowTitleAlign, // ImVec2 WindowTitleAlign
ImGuiStyleVar_ChildRounding, // float ChildRounding
ImGuiStyleVar_ChildBorderSize, // float ChildBorderSize
ImGuiStyleVar_PopupRounding, // float PopupRounding
@@ -760,13 +872,16 @@ enum ImGuiStyleVar_
ImGuiStyleVar_ItemSpacing, // ImVec2 ItemSpacing
ImGuiStyleVar_ItemInnerSpacing, // ImVec2 ItemInnerSpacing
ImGuiStyleVar_IndentSpacing, // float IndentSpacing
+ ImGuiStyleVar_ScrollbarSize, // float ScrollbarSize
+ ImGuiStyleVar_ScrollbarRounding, // float ScrollbarRounding
ImGuiStyleVar_GrabMinSize, // float GrabMinSize
+ ImGuiStyleVar_GrabRounding, // float GrabRounding
ImGuiStyleVar_ButtonTextAlign, // ImVec2 ButtonTextAlign
- ImGuiStyleVar_Count_
+ ImGuiStyleVar_COUNT
// Obsolete names (will be removed)
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
- , ImGuiStyleVar_ChildWindowRounding = ImGuiStyleVar_ChildRounding
+ , ImGuiStyleVar_Count_ = ImGuiStyleVar_COUNT, ImGuiStyleVar_ChildWindowRounding = ImGuiStyleVar_ChildRounding
#endif
};
@@ -781,6 +896,7 @@ enum ImGuiColorEditFlags_
ImGuiColorEditFlags_NoTooltip = 1 << 6, // // ColorEdit, ColorPicker, ColorButton: disable tooltip when hovering the preview.
ImGuiColorEditFlags_NoLabel = 1 << 7, // // ColorEdit, ColorPicker: disable display of inline text label (the label is still forwarded to the tooltip and picker).
ImGuiColorEditFlags_NoSidePreview = 1 << 8, // // ColorPicker: disable bigger color preview on right side of the picker, use small colored square preview instead.
+
// User Options (right-click on widget to change some of them). You can set application defaults using SetColorEditOptions(). The idea is that you probably don't want to override them in most of your calls, let the user choose and/or call SetColorEditOptions() during startup.
ImGuiColorEditFlags_AlphaBar = 1 << 9, // // ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker.
ImGuiColorEditFlags_AlphaPreview = 1 << 10, // // ColorEdit, ColorPicker, ColorButton: display preview as a transparent color over a checkerboard, instead of opaque.
@@ -793,7 +909,8 @@ enum ImGuiColorEditFlags_
ImGuiColorEditFlags_Float = 1 << 17, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0.0f..1.0f floats instead of 0..255 integers. No round-trip of value via integers.
ImGuiColorEditFlags_PickerHueBar = 1 << 18, // [PickerMode] // ColorPicker: bar for Hue, rectangle for Sat/Value.
ImGuiColorEditFlags_PickerHueWheel = 1 << 19, // [PickerMode] // ColorPicker: wheel for Hue, triangle for Sat/Value.
- // Internals/Masks
+
+ // [Internal] Masks
ImGuiColorEditFlags__InputsMask = ImGuiColorEditFlags_RGB|ImGuiColorEditFlags_HSV|ImGuiColorEditFlags_HEX,
ImGuiColorEditFlags__DataTypeMask = ImGuiColorEditFlags_Uint8|ImGuiColorEditFlags_Float,
ImGuiColorEditFlags__PickerMask = ImGuiColorEditFlags_PickerHueWheel|ImGuiColorEditFlags_PickerHueBar,
@@ -801,27 +918,33 @@ enum ImGuiColorEditFlags_
};
// Enumeration for GetMouseCursor()
+// User code may request binding to display given cursor by calling SetMouseCursor(), which is why we have some cursors that are marked unused here
enum ImGuiMouseCursor_
{
ImGuiMouseCursor_None = -1,
ImGuiMouseCursor_Arrow = 0,
ImGuiMouseCursor_TextInput, // When hovering over InputText, etc.
- ImGuiMouseCursor_Move, // Unused
+ ImGuiMouseCursor_ResizeAll, // Unused by imgui functions
ImGuiMouseCursor_ResizeNS, // When hovering over an horizontal border
ImGuiMouseCursor_ResizeEW, // When hovering over a vertical border or a column
ImGuiMouseCursor_ResizeNESW, // When hovering over the bottom-left corner of a window
ImGuiMouseCursor_ResizeNWSE, // When hovering over the bottom-right corner of a window
- ImGuiMouseCursor_Count_
+ ImGuiMouseCursor_COUNT
+
+ // Obsolete names (will be removed)
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ , ImGuiMouseCursor_Count_ = ImGuiMouseCursor_COUNT
+#endif
};
// Condition for ImGui::SetWindow***(), SetNextWindow***(), SetNextTreeNode***() functions
-// All those functions treat 0 as a shortcut to ImGuiCond_Always. From the point of view of the user use this as an enum (don't combine multiple values into flags).
+// Important: Treat as a regular enum! Do NOT combine multiple values using binary operators! All the functions above treat 0 as a shortcut to ImGuiCond_Always.
enum ImGuiCond_
{
ImGuiCond_Always = 1 << 0, // Set the variable
ImGuiCond_Once = 1 << 1, // Set the variable once per runtime session (only the first call with succeed)
- ImGuiCond_FirstUseEver = 1 << 2, // Set the variable if the window has no saved data (if doesn't exist in the .ini file)
- ImGuiCond_Appearing = 1 << 3 // Set the variable if the window is appearing after being hidden/inactive (or the first time)
+ ImGuiCond_FirstUseEver = 1 << 2, // Set the variable if the object/window has no persistently saved data (no entry in .ini file)
+ ImGuiCond_Appearing = 1 << 3 // Set the variable if the object/window is appearing after being hidden/inactive (or the first time)
// Obsolete names (will be removed)
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
@@ -829,33 +952,36 @@ enum ImGuiCond_
#endif
};
+// You may modify the ImGui::GetStyle() main instance during initialization and before NewFrame().
+// During the frame, use ImGui::PushStyleVar(ImGuiStyleVar_XXXX)/PopStyleVar() to alter the main style values, and ImGui::PushStyleColor(ImGuiCol_XXX)/PopStyleColor() for colors.
struct ImGuiStyle
{
- float Alpha; // Global alpha applies to everything in ImGui
- ImVec2 WindowPadding; // Padding within a window
- float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows
- float WindowBorderSize; // Thickness of border around windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly)
- ImVec2 WindowMinSize; // Minimum window size
+ float Alpha; // Global alpha applies to everything in ImGui.
+ ImVec2 WindowPadding; // Padding within a window.
+ float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows.
+ float WindowBorderSize; // Thickness of border around windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).
+ ImVec2 WindowMinSize; // Minimum window size. This is a global setting. If you want to constraint individual windows, use SetNextWindowSizeConstraints().
ImVec2 WindowTitleAlign; // Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically centered.
float ChildRounding; // Radius of child window corners rounding. Set to 0.0f to have rectangular windows.
- float ChildBorderSize; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly)
- float PopupRounding; // Radius of popup window corners rounding.
- float PopupBorderSize; // Thickness of border around popup windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly)
- ImVec2 FramePadding; // Padding within a framed rectangle (used by most widgets)
+ float ChildBorderSize; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).
+ float PopupRounding; // Radius of popup window corners rounding. (Note that tooltip windows use WindowRounding)
+ float PopupBorderSize; // Thickness of border around popup/tooltip windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).
+ ImVec2 FramePadding; // Padding within a framed rectangle (used by most widgets).
float FrameRounding; // Radius of frame corners rounding. Set to 0.0f to have rectangular frame (used by most widgets).
- float FrameBorderSize; // Thickness of border around frames. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly)
- ImVec2 ItemSpacing; // Horizontal and vertical spacing between widgets/lines
- ImVec2 ItemInnerSpacing; // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
+ float FrameBorderSize; // Thickness of border around frames. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).
+ ImVec2 ItemSpacing; // Horizontal and vertical spacing between widgets/lines.
+ ImVec2 ItemInnerSpacing; // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label).
ImVec2 TouchExtraPadding; // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
float IndentSpacing; // Horizontal indentation when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
- float ColumnsMinSpacing; // Minimum horizontal spacing between two columns
- float ScrollbarSize; // Width of the vertical scrollbar, Height of the horizontal scrollbar
- float ScrollbarRounding; // Radius of grab corners for scrollbar
+ float ColumnsMinSpacing; // Minimum horizontal spacing between two columns.
+ float ScrollbarSize; // Width of the vertical scrollbar, Height of the horizontal scrollbar.
+ float ScrollbarRounding; // Radius of grab corners for scrollbar.
float GrabMinSize; // Minimum width/height of a grab box for slider/scrollbar.
float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f,0.5f) for horizontally+vertically centered.
ImVec2 DisplayWindowPadding; // Window positions are clamped to be visible within the display area by at least this amount. Only covers regular windows.
ImVec2 DisplaySafeAreaPadding; // 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.
+ float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
bool AntiAliasedLines; // Enable anti-aliasing on lines/borders. Disable if you are really tight on CPU/GPU.
bool AntiAliasedFill; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.)
float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
@@ -873,6 +999,8 @@ struct ImGuiIO
// Settings (fill once) // Default value:
//------------------------------------------------------------------
+ ImGuiConfigFlags ConfigFlags; // = 0 // See ImGuiConfigFlags_ enum. Set by user/application. Gamepad/keyboard navigation options, etc.
+ ImGuiBackendFlags BackendFlags; // = 0 // Set ImGuiBackendFlags_ enum. Set by imgui_impl_xxx files or custom back-end.
ImVec2 DisplaySize; // <unset> // Display size, in pixels. For clamping windows positions.
float DeltaTime; // = 1.0f/60.0f // Time elapsed since last frame, in seconds.
float IniSavingRate; // = 5.0f // Maximum time between saving positions/sizes to .ini file, in seconds.
@@ -880,8 +1008,8 @@ struct ImGuiIO
const char* LogFilename; // = "imgui_log.txt" // Path to .log file (default parameter to ImGui::LogToFile when no file is specified).
float MouseDoubleClickTime; // = 0.30f // Time for a double-click, in seconds.
float MouseDoubleClickMaxDist; // = 6.0f // Distance threshold to stay in to validate a double-click, in pixels.
- float MouseDragThreshold; // = 6.0f // Distance threshold before considering we are dragging
- int KeyMap[ImGuiKey_COUNT]; // <unset> // Map of indices into the KeysDown[512] entries array
+ float MouseDragThreshold; // = 6.0f // Distance threshold before considering we are dragging.
+ int KeyMap[ImGuiKey_COUNT]; // <unset> // Map of indices into the KeysDown[512] entries array which represent your "native" keyboard state.
float KeyRepeatDelay; // = 0.250f // When holding a key/button, time before it starts repeating, in seconds (for buttons in Repeat mode, etc.).
float KeyRepeatRate; // = 0.050f // When holding a key/button, rate at which it repeats, in seconds.
void* UserData; // = NULL // Store your own data for retrieval by callbacks.
@@ -902,41 +1030,39 @@ struct ImGuiIO
// Settings (User Functions)
//------------------------------------------------------------------
- // Rendering function, will be called in Render().
- // Alternatively you can keep this to NULL and call GetDrawData() after Render() to get the same pointer.
- // See example applications if you are unsure of how to implement this.
- void (*RenderDrawListsFn)(ImDrawData* data);
-
// Optional: access OS clipboard
// (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures)
const char* (*GetClipboardTextFn)(void* user_data);
void (*SetClipboardTextFn)(void* user_data, const char* text);
void* ClipboardUserData;
- // Optional: override memory allocations. MemFreeFn() may be called with a NULL pointer.
- // (default to posix malloc/free)
- void* (*MemAllocFn)(size_t sz);
- void (*MemFreeFn)(void* ptr);
-
// Optional: notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese IME in Windows)
// (default to use native imm32 api on Windows)
void (*ImeSetInputScreenPosFn)(int x, int y);
void* ImeWindowHandle; // (Windows) Set this to your HWND to get automatic IME cursor positioning.
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ // [OBSOLETE] Rendering function, will be automatically called in Render(). Please call your rendering function yourself now! You can obtain the ImDrawData* by calling ImGui::GetDrawData() after Render().
+ // See example applications if you are unsure of how to implement this.
+ void (*RenderDrawListsFn)(ImDrawData* data);
+#endif
+
//------------------------------------------------------------------
// Input - Fill before calling NewFrame()
//------------------------------------------------------------------
- ImVec2 MousePos; // Mouse position, in pixels. Set to ImVec2(-FLT_MAX,-FLT_MAX) if mouse is unavailable (on another screen, etc.)
- bool MouseDown[5]; // Mouse buttons: left, right, middle + extras. ImGui itself mostly only uses left button (BeginPopupContext** are using right button). Others buttons allows us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API.
- float MouseWheel; // Mouse wheel: 1 unit scrolls about 5 lines text.
- bool MouseDrawCursor; // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor).
- bool KeyCtrl; // Keyboard modifier pressed: Control
- bool KeyShift; // Keyboard modifier pressed: Shift
- bool KeyAlt; // Keyboard modifier pressed: Alt
- bool KeySuper; // Keyboard modifier pressed: Cmd/Super/Windows
- bool KeysDown[512]; // Keyboard keys that are pressed (in whatever storage order you naturally have access to keyboard data)
- ImWchar InputCharacters[16+1]; // List of characters input (translated by user from keypress+keyboard state). Fill using AddInputCharacter() helper.
+ ImVec2 MousePos; // Mouse position, in pixels. Set to ImVec2(-FLT_MAX,-FLT_MAX) if mouse is unavailable (on another screen, etc.)
+ bool MouseDown[5]; // Mouse buttons: left, right, middle + extras. ImGui itself mostly only uses left button (BeginPopupContext** are using right button). Others buttons allows us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API.
+ float MouseWheel; // Mouse wheel: 1 unit scrolls about 5 lines text.
+ float MouseWheelH; // Mouse wheel (Horizontal). Most users don't have a mouse with an horizontal wheel, may not be filled by all back-ends.
+ bool MouseDrawCursor; // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor).
+ bool KeyCtrl; // Keyboard modifier pressed: Control
+ bool KeyShift; // Keyboard modifier pressed: Shift
+ bool KeyAlt; // Keyboard modifier pressed: Alt
+ bool KeySuper; // Keyboard modifier pressed: Cmd/Super/Windows
+ bool KeysDown[512]; // Keyboard keys that are pressed (ideally left in the "native" order your engine has access to keyboard keys, so you can use your own defines/enums for keys).
+ ImWchar InputCharacters[16+1]; // List of characters input (translated by user from keypress+keyboard state). Fill using AddInputCharacter() helper.
+ float NavInputs[ImGuiNavInput_COUNT]; // Gamepad inputs (keyboard keys will be auto-mapped and be written here by ImGui::NewFrame, all values will be cleared back to zero in ImGui::EndFrame)
// Functions
IMGUI_API void AddInputCharacter(ImWchar c); // Add new character into InputCharacters[]
@@ -947,12 +1073,13 @@ struct ImGuiIO
// Output - Retrieve after calling NewFrame()
//------------------------------------------------------------------
- bool WantCaptureMouse; // When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. This is set by ImGui when it wants to use your mouse (e.g. unclicked mouse is hovering a window, or a widget is active).
- bool WantCaptureKeyboard; // When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. This is set by ImGui when it wants to use your keyboard inputs.
+ bool WantCaptureMouse; // When io.WantCaptureMouse is true, imgui will use the mouse inputs, do not dispatch them to your main game/application (in both cases, always pass on mouse inputs to imgui). (e.g. unclicked mouse is hovering over an imgui window, widget is active, mouse was clicked over an imgui window, etc.).
+ bool WantCaptureKeyboard; // When io.WantCaptureKeyboard is true, imgui will use the keyboard inputs, do not dispatch them to your main game/application (in both cases, always pass keyboard inputs to imgui). (e.g. InputText active, or an imgui window is focused and navigation is enabled, etc.).
bool WantTextInput; // Mobile/console: when io.WantTextInput is true, you may display an on-screen keyboard. This is set by ImGui when it wants textual keyboard input to happen (e.g. when a InputText widget is active).
- bool WantMoveMouse; // [BETA-NAV] MousePos has been altered, back-end should reposition mouse on next frame. Set only when 'NavMovesMouse=true'.
+ bool WantSetMousePos; // MousePos has been altered, back-end should reposition mouse on next frame. Set only when ImGuiConfigFlags_NavEnableSetMousePos flag is enabled.
+ bool NavActive; // Directional navigation is currently allowed (will handle ImGuiKey_NavXXX events) = a window is focused and it doesn't use the ImGuiWindowFlags_NoNavInputs flag.
+ bool NavVisible; // Directional navigation is visible and allowed (will handle ImGuiKey_NavXXX events).
float Framerate; // Application framerate estimation, in frame per second. Solely for convenience. Rolling average estimation based on IO.DeltaTime over 120 frames
- int MetricsAllocs; // Number of active memory allocations
int MetricsRenderVertices; // Vertices output during last call to Render()
int MetricsRenderIndices; // Indices output during last call to Render() = number of triangles * 3
int MetricsActiveWindows; // Number of visible root windows (exclude child windows)
@@ -975,30 +1102,41 @@ struct ImGuiIO
float MouseDragMaxDistanceSqr[5]; // Squared maximum distance of how much mouse has traveled from the clicking point
float KeysDownDuration[512]; // Duration the keyboard key has been down (0.0f == just pressed)
float KeysDownDurationPrev[512]; // Previous duration the key has been down
+ float NavInputsDownDuration[ImGuiNavInput_COUNT];
+ float NavInputsDownDurationPrev[ImGuiNavInput_COUNT];
IMGUI_API ImGuiIO();
};
//-----------------------------------------------------------------------------
-// Obsolete functions (Will be removed! Also see 'API BREAKING CHANGES' section in imgui.cpp)
+// Obsolete functions (Will be removed! Read 'API BREAKING CHANGES' section in imgui.cpp for details)
//-----------------------------------------------------------------------------
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
namespace ImGui
{
- static inline void ShowTestWindow() { return ShowDemoWindow(); } // OBSOLETE 1.53+
- static inline bool IsRootWindowFocused() { return IsWindowFocused(ImGuiFocusedFlags_RootWindow); } // OBSOLETE 1.53+
- static inline bool IsRootWindowOrAnyChildFocused() { return IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows); } // OBSOLETE 1.53+
- static inline void SetNextWindowContentWidth(float width) { SetNextWindowContentSize(ImVec2(width, 0.0f)); } // OBSOLETE 1.53+ (nb: original version preserved last Y value set by SetNextWindowContentSize())
- static inline bool IsRootWindowOrAnyChildHovered(ImGuiHoveredFlags flags = 0) { return IsItemHovered(flags | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows); } // OBSOLETE 1.53+ use flags directly
- bool Begin(const char* name, bool* p_open, const ImVec2& size_on_first_use, float bg_alpha_override = -1.0f, ImGuiWindowFlags flags = 0); // OBSOLETE 1.52+. use SetNextWindowSize() instead if you want to set a window size.
- static inline void AlignFirstTextHeightToWidgets() { AlignTextToFramePadding(); } // OBSOLETE 1.52+
- static inline void SetNextWindowPosCenter(ImGuiCond cond = 0) { SetNextWindowPos(ImVec2(GetIO().DisplaySize.x * 0.5f, GetIO().DisplaySize.y * 0.5f), cond, ImVec2(0.5f, 0.5f)); } // OBSOLETE 1.52+
- static inline bool IsItemHoveredRect() { return IsItemHovered(ImGuiHoveredFlags_RectOnly); } // OBSOLETE 1.51+
- static inline bool IsPosHoveringAnyWindow(const ImVec2&) { IM_ASSERT(0); return false; } // OBSOLETE 1.51+. This was partly broken. You probably wanted to use ImGui::GetIO().WantCaptureMouse instead.
- static inline bool IsMouseHoveringAnyWindow() { return IsAnyWindowHovered(); } // OBSOLETE 1.51+
- static inline bool IsMouseHoveringWindow() { return IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem); } // OBSOLETE 1.51+
- static inline bool CollapsingHeader(const char* label, const char* str_id, bool framed = true, bool default_open = false) { (void)str_id; (void)framed; ImGuiTreeNodeFlags default_open_flags = 1 << 5; return CollapsingHeader(label, (default_open ? default_open_flags : 0)); } // OBSOLETE 1.49+
+ // OBSOLETED in 1.60 (from Dec 2017)
+ static inline bool IsAnyWindowFocused() { return IsWindowFocused(ImGuiFocusedFlags_AnyWindow); }
+ static inline bool IsAnyWindowHovered() { return IsWindowHovered(ImGuiHoveredFlags_AnyWindow); }
+ static inline ImVec2 CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge = false, float outward = 0.f) { (void)on_edge; (void)outward; IM_ASSERT(0); return pos; }
+ // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017)
+ static inline void ShowTestWindow() { return ShowDemoWindow(); }
+ static inline bool IsRootWindowFocused() { return IsWindowFocused(ImGuiFocusedFlags_RootWindow); }
+ static inline bool IsRootWindowOrAnyChildFocused() { return IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows); }
+ static inline void SetNextWindowContentWidth(float w) { SetNextWindowContentSize(ImVec2(w, 0.0f)); }
+ static inline float GetItemsLineHeightWithSpacing() { return GetFrameHeightWithSpacing(); }
+ // OBSOLETED in 1.52 (between Aug 2017 and Oct 2017)
+ bool Begin(const char* name, bool* p_open, const ImVec2& size_on_first_use, float bg_alpha_override = -1.0f, ImGuiWindowFlags flags = 0); // Use SetNextWindowSize(size, ImGuiCond_FirstUseEver) + SetNextWindowBgAlpha() instead.
+ static inline bool IsRootWindowOrAnyChildHovered() { return IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows); }
+ static inline void AlignFirstTextHeightToWidgets() { AlignTextToFramePadding(); }
+ static inline void SetNextWindowPosCenter(ImGuiCond c=0) { ImGuiIO& io = GetIO(); SetNextWindowPos(ImVec2(io.DisplaySize.x * 0.5f, io.DisplaySize.y * 0.5f), c, ImVec2(0.5f, 0.5f)); }
+ // OBSOLETED in 1.51 (between Jun 2017 and Aug 2017)
+ static inline bool IsItemHoveredRect() { return IsItemHovered(ImGuiHoveredFlags_RectOnly); }
+ static inline bool IsPosHoveringAnyWindow(const ImVec2&) { IM_ASSERT(0); return false; } // This was misleading and partly broken. You probably want to use the ImGui::GetIO().WantCaptureMouse flag instead.
+ static inline bool IsMouseHoveringAnyWindow() { return IsWindowHovered(ImGuiHoveredFlags_AnyWindow); }
+ static inline bool IsMouseHoveringWindow() { return IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem); }
+ // OBSOLETED IN 1.49 (between Apr 2016 and May 2016)
+ static inline bool CollapsingHeader(const char* label, const char* str_id, bool framed = true, bool default_open = false) { (void)str_id; (void)framed; ImGuiTreeNodeFlags default_open_flags = 1 << 5; return CollapsingHeader(label, (default_open ? default_open_flags : 0)); }
}
#endif
@@ -1006,8 +1144,8 @@ namespace ImGui
// Helpers
//-----------------------------------------------------------------------------
-// Lightweight std::vector<> like class to avoid dragging dependencies (also: windows implementation of STL with debug enabled is absurdly slow, so let's bypass it so our code runs fast in debug).
-// Our implementation does NOT call C++ constructors/destructors. This is intentional and we do not require it. Do not use this class as a straight std::vector replacement in your code!
+// Helper: Lightweight std::vector<> like class to avoid dragging dependencies (also: Windows implementation of STL with debug enabled is absurdly slow, so let's bypass it so our code runs fast in debug).
+// *Important* Our implementation does NOT call C++ constructors/destructors. This is intentional, we do not require it but you have to be mindful of that. Do not use this class as a straight std::vector replacement in your code!
template<typename T>
class ImVector
{
@@ -1022,11 +1160,12 @@ public:
inline ImVector() { Size = Capacity = 0; Data = NULL; }
inline ~ImVector() { if (Data) ImGui::MemFree(Data); }
+ inline ImVector(const ImVector<T>& src) { Size = Capacity = 0; Data = NULL; operator=(src); }
+ inline ImVector& operator=(const ImVector<T>& src) { clear(); resize(src.Size); memcpy(Data, src.Data, (size_t)Size * sizeof(value_type)); return *this; }
inline bool empty() const { return Size == 0; }
inline int size() const { return Size; }
inline int capacity() const { return Capacity; }
-
inline value_type& operator[](int i) { IM_ASSERT(i < Size); return Data[i]; }
inline const value_type& operator[](int i) const { IM_ASSERT(i < Size); return Data[i]; }
@@ -1039,38 +1178,44 @@ public:
inline const value_type& front() const { IM_ASSERT(Size > 0); return Data[0]; }
inline value_type& back() { IM_ASSERT(Size > 0); return Data[Size - 1]; }
inline const value_type& back() const { IM_ASSERT(Size > 0); return Data[Size - 1]; }
- inline void swap(ImVector<T>& rhs) { int rhs_size = rhs.Size; rhs.Size = Size; Size = rhs_size; int rhs_cap = rhs.Capacity; rhs.Capacity = Capacity; Capacity = rhs_cap; value_type* rhs_data = rhs.Data; rhs.Data = Data; Data = rhs_data; }
+ inline void swap(ImVector<value_type>& rhs) { int rhs_size = rhs.Size; rhs.Size = Size; Size = rhs_size; int rhs_cap = rhs.Capacity; rhs.Capacity = Capacity; Capacity = rhs_cap; value_type* rhs_data = rhs.Data; rhs.Data = Data; Data = rhs_data; }
- inline int _grow_capacity(int size) const { int new_capacity = Capacity ? (Capacity + Capacity/2) : 8; return new_capacity > size ? new_capacity : size; }
-
- inline void resize(int new_size) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); Size = new_size; }
- inline void resize(int new_size, const T& v){ if (new_size > Capacity) reserve(_grow_capacity(new_size)); if (new_size > Size) for (int n = Size; n < new_size; n++) Data[n] = v; Size = new_size; }
- inline void reserve(int new_capacity)
+ inline int _grow_capacity(int sz) const { int new_capacity = Capacity ? (Capacity + Capacity/2) : 8; return new_capacity > sz ? new_capacity : sz; }
+ inline void resize(int new_size) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); Size = new_size; }
+ inline void resize(int new_size,const value_type& v){ if (new_size > Capacity) reserve(_grow_capacity(new_size)); if (new_size > Size) for (int n = Size; n < new_size; n++) memcpy(&Data[n], &v, sizeof(v)); Size = new_size; }
+ inline void reserve(int new_capacity)
{
if (new_capacity <= Capacity)
return;
- T* new_data = (value_type*)ImGui::MemAlloc((size_t)new_capacity * sizeof(T));
+ value_type* new_data = (value_type*)ImGui::MemAlloc((size_t)new_capacity * sizeof(value_type));
if (Data)
- memcpy(new_data, Data, (size_t)Size * sizeof(T));
+ memcpy(new_data, Data, (size_t)Size * sizeof(value_type));
ImGui::MemFree(Data);
Data = new_data;
Capacity = new_capacity;
}
- inline void push_back(const value_type& v) { if (Size == Capacity) reserve(_grow_capacity(Size + 1)); Data[Size++] = v; }
- inline void pop_back() { IM_ASSERT(Size > 0); Size--; }
- inline void push_front(const value_type& v) { if (Size == 0) push_back(v); else insert(Data, v); }
-
- inline iterator erase(const_iterator it) { IM_ASSERT(it >= Data && it < Data+Size); const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + 1, ((size_t)Size - (size_t)off - 1) * sizeof(value_type)); Size--; return Data + off; }
- inline iterator insert(const_iterator it, const value_type& v) { IM_ASSERT(it >= Data && it <= Data+Size); const ptrdiff_t off = it - Data; if (Size == Capacity) reserve(_grow_capacity(Size + 1)); if (off < (int)Size) memmove(Data + off + 1, Data + off, ((size_t)Size - (size_t)off) * sizeof(value_type)); Data[off] = v; Size++; return Data + off; }
- inline bool contains(const value_type& v) const { const T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data++ == v) return true; return false; }
+ // NB: &v cannot be pointing inside the ImVector Data itself! e.g. v.push_back(v[10]) is forbidden.
+ inline void push_back(const value_type& v) { if (Size == Capacity) reserve(_grow_capacity(Size + 1)); memcpy(&Data[Size], &v, sizeof(v)); Size++; }
+ inline void pop_back() { IM_ASSERT(Size > 0); Size--; }
+ inline void push_front(const value_type& v) { if (Size == 0) push_back(v); else insert(Data, v); }
+ inline iterator erase(const_iterator it) { IM_ASSERT(it >= Data && it < Data+Size); const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + 1, ((size_t)Size - (size_t)off - 1) * sizeof(value_type)); Size--; return Data + off; }
+ inline iterator insert(const_iterator it, const value_type& v) { IM_ASSERT(it >= Data && it <= Data+Size); const ptrdiff_t off = it - Data; if (Size == Capacity) reserve(_grow_capacity(Size + 1)); if (off < (int)Size) memmove(Data + off + 1, Data + off, ((size_t)Size - (size_t)off) * sizeof(value_type)); memcpy(&Data[off], &v, sizeof(v)); Size++; return Data + off; }
+ inline bool contains(const value_type& v) const { const T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data++ == v) return true; return false; }
};
-// Helper: execute a block of code at maximum once a frame. Convenient if you want to quickly create an UI within deep-nested code that runs multiple times every frame.
-// Usage:
-// static ImGuiOnceUponAFrame oaf;
-// if (oaf)
-// ImGui::Text("This will be called only once per frame");
+// Helper: IM_NEW(), IM_PLACEMENT_NEW(), IM_DELETE() macros to call MemAlloc + Placement New, Placement Delete + MemFree
+// We call C++ constructor on own allocated memory via the placement "new(ptr) Type()" syntax.
+// Defining a custom placement new() with a dummy parameter allows us to bypass including <new> which on some platforms complains when user has disabled exceptions.
+struct ImNewDummy {};
+inline void* operator new(size_t, ImNewDummy, void* ptr) { return ptr; }
+inline void operator delete(void*, ImNewDummy, void*) {} // This is only required so we can use the symetrical new()
+#define IM_PLACEMENT_NEW(_PTR) new(ImNewDummy(), _PTR)
+#define IM_NEW(_TYPE) new(ImNewDummy(), ImGui::MemAlloc(sizeof(_TYPE))) _TYPE
+template<typename T> void IM_DELETE(T*& p) { if (p) { p->~T(); ImGui::MemFree(p); p = NULL; } }
+
+// Helper: Execute a block of code at maximum once a frame. Convenient if you want to quickly create an UI within deep-nested code that runs multiple times every frame.
+// Usage: static ImGuiOnceUponAFrame oaf; if (oaf) ImGui::Text("This will be called only once per frame");
struct ImGuiOnceUponAFrame
{
ImGuiOnceUponAFrame() { RefFrame = -1; }
@@ -1078,7 +1223,7 @@ struct ImGuiOnceUponAFrame
operator bool() const { int current_frame = ImGui::GetFrameCount(); if (RefFrame == current_frame) return false; RefFrame = current_frame; return true; }
};
-// Helper macro for ImGuiOnceUponAFrame. Attention: The macro expands into 2 statement so make sure you don't use it within e.g. an if() statement without curly braces.
+// Helper: Macro for ImGuiOnceUponAFrame. Attention: The macro expands into 2 statement so make sure you don't use it within e.g. an if() statement without curly braces.
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // Will obsolete
#define IMGUI_ONCE_UPON_A_FRAME static ImGuiOnceUponAFrame imgui_oaf; if (imgui_oaf)
#endif
@@ -1134,8 +1279,8 @@ struct ImGuiTextBuffer
// Helper: Simple Key->value storage
// Typically you don't have to worry about this since a storage is held within each Window.
-// We use it to e.g. store collapse state for a tree (Int 0/1), store color edit options.
-// This is optimized for efficient reading (dichotomy into a contiguous buffer), rare writing (typically tied to user interactions)
+// We use it to e.g. store collapse state for a tree (Int 0/1)
+// This is optimized for efficient lookup (dichotomy into a contiguous buffer) and rare insertion (typically tied to user interactions aka max once a frame)
// You can use it as custom user storage for temporary values. Declare your own storage if, for example:
// - You want to manipulate the open/close state of a particular sub-tree in your interface (tree node uses Int 0/1 to store their state).
// - You want to store custom debug data easily without adding or editing structures in your code (probably not efficient, but convenient)
@@ -1211,7 +1356,7 @@ struct ImGuiTextEditCallbackData
// Resizing callback data to apply custom constraint. As enabled by SetNextWindowSizeConstraints(). Callback is called during the next Begin().
// NB: For basic min/max size constraint on each axis you don't need to use the callback! The SetNextWindowSizeConstraints() parameters are enough.
-struct ImGuiSizeConstraintCallbackData
+struct ImGuiSizeCallbackData
{
void* UserData; // Read-only. What user passed to SetNextWindowSizeConstraints()
ImVec2 Pos; // Read-only. Window position, for reference.
@@ -1230,7 +1375,7 @@ struct ImGuiPayload
ImGuiID SourceId; // Source item id
ImGuiID SourceParentId; // Source parent id (if available)
int DataFrameCount; // Data timestamp
- char DataType[8 + 1]; // Data type tag (short user-supplied string)
+ char DataType[32+1]; // Data type tag (short user-supplied string, 32 characters max)
bool Preview; // Set when AcceptDragDropPayload() was called and mouse has been hovering the target item (nb: handle overlapping drag targets)
bool Delivery; // Set when AcceptDragDropPayload() was called and mouse button is released over the target item.
@@ -1260,7 +1405,7 @@ struct ImGuiPayload
#define IM_COL32_BLACK IM_COL32(0,0,0,255) // Opaque black
#define IM_COL32_BLACK_TRANS IM_COL32(0,0,0,0) // Transparent black = 0x00000000
-// ImColor() helper to implicity converts colors to either ImU32 (packed 4x1 byte) or ImVec4 (4x1 float)
+// Helper: ImColor() implicity converts colors to either ImU32 (packed 4x1 byte) or ImVec4 (4x1 float)
// Prefer using IM_COL32() macros if you want a guaranteed compile-time ImU32 for usage with ImDrawList API.
// **Avoid storing ImColor! Store either u32 of ImVec4. This is not a full-featured color class. MAY OBSOLETE.
// **None of the ImGui API are using ImColor directly but you can use it as a convenience to pass colors in either ImU32 or ImVec4 formats. Explicitly cast to ImU32 or ImVec4 if needed.
@@ -1394,9 +1539,9 @@ struct ImDrawList
ImVector<ImDrawCmd> CmdBuffer; // Draw commands. Typically 1 command = 1 GPU draw call, unless the command is a callback.
ImVector<ImDrawIdx> IdxBuffer; // Index buffer. Each command consume ImDrawCmd::ElemCount of those
ImVector<ImDrawVert> VtxBuffer; // Vertex buffer.
+ ImDrawListFlags Flags; // Flags, you may poke into these to adjust anti-aliasing settings per-primitive.
// [Internal, used while building lists]
- ImDrawListFlags Flags; // Flags, you may poke into these to adjust anti-aliasing settings per-primitive.
const ImDrawListSharedData* _Data; // Pointer to shared draw data (you can use ImGui::GetDrawListSharedData() to get the one from current ImGui context)
const char* _OwnerName; // Pointer to owner window's name for debugging
unsigned int _VtxCurrentIdx; // [Internal] == VtxBuffer.Size
@@ -1409,12 +1554,13 @@ struct ImDrawList
int _ChannelsCount; // [Internal] number of active channels (1+)
ImVector<ImDrawChannel> _Channels; // [Internal] draw channels for columns API (not resized down so _ChannelsCount may be smaller than _Channels.Size)
+ // If you want to create ImDrawList instances, pass them ImGui::GetDrawListSharedData() or create and use your own ImDrawListSharedData (so you can use ImDrawList without ImGui)
ImDrawList(const ImDrawListSharedData* shared_data) { _Data = shared_data; _OwnerName = NULL; Clear(); }
~ImDrawList() { ClearFreeMemory(); }
IMGUI_API void PushClipRect(ImVec2 clip_rect_min, ImVec2 clip_rect_max, bool intersect_with_current_clip_rect = false); // Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling)
IMGUI_API void PushClipRectFullScreen();
IMGUI_API void PopClipRect();
- IMGUI_API void PushTextureID(const ImTextureID& texture_id);
+ IMGUI_API void PushTextureID(ImTextureID texture_id);
IMGUI_API void PopTextureID();
inline ImVec2 GetClipRectMin() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.x, cr.y); }
inline ImVec2 GetClipRectMax() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.z, cr.w); }
@@ -1460,6 +1606,7 @@ struct ImDrawList
// Advanced
IMGUI_API void AddCallback(ImDrawCallback callback, void* callback_data); // Your rendering function must check for 'UserCallback' in ImDrawCmd and call the function instead of rendering triangles.
IMGUI_API void AddDrawCmd(); // This is useful if you need to forcefully create a new draw call (to allow for dependent rendering / blending). Otherwise primitives are merged into the same draw-call as much as possible
+ IMGUI_API ImDrawList* CloneOutput() const; // Create a clone of the CmdBuffer/IdxBuffer/VtxBuffer.
// Internal helpers
// NB: all primitives needs to be reserved via PrimReserve() beforehand!
@@ -1477,38 +1624,42 @@ struct ImDrawList
};
// All draw data to render an ImGui frame
+// (NB: the style and the naming convention here is a little inconsistent but we preserve them for backward compatibility purpose)
struct ImDrawData
{
bool Valid; // Only valid after Render() is called and before the next NewFrame() is called.
- ImDrawList** CmdLists;
- int CmdListsCount;
- int TotalVtxCount; // For convenience, sum of all cmd_lists vtx_buffer.Size
- int TotalIdxCount; // For convenience, sum of all cmd_lists idx_buffer.Size
+ ImDrawList** CmdLists; // Array of ImDrawList* to render. The ImDrawList are owned by ImGuiContext and only pointed to from here.
+ int CmdListsCount; // Number of ImDrawList* to render
+ int TotalIdxCount; // For convenience, sum of all ImDrawList's IdxBuffer.Size
+ int TotalVtxCount; // For convenience, sum of all ImDrawList's VtxBuffer.Size
// Functions
- ImDrawData() { Valid = false; CmdLists = NULL; CmdListsCount = TotalVtxCount = TotalIdxCount = 0; }
- IMGUI_API void DeIndexAllBuffers(); // For backward compatibility or convenience: convert all buffers from indexed to de-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering!
- IMGUI_API void ScaleClipRects(const ImVec2& sc); // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than ImGui expects, or if there is a difference between your window resolution and framebuffer resolution.
+ ImDrawData() { Valid = false; Clear(); }
+ ~ImDrawData() { Clear(); }
+ void Clear() { Valid = false; CmdLists = NULL; CmdListsCount = TotalVtxCount = TotalIdxCount = 0; } // The ImDrawList are owned by ImGuiContext!
+ IMGUI_API void DeIndexAllBuffers(); // Helper to convert all buffers from indexed to non-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering!
+ IMGUI_API void ScaleClipRects(const ImVec2& sc); // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than ImGui expects, or if there is a difference between your window resolution and framebuffer resolution.
};
struct ImFontConfig
{
- void* FontData; // // TTF/OTF data
- int FontDataSize; // // TTF/OTF data size
- bool FontDataOwnedByAtlas; // true // TTF/OTF data ownership taken by the container ImFontAtlas (will delete memory itself).
- int FontNo; // 0 // Index of font within TTF/OTF file
- float SizePixels; // // Size in pixels for rasterizer.
- int OversampleH, OversampleV; // 3, 1 // Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on the Y axis.
- bool PixelSnapH; // false // Align every glyph to pixel boundary. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1.
- ImVec2 GlyphExtraSpacing; // 0, 0 // Extra spacing (in pixels) between glyphs. Only X axis is supported for now.
- ImVec2 GlyphOffset; // 0, 0 // Offset all glyphs from this font input.
- const ImWchar* GlyphRanges; // NULL // Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE.
- bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights.
- unsigned int RasterizerFlags; // 0x00 // Settings for custom font rasterizer (e.g. ImGuiFreeType). Leave as zero if you aren't using one.
- float RasterizerMultiply; // 1.0f // Brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable.
+ void* FontData; // // TTF/OTF data
+ int FontDataSize; // // TTF/OTF data size
+ bool FontDataOwnedByAtlas; // true // TTF/OTF data ownership taken by the container ImFontAtlas (will delete memory itself).
+ int FontNo; // 0 // Index of font within TTF/OTF file
+ float SizePixels; // // Size in pixels for rasterizer.
+ int OversampleH; // 3 // Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on the Y axis.
+ int OversampleV; // 1 // Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on the Y axis.
+ bool PixelSnapH; // false // Align every glyph to pixel boundary. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1.
+ ImVec2 GlyphExtraSpacing; // 0, 0 // Extra spacing (in pixels) between glyphs. Only X axis is supported for now.
+ ImVec2 GlyphOffset; // 0, 0 // Offset all glyphs from this font input.
+ const ImWchar* GlyphRanges; // NULL // Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE.
+ bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights.
+ unsigned int RasterizerFlags; // 0x00 // Settings for custom font rasterizer (e.g. ImGuiFreeType). Leave as zero if you aren't using one.
+ float RasterizerMultiply; // 1.0f // Brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable.
// [Internal]
- char Name[32]; // Name (strictly to ease debugging)
+ char Name[40]; // Name (strictly to ease debugging)
ImFont* DstFont;
IMGUI_API ImFontConfig();
@@ -1522,6 +1673,12 @@ struct ImFontGlyph
float U0, V0, U1, V1; // Texture coordinates
};
+enum ImFontAtlasFlags_
+{
+ ImFontAtlasFlags_NoPowerOfTwoHeight = 1 << 0, // Don't round the height to next power of two
+ ImFontAtlasFlags_NoMouseCursors = 1 << 1 // Don't build software mouse cursors into the atlas
+};
+
// Load and rasterize multiple TTF/OTF fonts into a same texture.
// Sharing a texture for multiple fonts allows us to reduce the number of draw calls during rendering.
// We also add custom graphic data into the texture that serves for ImGui.
@@ -1540,10 +1697,10 @@ struct ImFontAtlas
IMGUI_API ImFont* AddFontFromMemoryTTF(void* font_data, int font_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // Note: Transfer ownership of 'ttf_data' to ImFontAtlas! Will be deleted after Build(). Set font_cfg->FontDataOwnedByAtlas to false to keep ownership.
IMGUI_API ImFont* AddFontFromMemoryCompressedTTF(const void* compressed_font_data, int compressed_font_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data' still owned by caller. Compress with binary_to_compressed_c.cpp.
IMGUI_API ImFont* AddFontFromMemoryCompressedBase85TTF(const char* compressed_font_data_base85, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data_base85' still owned by caller. Compress with binary_to_compressed_c.cpp with -base85 parameter.
- IMGUI_API void ClearTexData(); // Clear the CPU-side texture data. Saves RAM once the texture has been copied to graphics memory.
- IMGUI_API void ClearInputData(); // Clear the input TTF data (inc sizes, glyph ranges)
- IMGUI_API void ClearFonts(); // Clear the ImGui-side font data (glyphs storage, UV coordinates)
- IMGUI_API void Clear(); // Clear all
+ IMGUI_API void ClearInputData(); // Clear input data (all ImFontConfig structures including sizes, TTF data, glyph ranges, etc.) = all the data used to build the texture and fonts.
+ IMGUI_API void ClearTexData(); // Clear output texture data (CPU side). Saves RAM once the texture has been copied to graphics memory.
+ IMGUI_API void ClearFonts(); // Clear output font data (glyphs storage, UV coordinates).
+ IMGUI_API void Clear(); // Clear all input and output.
// Build atlas, retrieve pixel data.
// User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID().
@@ -1600,13 +1757,17 @@ struct ImFontAtlas
IMGUI_API int AddCustomRectRegular(unsigned int id, int width, int height); // Id needs to be >= 0x10000. Id >= 0x80000000 are reserved for ImGui and ImDrawList
IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0,0)); // Id needs to be < 0x10000 to register a rectangle to map into a specific font.
- IMGUI_API void CalcCustomRectUV(const CustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max);
const CustomRect* GetCustomRectByIndex(int index) const { if (index < 0) return NULL; return &CustomRects[index]; }
+ // [Internal]
+ IMGUI_API void CalcCustomRectUV(const CustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max);
+ IMGUI_API bool GetMouseCursorTexData(ImGuiMouseCursor cursor, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]);
+
//-------------------------------------------
// Members
//-------------------------------------------
+ ImFontAtlasFlags Flags; // Build flags (see ImFontAtlasFlags_)
ImTextureID TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure.
int TexDesiredWidth; // Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height.
int TexGlyphPadding; // Padding between glyphs within texture in pixels. Defaults to 1.
@@ -1617,6 +1778,7 @@ struct ImFontAtlas
unsigned int* TexPixelsRGBA32; // 4 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight * 4
int TexWidth; // Texture width calculated during Build().
int TexHeight; // Texture height calculated during Build().
+ ImVec2 TexUvScale; // = (1.0f/TexWidth, 1.0f/TexHeight)
ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel
ImVector<ImFont*> Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font.
ImVector<CustomRect> CustomRects; // Rectangles for packing custom texture data into the atlas.
@@ -1631,7 +1793,7 @@ struct ImFont
// Members: Hot ~62/78 bytes
float FontSize; // <user set> // Height of characters, set during loading (don't change after loading)
float Scale; // = 1.f // Base font scale, multiplied by the per-window font scale which you can adjust with SetFontScale()
- ImVec2 DisplayOffset; // = (0.f,1.f) // Offset font rendering by xx pixels
+ ImVec2 DisplayOffset; // = (0.f,0.f) // Offset font rendering by xx pixels
ImVector<ImFontGlyph> Glyphs; // // All glyphs.
ImVector<float> IndexAdvanceX; // // Sparse. Glyphs->AdvanceX in a directly indexable way (more cache-friendly, for CalcTextSize functions which are often bottleneck in large UI).
ImVector<unsigned short> IndexLookup; // // Sparse. Index glyphs by Unicode code-point.
@@ -1644,6 +1806,7 @@ struct ImFont
ImFontConfig* ConfigData; // // Pointer within ContainerAtlas->ConfigData
ImFontAtlas* ContainerAtlas; // // What we has been loaded into
float Ascent, Descent; // // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize]
+ bool DirtyLookupTables;
int MetricsTotalSurface;// // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs)
// Methods
@@ -1652,6 +1815,7 @@ struct ImFont
IMGUI_API void ClearOutputData();
IMGUI_API void BuildLookupTable();
IMGUI_API const ImFontGlyph*FindGlyph(ImWchar c) const;
+ IMGUI_API const ImFontGlyph*FindGlyphNoFallback(ImWchar c) const;
IMGUI_API void SetFallbackChar(ImWchar c);
float GetCharAdvance(ImWchar c) const { return ((int)c < IndexAdvanceX.Size) ? IndexAdvanceX[(int)c] : FallbackAdvanceX; }
bool IsLoaded() const { return ContainerAtlas != NULL; }
diff --git a/imgui/imgui_demo.cpp b/imgui/imgui_demo.cpp
index d739dfa4..8b7b5450 100644
--- a/imgui/imgui_demo.cpp
+++ b/imgui/imgui_demo.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.53
+// dear imgui, v1.60
// (demo code)
// Message to the person tempted to delete this file when integrating ImGui into their code base:
@@ -94,7 +94,7 @@ static void ShowHelpMarker(const char* desc)
if (ImGui::IsItemHovered())
{
ImGui::BeginTooltip();
- ImGui::PushTextWrapPos(450.0f);
+ ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
ImGui::TextUnformatted(desc);
ImGui::PopTextWrapPos();
ImGui::EndTooltip();
@@ -160,7 +160,7 @@ void ImGui::ShowDemoWindow(bool* p_open)
if (show_app_about)
{
ImGui::Begin("About Dear ImGui", &show_app_about, ImGuiWindowFlags_AlwaysAutoResize);
- ImGui::Text("dear imgui, %s", ImGui::GetVersion());
+ ImGui::Text("Dear ImGui, %s", ImGui::GetVersion());
ImGui::Separator();
ImGui::Text("By Omar Cornut and all dear imgui contributors.");
ImGui::Text("Dear ImGui is licensed under the MIT License, see LICENSE for more information.");
@@ -174,6 +174,7 @@ void ImGui::ShowDemoWindow(bool* p_open)
static bool no_resize = false;
static bool no_collapse = false;
static bool no_close = false;
+ static bool no_nav = false;
// Demonstrate the various window flags. Typically you would just use the default.
ImGuiWindowFlags window_flags = 0;
@@ -183,6 +184,7 @@ void ImGui::ShowDemoWindow(bool* p_open)
if (no_move) window_flags |= ImGuiWindowFlags_NoMove;
if (no_resize) window_flags |= ImGuiWindowFlags_NoResize;
if (no_collapse) window_flags |= ImGuiWindowFlags_NoCollapse;
+ if (no_nav) window_flags |= ImGuiWindowFlags_NoNav;
if (no_close) p_open = NULL; // Don't pass our bool* to Begin
ImGui::SetNextWindowSize(ImVec2(550,680), ImGuiCond_FirstUseEver);
@@ -247,7 +249,8 @@ void ImGui::ShowDemoWindow(bool* p_open)
ImGui::Checkbox("No move", &no_move); ImGui::SameLine(150);
ImGui::Checkbox("No resize", &no_resize); ImGui::SameLine(300);
ImGui::Checkbox("No collapse", &no_collapse);
- ImGui::Checkbox("No close", &no_close);
+ ImGui::Checkbox("No close", &no_close); ImGui::SameLine(150);
+ ImGui::Checkbox("No nav", &no_nav);
if (ImGui::TreeNode("Style"))
{
@@ -297,6 +300,12 @@ void ImGui::ShowDemoWindow(bool* p_open)
ImGui::PopID();
}
+ // Arrow buttons
+ float spacing = ImGui::GetStyle().ItemInnerSpacing.x;
+ if (ImGui::ArrowButton("##left", ImGuiDir_Left)) {}
+ ImGui::SameLine(0.0f, spacing);
+ if (ImGui::ArrowButton("##left", ImGuiDir_Right)) {}
+
ImGui::Text("Hover over me");
if (ImGui::IsItemHovered())
ImGui::SetTooltip("I am a tooltip");
@@ -312,43 +321,22 @@ void ImGui::ShowDemoWindow(bool* p_open)
ImGui::EndTooltip();
}
- // Testing ImGuiOnceUponAFrame helper.
- //static ImGuiOnceUponAFrame once;
- //for (int i = 0; i < 5; i++)
- // if (once)
- // ImGui::Text("This will be displayed only once.");
-
ImGui::Separator();
ImGui::LabelText("label", "Value");
{
- // Simplified one-liner Combo() API, using values packed in a single constant string
- static int current_item_1 = 1;
- ImGui::Combo("combo", &current_item_1, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0");
- //ImGui::Combo("combo w/ array of char*", &current_item_2_idx, items, IM_ARRAYSIZE(items)); // Combo using proper array. You can also pass a callback to retrieve array value, no need to create/copy an array just for that.
-
- // General BeginCombo() API, you have full control over your selection data and display type
- const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO", "PPPP", "QQQQQQQQQQ", "RRR", "SSSS" };
- static const char* current_item_2 = NULL;
- if (ImGui::BeginCombo("combo 2", current_item_2)) // The second parameter is the label previewed before opening the combo.
- {
- for (int n = 0; n < IM_ARRAYSIZE(items); n++)
- {
- bool is_selected = (current_item_2 == items[n]); // You can store your selection however you want, outside or inside your objects
- if (ImGui::Selectable(items[n], is_selected))
- current_item_2 = items[n];
- if (is_selected)
- ImGui::SetItemDefaultFocus(); // Set the initial focus when opening the combo (scrolling + for keyboard navigation support in the upcoming navigation branch)
- }
- ImGui::EndCombo();
- }
+ // Using the _simplified_ one-liner Combo() api here
+ const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" };
+ static int item_current = 0;
+ ImGui::Combo("combo", &item_current, items, IM_ARRAYSIZE(items));
+ ImGui::SameLine(); ShowHelpMarker("Refer to the \"Combo\" section below for an explanation of the full BeginCombo/EndCombo API, and demonstration of various flags.\n");
}
{
static char str0[128] = "Hello, world!";
- static int i0=123;
- static float f0=0.001f;
+ static int i0 = 123;
+ static float f0 = 0.001f;
ImGui::InputText("input text", str0, IM_ARRAYSIZE(str0));
ImGui::SameLine(); ShowHelpMarker("Hold SHIFT or use mouse to select text.\n" "CTRL+Left/Right to word jump.\n" "CTRL+A or double-click to select all.\n" "CTRL+X,CTRL+C,CTRL+V clipboard.\n" "CTRL+Z,CTRL+Y undo/redo.\n" "ESCAPE to revert.\n");
@@ -357,12 +345,17 @@ void ImGui::ShowDemoWindow(bool* p_open)
ImGui::InputFloat("input float", &f0, 0.01f, 1.0f);
+ // NB: You can use the %e notation as well.
+ static double d0 = 999999.000001;
+ ImGui::InputDouble("input double", &d0, 0.01f, 1.0f, "%.6f");
+ ImGui::SameLine(); ShowHelpMarker("You can input value using the scientific notation,\n e.g. \"1e+8\" becomes \"100000000\".\n");
+
static float vec4a[4] = { 0.10f, 0.20f, 0.30f, 0.44f };
ImGui::InputFloat3("input float3", vec4a);
}
{
- static int i1=50, i2=42;
+ static int i1 = 50, i2 = 42;
ImGui::DragInt("drag int", &i1, 1);
ImGui::SameLine(); ShowHelpMarker("Click and drag to edit value.\nHold SHIFT/ALT for faster/slower edit.\nDouble-click or CTRL+click to input value.");
@@ -385,25 +378,36 @@ void ImGui::ShowDemoWindow(bool* p_open)
ImGui::SliderAngle("slider angle", &angle);
}
- static float col1[3] = { 1.0f,0.0f,0.2f };
- static float col2[4] = { 0.4f,0.7f,0.0f,0.5f };
- ImGui::ColorEdit3("color 1", col1);
- ImGui::SameLine(); ShowHelpMarker("Click on the colored square to open a color picker.\nRight-click on the colored square to show options.\nCTRL+click on individual component to input value.\n");
-
- ImGui::ColorEdit4("color 2", col2);
+ {
+ static float col1[3] = { 1.0f,0.0f,0.2f };
+ static float col2[4] = { 0.4f,0.7f,0.0f,0.5f };
+ ImGui::ColorEdit3("color 1", col1);
+ ImGui::SameLine(); ShowHelpMarker("Click on the colored square to open a color picker.\nRight-click on the colored square to show options.\nCTRL+click on individual component to input value.\n");
- const char* listbox_items[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" };
- static int listbox_item_current = 1;
- ImGui::ListBox("listbox\n(single select)", &listbox_item_current, listbox_items, IM_ARRAYSIZE(listbox_items), 4);
+ ImGui::ColorEdit4("color 2", col2);
+ }
- //static int listbox_item_current2 = 2;
- //ImGui::PushItemWidth(-1);
- //ImGui::ListBox("##listbox2", &listbox_item_current2, listbox_items, IM_ARRAYSIZE(listbox_items), 4);
- //ImGui::PopItemWidth();
+ {
+ // List box
+ const char* listbox_items[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" };
+ static int listbox_item_current = 1;
+ ImGui::ListBox("listbox\n(single select)", &listbox_item_current, listbox_items, IM_ARRAYSIZE(listbox_items), 4);
+
+ //static int listbox_item_current2 = 2;
+ //ImGui::PushItemWidth(-1);
+ //ImGui::ListBox("##listbox2", &listbox_item_current2, listbox_items, IM_ARRAYSIZE(listbox_items), 4);
+ //ImGui::PopItemWidth();
+ }
ImGui::TreePop();
}
+ // Testing ImGuiOnceUponAFrame helper.
+ //static ImGuiOnceUponAFrame once;
+ //for (int i = 0; i < 5; i++)
+ // if (once)
+ // ImGui::Text("This will be displayed only once.");
+
if (ImGui::TreeNode("Trees"))
{
if (ImGui::TreeNode("Basic trees"))
@@ -413,7 +417,7 @@ void ImGui::ShowDemoWindow(bool* p_open)
{
ImGui::Text("blah blah");
ImGui::SameLine();
- if (ImGui::SmallButton("print")) printf("Child %d pressed", i);
+ if (ImGui::SmallButton("button")) { };
ImGui::TreePop();
}
ImGui::TreePop();
@@ -561,8 +565,8 @@ void ImGui::ShowDemoWindow(bool* p_open)
if (ImGui::TreeNode("Images"))
{
- ImGui::TextWrapped("Below we are displaying the font texture (which is the only texture we have access to in this demo). Use the 'ImTextureID' type as storage to pass pointers or identifier to your own texture data. Hover the texture for a zoomed view!");
ImGuiIO& io = ImGui::GetIO();
+ ImGui::TextWrapped("Below we are displaying the font texture (which is the only texture we have access to in this demo). Use the 'ImTextureID' type as storage to pass pointers or identifier to your own texture data. Hover the texture for a zoomed view!");
// Here we are grabbing the font texture because that's the only one we have access to inside the demo code.
// Remember that ImTextureID is just storage for whatever you want it to be, it is essentially a value that will be passed to the render function inside the ImDrawCmd structure.
@@ -581,14 +585,15 @@ void ImGui::ShowDemoWindow(bool* p_open)
if (ImGui::IsItemHovered())
{
ImGui::BeginTooltip();
- float focus_sz = 32.0f;
- float focus_x = io.MousePos.x - pos.x - focus_sz * 0.5f; if (focus_x < 0.0f) focus_x = 0.0f; else if (focus_x > my_tex_w - focus_sz) focus_x = my_tex_w - focus_sz;
- float focus_y = io.MousePos.y - pos.y - focus_sz * 0.5f; if (focus_y < 0.0f) focus_y = 0.0f; else if (focus_y > my_tex_h - focus_sz) focus_y = my_tex_h - focus_sz;
- ImGui::Text("Min: (%.2f, %.2f)", focus_x, focus_y);
- ImGui::Text("Max: (%.2f, %.2f)", focus_x + focus_sz, focus_y + focus_sz);
- ImVec2 uv0 = ImVec2((focus_x) / my_tex_w, (focus_y) / my_tex_h);
- ImVec2 uv1 = ImVec2((focus_x + focus_sz) / my_tex_w, (focus_y + focus_sz) / my_tex_h);
- ImGui::Image(my_tex_id, ImVec2(128,128), uv0, uv1, ImColor(255,255,255,255), ImColor(255,255,255,128));
+ float region_sz = 32.0f;
+ float region_x = io.MousePos.x - pos.x - region_sz * 0.5f; if (region_x < 0.0f) region_x = 0.0f; else if (region_x > my_tex_w - region_sz) region_x = my_tex_w - region_sz;
+ float region_y = io.MousePos.y - pos.y - region_sz * 0.5f; if (region_y < 0.0f) region_y = 0.0f; else if (region_y > my_tex_h - region_sz) region_y = my_tex_h - region_sz;
+ float zoom = 4.0f;
+ ImGui::Text("Min: (%.2f, %.2f)", region_x, region_y);
+ ImGui::Text("Max: (%.2f, %.2f)", region_x + region_sz, region_y + region_sz);
+ ImVec2 uv0 = ImVec2((region_x) / my_tex_w, (region_y) / my_tex_h);
+ ImVec2 uv1 = ImVec2((region_x + region_sz) / my_tex_w, (region_y + region_sz) / my_tex_h);
+ ImGui::Image(my_tex_id, ImVec2(region_sz * zoom, region_sz * zoom), uv0, uv1, ImColor(255,255,255,255), ImColor(255,255,255,128));
ImGui::EndTooltip();
}
ImGui::TextWrapped("And now some textured buttons..");
@@ -607,26 +612,103 @@ void ImGui::ShowDemoWindow(bool* p_open)
ImGui::TreePop();
}
+ if (ImGui::TreeNode("Combo"))
+ {
+ // Expose flags as checkbox for the demo
+ static ImGuiComboFlags flags = 0;
+ ImGui::CheckboxFlags("ImGuiComboFlags_PopupAlignLeft", (unsigned int*)&flags, ImGuiComboFlags_PopupAlignLeft);
+ if (ImGui::CheckboxFlags("ImGuiComboFlags_NoArrowButton", (unsigned int*)&flags, ImGuiComboFlags_NoArrowButton))
+ flags &= ~ImGuiComboFlags_NoPreview; // Clear the other flag, as we cannot combine both
+ if (ImGui::CheckboxFlags("ImGuiComboFlags_NoPreview", (unsigned int*)&flags, ImGuiComboFlags_NoPreview))
+ flags &= ~ImGuiComboFlags_NoArrowButton; // Clear the other flag, as we cannot combine both
+
+ // General BeginCombo() API, you have full control over your selection data and display type.
+ // (your selection data could be an index, a pointer to the object, an id for the object, a flag stored in the object itself, etc.)
+ const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" };
+ static const char* item_current = items[0]; // Here our selection is a single pointer stored outside the object.
+ if (ImGui::BeginCombo("combo 1", item_current, flags)) // The second parameter is the label previewed before opening the combo.
+ {
+ for (int n = 0; n < IM_ARRAYSIZE(items); n++)
+ {
+ bool is_selected = (item_current == items[n]);
+ if (ImGui::Selectable(items[n], is_selected))
+ item_current = items[n];
+ if (is_selected)
+ ImGui::SetItemDefaultFocus(); // Set the initial focus when opening the combo (scrolling + for keyboard navigation support in the upcoming navigation branch)
+ }
+ ImGui::EndCombo();
+ }
+
+ // Simplified one-liner Combo() API, using values packed in a single constant string
+ static int item_current_2 = 0;
+ ImGui::Combo("combo 2 (one-liner)", &item_current_2, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0");
+
+ // Simplified one-liner Combo() using an array of const char*
+ static int item_current_3 = -1; // If the selection isn't within 0..count, Combo won't display a preview
+ ImGui::Combo("combo 3 (array)", &item_current_3, items, IM_ARRAYSIZE(items));
+
+ // Simplified one-liner Combo() using an accessor function
+ struct FuncHolder { static bool ItemGetter(void* data, int idx, const char** out_str) { *out_str = ((const char**)data)[idx]; return true; } };
+ static int item_current_4 = 0;
+ ImGui::Combo("combo 4 (function)", &item_current_4, &FuncHolder::ItemGetter, items, IM_ARRAYSIZE(items));
+
+ ImGui::TreePop();
+ }
+
if (ImGui::TreeNode("Selectables"))
{
+ // Selectable() has 2 overloads:
+ // - The one taking "bool selected" as a read-only selection information. When Selectable() has been clicked is returns true and you can alter selection state accordingly.
+ // - The one taking "bool* p_selected" as a read-write selection information (convenient in some cases)
+ // The earlier is more flexible, as in real application your selection may be stored in a different manner (in flags within objects, as an external list, etc).
if (ImGui::TreeNode("Basic"))
{
- static bool selected[4] = { false, true, false, false };
- ImGui::Selectable("1. I am selectable", &selected[0]);
- ImGui::Selectable("2. I am selectable", &selected[1]);
+ static bool selection[5] = { false, true, false, false, false };
+ ImGui::Selectable("1. I am selectable", &selection[0]);
+ ImGui::Selectable("2. I am selectable", &selection[1]);
ImGui::Text("3. I am not selectable");
- ImGui::Selectable("4. I am selectable", &selected[2]);
- if (ImGui::Selectable("5. I am double clickable", selected[3], ImGuiSelectableFlags_AllowDoubleClick))
+ ImGui::Selectable("4. I am selectable", &selection[3]);
+ if (ImGui::Selectable("5. I am double clickable", selection[4], ImGuiSelectableFlags_AllowDoubleClick))
if (ImGui::IsMouseDoubleClicked(0))
- selected[3] = !selected[3];
+ selection[4] = !selection[4];
ImGui::TreePop();
}
- if (ImGui::TreeNode("Rendering more text into the same block"))
+ if (ImGui::TreeNode("Selection State: Single Selection"))
{
+ static int selected = -1;
+ for (int n = 0; n < 5; n++)
+ {
+ char buf[32];
+ sprintf(buf, "Object %d", n);
+ if (ImGui::Selectable(buf, selected == n))
+ selected = n;
+ }
+ ImGui::TreePop();
+ }
+ if (ImGui::TreeNode("Selection State: Multiple Selection"))
+ {
+ ShowHelpMarker("Hold CTRL and click to select multiple items.");
+ static bool selection[5] = { false, false, false, false, false };
+ for (int n = 0; n < 5; n++)
+ {
+ char buf[32];
+ sprintf(buf, "Object %d", n);
+ if (ImGui::Selectable(buf, selection[n]))
+ {
+ if (!ImGui::GetIO().KeyCtrl) // Clear selection when CTRL is not held
+ memset(selection, 0, sizeof(selection));
+ selection[n] ^= 1;
+ }
+ }
+ ImGui::TreePop();
+ }
+ if (ImGui::TreeNode("Rendering more text into the same line"))
+ {
+ // Using the Selectable() override that takes "bool* p_selected" parameter and toggle your booleans automatically.
static bool selected[3] = { false, false, false };
- ImGui::Selectable("main.c", &selected[0]); ImGui::SameLine(300); ImGui::Text(" 2,345 bytes");
+ ImGui::Selectable("main.c", &selected[0]); ImGui::SameLine(300); ImGui::Text(" 2,345 bytes");
ImGui::Selectable("Hello.cpp", &selected[1]); ImGui::SameLine(300); ImGui::Text("12,345 bytes");
- ImGui::Selectable("Hello.h", &selected[2]); ImGui::SameLine(300); ImGui::Text(" 2,345 bytes");
+ ImGui::Selectable("Hello.h", &selected[2]); ImGui::SameLine(300); ImGui::Text(" 2,345 bytes");
ImGui::TreePop();
}
if (ImGui::TreeNode("In columns"))
@@ -773,14 +855,14 @@ void ImGui::ShowDemoWindow(bool* p_open)
{
static ImVec4 color = ImColor(114, 144, 154, 200);
- static bool hdr = false;
static bool alpha_preview = true;
static bool alpha_half_preview = false;
static bool options_menu = true;
- ImGui::Checkbox("With HDR", &hdr); ImGui::SameLine(); ShowHelpMarker("Currently all this does is to lift the 0..1 limits on dragging widgets.");
+ static bool hdr = false;
ImGui::Checkbox("With Alpha Preview", &alpha_preview);
ImGui::Checkbox("With Half Alpha Preview", &alpha_half_preview);
ImGui::Checkbox("With Options Menu", &options_menu); ImGui::SameLine(); ShowHelpMarker("Right-click on the individual color widget to show options.");
+ ImGui::Checkbox("With HDR", &hdr); ImGui::SameLine(); ShowHelpMarker("Currently all this does is to lift the 0..1 limits on dragging widgets.");
int misc_flags = (hdr ? ImGuiColorEditFlags_HDR : 0) | (alpha_half_preview ? ImGuiColorEditFlags_AlphaPreviewHalf : (alpha_preview ? ImGuiColorEditFlags_AlphaPreview : 0)) | (options_menu ? 0 : ImGuiColorEditFlags_NoOptions);
ImGui::Text("Color widget:");
@@ -1017,9 +1099,10 @@ void ImGui::ShowDemoWindow(bool* p_open)
if (ImGui::TreeNode("Child regions"))
{
static bool disable_mouse_wheel = false;
+ static bool disable_menu = false;
ImGui::Checkbox("Disable Mouse Wheel", &disable_mouse_wheel);
+ ImGui::Checkbox("Disable Menu", &disable_menu);
- ImGui::Text("Without border");
static int line = 50;
bool goto_line = ImGui::Button("Goto");
ImGui::SameLine();
@@ -1027,33 +1110,47 @@ void ImGui::ShowDemoWindow(bool* p_open)
goto_line |= ImGui::InputInt("##Line", &line, 0, 0, ImGuiInputTextFlags_EnterReturnsTrue);
ImGui::PopItemWidth();
- ImGui::BeginChild("Sub1", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.5f,300), false, ImGuiWindowFlags_HorizontalScrollbar | (disable_mouse_wheel ? ImGuiWindowFlags_NoScrollWithMouse : 0));
- for (int i = 0; i < 100; i++)
+ // Child 1: no border, enable horizontal scrollbar
{
- ImGui::Text("%04d: scrollable region", i);
- if (goto_line && line == i)
+ ImGui::BeginChild("Child1", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.5f, 300), false, ImGuiWindowFlags_HorizontalScrollbar | (disable_mouse_wheel ? ImGuiWindowFlags_NoScrollWithMouse : 0));
+ for (int i = 0; i < 100; i++)
+ {
+ ImGui::Text("%04d: scrollable region", i);
+ if (goto_line && line == i)
+ ImGui::SetScrollHere();
+ }
+ if (goto_line && line >= 100)
ImGui::SetScrollHere();
+ ImGui::EndChild();
}
- if (goto_line && line >= 100)
- ImGui::SetScrollHere();
- ImGui::EndChild();
ImGui::SameLine();
- ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f);
- ImGui::BeginChild("Sub2", ImVec2(0,300), true, (disable_mouse_wheel ? ImGuiWindowFlags_NoScrollWithMouse : 0));
- ImGui::Text("With border");
- ImGui::Columns(2);
- for (int i = 0; i < 100; i++)
+ // Child 2: rounded border
{
- if (i == 50)
- ImGui::NextColumn();
- char buf[32];
- sprintf(buf, "%08x", i*5731);
- ImGui::Button(buf, ImVec2(-1.0f, 0.0f));
+ ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f);
+ ImGui::BeginChild("Child2", ImVec2(0,300), true, (disable_mouse_wheel ? ImGuiWindowFlags_NoScrollWithMouse : 0) | (disable_menu ? 0 : ImGuiWindowFlags_MenuBar));
+ if (!disable_menu && ImGui::BeginMenuBar())
+ {
+ if (ImGui::BeginMenu("Menu"))
+ {
+ ShowExampleMenuFile();
+ ImGui::EndMenu();
+ }
+ ImGui::EndMenuBar();
+ }
+ ImGui::Columns(2);
+ for (int i = 0; i < 100; i++)
+ {
+ if (i == 50)
+ ImGui::NextColumn();
+ char buf[32];
+ sprintf(buf, "%08x", i*5731);
+ ImGui::Button(buf, ImVec2(-1.0f, 0.0f));
+ }
+ ImGui::EndChild();
+ ImGui::PopStyleVar();
}
- ImGui::EndChild();
- ImGui::PopStyleVar();
ImGui::TreePop();
}
@@ -1361,8 +1458,8 @@ void ImGui::ShowDemoWindow(bool* p_open)
ImVec4 clip_rect(pos.x, pos.y, pos.x+size.x, pos.y+size.y);
ImGui::InvisibleButton("##dummy", size);
if (ImGui::IsItemActive() && ImGui::IsMouseDragging()) { offset.x += ImGui::GetIO().MouseDelta.x; offset.y += ImGui::GetIO().MouseDelta.y; }
- ImGui::GetWindowDrawList()->AddRectFilled(pos, ImVec2(pos.x+size.x,pos.y+size.y), ImColor(90,90,120,255));
- ImGui::GetWindowDrawList()->AddText(ImGui::GetFont(), ImGui::GetFontSize()*2.0f, ImVec2(pos.x+offset.x,pos.y+offset.y), ImColor(255,255,255,255), "Line 1 hello\nLine 2 clip me!", NULL, 0.0f, &clip_rect);
+ ImGui::GetWindowDrawList()->AddRectFilled(pos, ImVec2(pos.x+size.x,pos.y+size.y), IM_COL32(90,90,120,255));
+ ImGui::GetWindowDrawList()->AddText(ImGui::GetFont(), ImGui::GetFontSize()*2.0f, ImVec2(pos.x+offset.x,pos.y+offset.y), IM_COL32(255,255,255,255), "Line 1 hello\nLine 2 clip me!", NULL, 0.0f, &clip_rect);
ImGui::TreePop();
}
}
@@ -1481,7 +1578,7 @@ void ImGui::ShowDemoWindow(bool* p_open)
ImGui::OpenPopup("Delete?");
if (ImGui::BeginPopupModal("Delete?", NULL, ImGuiWindowFlags_AlwaysAutoResize))
{
- ImGui::Text("All those beautiful files will be deleted.\nThis operation cannot be undone!\n\n");
+ ImGui::Text("All those beautiful files will be deleted.\nThis operation cannot be undone!\n\n");
ImGui::Separator();
//static int dummy_i = 0;
@@ -1493,6 +1590,7 @@ void ImGui::ShowDemoWindow(bool* p_open)
ImGui::PopStyleVar();
if (ImGui::Button("OK", ImVec2(120,0))) { ImGui::CloseCurrentPopup(); }
+ ImGui::SetItemDefaultFocus();
ImGui::SameLine();
if (ImGui::Button("Cancel", ImVec2(120,0))) { ImGui::CloseCurrentPopup(); }
ImGui::EndPopup();
@@ -1512,7 +1610,7 @@ void ImGui::ShowDemoWindow(bool* p_open)
ImGui::OpenPopup("Stacked 2");
if (ImGui::BeginPopupModal("Stacked 2"))
{
- ImGui::Text("Hello from Stacked The Second");
+ ImGui::Text("Hello from Stacked The Second!");
if (ImGui::Button("Close"))
ImGui::CloseCurrentPopup();
ImGui::EndPopup();
@@ -1741,18 +1839,27 @@ void ImGui::ShowDemoWindow(bool* p_open)
ImGui::BulletText("%s", lines[i]);
}
- if (ImGui::CollapsingHeader("Inputs & Focus"))
+ if (ImGui::CollapsingHeader("Inputs, Navigation & Focus"))
{
ImGuiIO& io = ImGui::GetIO();
- ImGui::Checkbox("io.MouseDrawCursor", &io.MouseDrawCursor);
- ImGui::SameLine(); ShowHelpMarker("Request ImGui to render a mouse cursor for you in software. Note that a mouse cursor rendered via your application GPU rendering path will feel more laggy than hardware cursor, but will be more in sync with your other visuals.\n\nSome desktop applications may use both kinds of cursors (e.g. enable software cursor only when resizing/dragging something).");
ImGui::Text("WantCaptureMouse: %d", io.WantCaptureMouse);
ImGui::Text("WantCaptureKeyboard: %d", io.WantCaptureKeyboard);
ImGui::Text("WantTextInput: %d", io.WantTextInput);
- ImGui::Text("WantMoveMouse: %d", io.WantMoveMouse);
+ ImGui::Text("WantSetMousePos: %d", io.WantSetMousePos);
+ ImGui::Text("NavActive: %d, NavVisible: %d", io.NavActive, io.NavVisible);
+
+ ImGui::Checkbox("io.MouseDrawCursor", &io.MouseDrawCursor);
+ ImGui::SameLine(); ShowHelpMarker("Instruct ImGui to render a mouse cursor for you in software. Note that a mouse cursor rendered via your application GPU rendering path will feel more laggy than hardware cursor, but will be more in sync with your other visuals.\n\nSome desktop applications may use both kinds of cursors (e.g. enable software cursor only when resizing/dragging something).");
- if (ImGui::TreeNode("Keyboard & Mouse State"))
+ ImGui::CheckboxFlags("io.ConfigFlags: NavEnableGamepad", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NavEnableGamepad);
+ ImGui::CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard);
+ ImGui::CheckboxFlags("io.ConfigFlags: NavEnableSetMousePos", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NavEnableSetMousePos);
+ ImGui::SameLine(); ShowHelpMarker("Instruct navigation to move the mouse cursor. See comment for ImGuiConfigFlags_NavEnableSetMousePos.");
+ ImGui::CheckboxFlags("io.ConfigFlags: NoMouseCursorChange", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NoMouseCursorChange);
+ ImGui::SameLine(); ShowHelpMarker("Instruct back-end to not alter mouse cursor shape and visibility.");
+
+ if (ImGui::TreeNode("Keyboard, Mouse & Navigation State"))
{
if (ImGui::IsMousePosValid())
ImGui::Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
@@ -1769,6 +1876,9 @@ void ImGui::ShowDemoWindow(bool* p_open)
ImGui::Text("Keys release:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (ImGui::IsKeyReleased(i)) { ImGui::SameLine(); ImGui::Text("%d", i); }
ImGui::Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
+ ImGui::Text("NavInputs down:"); for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++) if (io.NavInputs[i] > 0.0f) { ImGui::SameLine(); ImGui::Text("[%d] %.2f", i, io.NavInputs[i]); }
+ ImGui::Text("NavInputs pressed:"); for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++) if (io.NavInputsDownDuration[i] == 0.0f) { ImGui::SameLine(); ImGui::Text("[%d]", i); }
+ ImGui::Text("NavInputs duration:"); for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++) if (io.NavInputsDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("[%d] %.2f", i, io.NavInputsDownDuration[i]); }
ImGui::Button("Hovering me sets the\nkeyboard capture flag");
if (ImGui::IsItemHovered())
@@ -1817,11 +1927,22 @@ void ImGui::ShowDemoWindow(bool* p_open)
ImGui::InputText("3 (tab skip)", buf, IM_ARRAYSIZE(buf));
if (ImGui::IsItemActive()) has_focus = 3;
ImGui::PopAllowKeyboardFocus();
+
if (has_focus)
ImGui::Text("Item with focus: %d", has_focus);
else
ImGui::Text("Item with focus: <none>");
- ImGui::TextWrapped("Cursor & selection are preserved when refocusing last used item in code.");
+
+ // Use >= 0 parameter to SetKeyboardFocusHere() to focus an upcoming item
+ static float f3[3] = { 0.0f, 0.0f, 0.0f };
+ int focus_ahead = -1;
+ if (ImGui::Button("Focus on X")) focus_ahead = 0; ImGui::SameLine();
+ if (ImGui::Button("Focus on Y")) focus_ahead = 1; ImGui::SameLine();
+ if (ImGui::Button("Focus on Z")) focus_ahead = 2;
+ if (focus_ahead != -1) ImGui::SetKeyboardFocusHere(focus_ahead);
+ ImGui::SliderFloat3("Float3", &f3[0], 0.0f, 1.0f);
+
+ ImGui::TextWrapped("NB: Cursor & selection are preserved when refocusing last used item in code.");
ImGui::TreePop();
}
@@ -1837,11 +1958,13 @@ void ImGui::ShowDemoWindow(bool* p_open)
"IsWindowFocused() = %d\n"
"IsWindowFocused(_ChildWindows) = %d\n"
"IsWindowFocused(_ChildWindows|_RootWindow) = %d\n"
- "IsWindowFocused(_RootWindow) = %d\n",
+ "IsWindowFocused(_RootWindow) = %d\n"
+ "IsWindowFocused(_AnyWindow) = %d\n",
ImGui::IsWindowFocused(),
- ImGui::IsWindowFocused(ImGuiHoveredFlags_ChildWindows),
- ImGui::IsWindowFocused(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow),
- ImGui::IsWindowFocused(ImGuiHoveredFlags_RootWindow));
+ ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows),
+ ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_RootWindow),
+ ImGui::IsWindowFocused(ImGuiFocusedFlags_RootWindow),
+ ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow));
// Testing IsWindowHovered() function with its various flags (note that the flags can be combined)
ImGui::BulletText(
@@ -1850,13 +1973,15 @@ void ImGui::ShowDemoWindow(bool* p_open)
"IsWindowHovered(_AllowWhenBlockedByActiveItem) = %d\n"
"IsWindowHovered(_ChildWindows) = %d\n"
"IsWindowHovered(_ChildWindows|_RootWindow) = %d\n"
- "IsWindowHovered(_RootWindow) = %d\n",
+ "IsWindowHovered(_RootWindow) = %d\n"
+ "IsWindowHovered(_AnyWindow) = %d\n",
ImGui::IsWindowHovered(),
ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup),
ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem),
ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows),
ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow),
- ImGui::IsWindowHovered(ImGuiHoveredFlags_RootWindow));
+ ImGui::IsWindowHovered(ImGuiHoveredFlags_RootWindow),
+ ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow));
// Testing IsItemHovered() function (because BulletText is an item itself and that would affect the output of IsItemHovered, we pass all lines in a single items to shorten the code)
ImGui::Button("ITEM");
@@ -1894,7 +2019,7 @@ void ImGui::ShowDemoWindow(bool* p_open)
// Draw a line between the button and the mouse cursor
ImDrawList* draw_list = ImGui::GetWindowDrawList();
draw_list->PushClipRectFullScreen();
- draw_list->AddLine(ImGui::CalcItemRectClosestPoint(io.MousePos, true, -2.0f), io.MousePos, ImColor(ImGui::GetStyle().Colors[ImGuiCol_Button]), 4.0f);
+ draw_list->AddLine(io.MouseClickedPos[0], io.MousePos, ImGui::GetColorU32(ImGuiCol_Button), 4.0f);
draw_list->PopClipRect();
// Drag operations gets "unlocked" when the mouse has moved past a certain threshold (the default threshold is stored in io.MouseDragThreshold)
@@ -1910,17 +2035,17 @@ void ImGui::ShowDemoWindow(bool* p_open)
if (ImGui::TreeNode("Mouse cursors"))
{
const char* mouse_cursors_names[] = { "Arrow", "TextInput", "Move", "ResizeNS", "ResizeEW", "ResizeNESW", "ResizeNWSE" };
- IM_ASSERT(IM_ARRAYSIZE(mouse_cursors_names) == ImGuiMouseCursor_Count_);
+ IM_ASSERT(IM_ARRAYSIZE(mouse_cursors_names) == ImGuiMouseCursor_COUNT);
ImGui::Text("Current mouse cursor = %d: %s", ImGui::GetMouseCursor(), mouse_cursors_names[ImGui::GetMouseCursor()]);
ImGui::Text("Hover to see mouse cursors:");
ImGui::SameLine(); ShowHelpMarker("Your application can render a different mouse cursor based on what ImGui::GetMouseCursor() returns. If software cursor rendering (io.MouseDrawCursor) is set ImGui will draw the right cursor for you, otherwise your backend needs to handle it.");
- for (int i = 0; i < ImGuiMouseCursor_Count_; i++)
+ for (int i = 0; i < ImGuiMouseCursor_COUNT; i++)
{
char label[32];
sprintf(label, "Mouse cursor %d: %s", i, mouse_cursors_names[i]);
ImGui::Bullet(); ImGui::Selectable(label, false);
- if (ImGui::IsItemHovered())
+ if (ImGui::IsItemHovered() || ImGui::IsItemFocused())
ImGui::SetMouseCursor(i);
}
ImGui::TreePop();
@@ -1934,7 +2059,7 @@ void ImGui::ShowDemoWindow(bool* p_open)
// Here we use the simplified Combo() api that packs items into a single literal string. Useful for quick combo boxes where the choices are known locally.
bool ImGui::ShowStyleSelector(const char* label)
{
- static int style_idx = 0;
+ static int style_idx = -1;
if (ImGui::Combo(label, &style_idx, "Classic\0Dark\0Light\0"))
{
switch (style_idx)
@@ -1965,7 +2090,7 @@ void ImGui::ShowFontSelector(const char* label)
ShowHelpMarker(
"- Load additional fonts with io.Fonts->AddFontFromFileTTF().\n"
"- The font atlas is built when calling io.Fonts->GetTexDataAsXXXX() or io.Fonts->Build().\n"
- "- Read FAQ and documentation in extra_fonts/ for more details.\n"
+ "- Read FAQ and documentation in misc/fonts/ for more details.\n"
"- If you need to add/remove fonts at runtime (e.g. for DPI change), do it before calling NewFrame().");
}
@@ -2080,7 +2205,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref)
ImGui::RadioButton("Alpha", &alpha_flags, ImGuiColorEditFlags_AlphaPreview); ImGui::SameLine();
ImGui::RadioButton("Both", &alpha_flags, ImGuiColorEditFlags_AlphaPreviewHalf);
- ImGui::BeginChild("#colors", ImVec2(0, 300), true, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
+ ImGui::BeginChild("#colors", ImVec2(0, 300), true, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar | ImGuiWindowFlags_NavFlattened);
ImGui::PushItemWidth(-160);
for (int i = 0; i < ImGuiCol_COUNT; i++)
{
@@ -2092,7 +2217,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref)
if (memcmp(&style.Colors[i], &ref->Colors[i], sizeof(ImVec4)) != 0)
{
// Tips: in a real user application, you may want to merge and use an icon font into the main font, so instead of "Save"/"Revert" you'd use icons.
- // Read the FAQ and extra_fonts/README.txt about using icon fonts. It's really easy and super convenient!
+ // Read the FAQ and misc/fonts/README.txt about using icon fonts. It's really easy and super convenient!
ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); if (ImGui::Button("Save")) ref->Colors[i] = style.Colors[i];
ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); if (ImGui::Button("Revert")) style.Colors[i] = ref->Colors[i];
}
@@ -2128,38 +2253,35 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref)
ImGui::Text("The quick brown fox jumps over the lazy dog");
ImGui::PopFont();
ImGui::DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f"); // Scale only this font
+ ImGui::InputFloat("Font offset", &font->DisplayOffset.y, 1, 1, 0);
ImGui::SameLine(); ShowHelpMarker("Note than the default embedded font is NOT meant to be scaled.\n\nFont are currently rendered into bitmaps at a given size at the time of building the atlas. You may oversample them to get some flexibility with scaling. You can also render at multiple sizes and select which one to use at runtime.\n\n(Glimmer of hope: the atlas system should hopefully be rewritten in the future to make scaling more natural and automatic.)");
ImGui::Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
ImGui::Text("Fallback character: '%c' (%d)", font->FallbackChar, font->FallbackChar);
ImGui::Text("Texture surface: %d pixels (approx) ~ %dx%d", font->MetricsTotalSurface, (int)sqrtf((float)font->MetricsTotalSurface), (int)sqrtf((float)font->MetricsTotalSurface));
for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
- {
- ImFontConfig* cfg = &font->ConfigData[config_i];
- ImGui::BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d", config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH);
- }
+ if (ImFontConfig* cfg = &font->ConfigData[config_i])
+ ImGui::BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d", config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH);
if (ImGui::TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
{
// Display all glyphs of the fonts in separate pages of 256 characters
- const ImFontGlyph* glyph_fallback = font->FallbackGlyph; // Forcefully/dodgily make FindGlyph() return NULL on fallback, which isn't the default behavior.
- font->FallbackGlyph = NULL;
for (int base = 0; base < 0x10000; base += 256)
{
int count = 0;
for (int n = 0; n < 256; n++)
- count += font->FindGlyph((ImWchar)(base + n)) ? 1 : 0;
+ count += font->FindGlyphNoFallback((ImWchar)(base + n)) ? 1 : 0;
if (count > 0 && ImGui::TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base+255, count, count > 1 ? "glyphs" : "glyph"))
{
+ float cell_size = font->FontSize * 1;
float cell_spacing = style.ItemSpacing.y;
- ImVec2 cell_size(font->FontSize * 1, font->FontSize * 1);
ImVec2 base_pos = ImGui::GetCursorScreenPos();
ImDrawList* draw_list = ImGui::GetWindowDrawList();
for (int n = 0; n < 256; n++)
{
- ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size.x + cell_spacing), base_pos.y + (n / 16) * (cell_size.y + cell_spacing));
- ImVec2 cell_p2(cell_p1.x + cell_size.x, cell_p1.y + cell_size.y);
- const ImFontGlyph* glyph = font->FindGlyph((ImWchar)(base+n));;
+ ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
+ ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
+ const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base+n));
draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255,255,255,100) : IM_COL32(255,255,255,50));
- font->RenderChar(draw_list, cell_size.x, cell_p1, ImGui::GetColorU32(ImGuiCol_Text), (ImWchar)(base+n)); // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions available to generate a string.
+ font->RenderChar(draw_list, cell_size, cell_p1, ImGui::GetColorU32(ImGuiCol_Text), (ImWchar)(base+n)); // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions available to generate a string.
if (glyph && ImGui::IsMouseHoveringRect(cell_p1, cell_p2))
{
ImGui::BeginTooltip();
@@ -2171,11 +2293,10 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref)
ImGui::EndTooltip();
}
}
- ImGui::Dummy(ImVec2((cell_size.x + cell_spacing) * 16, (cell_size.y + cell_spacing) * 16));
+ ImGui::Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
ImGui::TreePop();
}
}
- font->FallbackGlyph = glyph_fallback;
ImGui::TreePop();
}
ImGui::TreePop();
@@ -2262,15 +2383,16 @@ static void ShowExampleMenuFile()
}
if (ImGui::BeginMenu("Colors"))
{
- ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0,0));
+ float sz = ImGui::GetTextLineHeight();
for (int i = 0; i < ImGuiCol_COUNT; i++)
{
const char* name = ImGui::GetStyleColorName((ImGuiCol)i);
- ImGui::ColorButton(name, ImGui::GetStyleColorVec4((ImGuiCol)i));
+ ImVec2 p = ImGui::GetCursorScreenPos();
+ ImGui::GetWindowDrawList()->AddRectFilled(p, ImVec2(p.x+sz, p.y+sz), ImGui::GetColorU32((ImGuiCol)i));
+ ImGui::Dummy(ImVec2(sz, sz));
ImGui::SameLine();
ImGui::MenuItem(name);
}
- ImGui::PopStyleVar();
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Disabled", false)) // Disabled
@@ -2303,8 +2425,8 @@ static void ShowExampleAppConstrainedResize(bool* p_open)
{
struct CustomConstraints // Helper functions to demonstrate programmatic constraints
{
- static void Square(ImGuiSizeConstraintCallbackData* data) { data->DesiredSize = ImVec2(IM_MAX(data->DesiredSize.x, data->DesiredSize.y), IM_MAX(data->DesiredSize.x, data->DesiredSize.y)); }
- static void Step(ImGuiSizeConstraintCallbackData* data) { float step = (float)(int)(intptr_t)data->UserData; data->DesiredSize = ImVec2((int)(data->DesiredSize.x / step + 0.5f) * step, (int)(data->DesiredSize.y / step + 0.5f) * step); }
+ static void Square(ImGuiSizeCallbackData* data) { data->DesiredSize = ImVec2(IM_MAX(data->DesiredSize.x, data->DesiredSize.y), IM_MAX(data->DesiredSize.x, data->DesiredSize.y)); }
+ static void Step(ImGuiSizeCallbackData* data) { float step = (float)(int)(intptr_t)data->UserData; data->DesiredSize = ImVec2((int)(data->DesiredSize.x / step + 0.5f) * step, (int)(data->DesiredSize.y / step + 0.5f) * step); }
};
static bool auto_resize = false;
@@ -2353,8 +2475,8 @@ static void ShowExampleAppFixedOverlay(bool* p_open)
ImVec2 window_pos = ImVec2((corner & 1) ? ImGui::GetIO().DisplaySize.x - DISTANCE : DISTANCE, (corner & 2) ? ImGui::GetIO().DisplaySize.y - DISTANCE : DISTANCE);
ImVec2 window_pos_pivot = ImVec2((corner & 1) ? 1.0f : 0.0f, (corner & 2) ? 1.0f : 0.0f);
ImGui::SetNextWindowPos(window_pos, ImGuiCond_Always, window_pos_pivot);
- ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0.0f, 0.0f, 0.0f, 0.3f)); // Transparent background
- if (ImGui::Begin("Example: Fixed Overlay", p_open, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoSavedSettings))
+ ImGui::SetNextWindowBgAlpha(0.3f); // Transparent background
+ if (ImGui::Begin("Example: Fixed Overlay", p_open, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_NoFocusOnAppearing|ImGuiWindowFlags_NoNav))
{
ImGui::Text("Simple overlay\nin the corner of the screen.\n(right-click to change position)");
ImGui::Separator();
@@ -2365,11 +2487,11 @@ static void ShowExampleAppFixedOverlay(bool* p_open)
if (ImGui::MenuItem("Top-right", NULL, corner == 1)) corner = 1;
if (ImGui::MenuItem("Bottom-left", NULL, corner == 2)) corner = 2;
if (ImGui::MenuItem("Bottom-right", NULL, corner == 3)) corner = 3;
+ if (p_open && ImGui::MenuItem("Close")) *p_open = false;
ImGui::EndPopup();
}
ImGui::End();
}
- ImGui::PopStyleColor();
}
// Demonstrate using "##" and "###" in identifiers to manipulate ID generation.
@@ -2445,7 +2567,7 @@ static void ShowExampleAppCustomRendering(bool* p_open)
draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 10.0f); x += sz+spacing;
draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 10.0f, ImDrawCornerFlags_TopLeft|ImDrawCornerFlags_BotRight); x += sz+spacing;
draw_list->AddTriangleFilled(ImVec2(x+sz*0.5f, y), ImVec2(x+sz,y+sz-0.5f), ImVec2(x,y+sz-0.5f), col32); x += sz+spacing;
- draw_list->AddRectFilledMultiColor(ImVec2(x, y), ImVec2(x+sz, y+sz), ImColor(0,0,0), ImColor(255,0,0), ImColor(255,255,0), ImColor(0,255,0));
+ draw_list->AddRectFilledMultiColor(ImVec2(x, y), ImVec2(x+sz, y+sz), IM_COL32(0,0,0,255), IM_COL32(255,0,0,255), IM_COL32(255,255,0,255), IM_COL32(0,255,0,255));
ImGui::Dummy(ImVec2((sz+spacing)*8, (sz+spacing)*3));
}
ImGui::Separator();
@@ -2464,8 +2586,8 @@ static void ShowExampleAppCustomRendering(bool* p_open)
ImVec2 canvas_size = ImGui::GetContentRegionAvail(); // Resize canvas to what's available
if (canvas_size.x < 50.0f) canvas_size.x = 50.0f;
if (canvas_size.y < 50.0f) canvas_size.y = 50.0f;
- draw_list->AddRectFilledMultiColor(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), ImColor(50,50,50), ImColor(50,50,60), ImColor(60,60,70), ImColor(50,50,60));
- draw_list->AddRect(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), ImColor(255,255,255));
+ draw_list->AddRectFilledMultiColor(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), IM_COL32(50,50,50,255), IM_COL32(50,50,60,255), IM_COL32(60,60,70,255), IM_COL32(50,50,60,255));
+ draw_list->AddRect(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), IM_COL32(255,255,255,255));
bool adding_preview = false;
ImGui::InvisibleButton("canvas", canvas_size);
@@ -2474,7 +2596,7 @@ static void ShowExampleAppCustomRendering(bool* p_open)
{
adding_preview = true;
points.push_back(mouse_pos_in_canvas);
- if (!ImGui::GetIO().MouseDown[0])
+ if (!ImGui::IsMouseDown(0))
adding_line = adding_preview = false;
}
if (ImGui::IsItemHovered())
@@ -2616,12 +2738,13 @@ struct ExampleAppConsole
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4,1)); // Tighten spacing
if (copy_to_clipboard)
ImGui::LogToClipboard();
+ ImVec4 col_default_text = ImGui::GetStyleColorVec4(ImGuiCol_Text);
for (int i = 0; i < Items.Size; i++)
{
const char* item = Items[i];
if (!filter.PassFilter(item))
continue;
- ImVec4 col = ImVec4(1.0f,1.0f,1.0f,1.0f); // A better implementation may store a type per-item. For the sample let's just parse the text.
+ ImVec4 col = col_default_text;
if (strstr(item, "[error]")) col = ImColor(1.0f,0.4f,0.4f,1.0f);
else if (strncmp(item, "# ", 2) == 0) col = ImColor(1.0f,0.78f,0.58f,1.0f);
ImGui::PushStyleColor(ImGuiCol_Text, col);
@@ -2638,6 +2761,7 @@ struct ExampleAppConsole
ImGui::Separator();
// Command-line
+ bool reclaim_focus = false;
if (ImGui::InputText("Input", InputBuf, IM_ARRAYSIZE(InputBuf), ImGuiInputTextFlags_EnterReturnsTrue|ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_CallbackHistory, &TextEditCallbackStub, (void*)this))
{
char* input_end = InputBuf+strlen(InputBuf);
@@ -2645,10 +2769,12 @@ struct ExampleAppConsole
if (InputBuf[0])
ExecCommand(InputBuf);
strcpy(InputBuf, "");
+ reclaim_focus = true;
}
- // Demonstrate keeping auto focus on the input box
- if (ImGui::IsItemHovered() || (ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) && !ImGui::IsAnyItemActive() && !ImGui::IsMouseClicked(0)))
+ // Demonstrate keeping focus on the input box
+ ImGui::SetItemDefaultFocus();
+ if (reclaim_focus)
ImGui::SetKeyboardFocusHere(-1); // Auto focus previous widget
ImGui::End();
diff --git a/imgui/imgui_draw.cpp b/imgui/imgui_draw.cpp
index 6efb6bc6..2606c1af 100644
--- a/imgui/imgui_draw.cpp
+++ b/imgui/imgui_draw.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.53
+// dear imgui, v1.60
// (drawing and font code)
// Contains implementation for
@@ -34,7 +34,6 @@
#ifdef _MSC_VER
#pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff)
#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
-#define snprintf _snprintf
#endif
#ifdef __clang__
@@ -42,7 +41,9 @@
#pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants ok.
#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 //
+#if __has_warning("-Wcomma")
#pragma clang diagnostic ignored "-Wcomma" // warning : possible misuse of comma operator here //
+#endif
#if __has_warning("-Wreserved-id-macro")
#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning : macro name is a reserved identifier //
#endif
@@ -53,16 +54,18 @@
#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
-#pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'xxxx' to type 'xxxx' casts away qualifiers
#endif
//-------------------------------------------------------------------------
// STB libraries implementation
//-------------------------------------------------------------------------
-//#define IMGUI_STB_NAMESPACE ImGuiStb
-//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION
+// Compile time options:
+//#define IMGUI_STB_NAMESPACE ImGuiStb
+//#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h"
+//#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h"
//#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION
+//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION
#ifdef IMGUI_STB_NAMESPACE
namespace IMGUI_STB_NAMESPACE
@@ -79,30 +82,40 @@ namespace IMGUI_STB_NAMESPACE
#pragma clang diagnostic ignored "-Wunused-function"
#pragma clang diagnostic ignored "-Wmissing-prototypes"
#pragma clang diagnostic ignored "-Wimplicit-fallthrough"
+#pragma clang diagnostic ignored "-Wcast-qual" // warning : cast from 'const xxxx *' to 'xxx *' drops const qualifier //
#endif
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wtype-limits" // warning: comparison is always true due to limited range of data type [-Wtype-limits]
+#pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers
#endif
-#define STBRP_ASSERT(x) IM_ASSERT(x)
#ifndef IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION
#define STBRP_STATIC
+#define STBRP_ASSERT(x) IM_ASSERT(x)
#define STB_RECT_PACK_IMPLEMENTATION
#endif
+#ifdef IMGUI_STB_RECT_PACK_FILENAME
+#include IMGUI_STB_RECT_PACK_FILENAME
+#else
#include "stb_rect_pack.h"
+#endif
+#ifndef IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION
#define STBTT_malloc(x,u) ((void)(u), ImGui::MemAlloc(x))
#define STBTT_free(x,u) ((void)(u), ImGui::MemFree(x))
#define STBTT_assert(x) IM_ASSERT(x)
-#ifndef IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION
#define STBTT_STATIC
#define STB_TRUETYPE_IMPLEMENTATION
#else
#define STBTT_DEF extern
#endif
+#ifdef IMGUI_STB_TRUETYPE_FILENAME
+#include IMGUI_STB_TRUETYPE_FILENAME
+#else
#include "stb_truetype.h"
+#endif
#ifdef __GNUC__
#pragma GCC diagnostic pop
@@ -125,6 +138,55 @@ using namespace IMGUI_STB_NAMESPACE;
// Style functions
//-----------------------------------------------------------------------------
+void ImGui::StyleColorsDark(ImGuiStyle* dst)
+{
+ ImGuiStyle* style = dst ? dst : &ImGui::GetStyle();
+ ImVec4* colors = style->Colors;
+
+ colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
+ colors[ImGuiCol_TextDisabled] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f);
+ colors[ImGuiCol_WindowBg] = ImVec4(0.06f, 0.06f, 0.06f, 0.94f);
+ colors[ImGuiCol_ChildBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.00f);
+ colors[ImGuiCol_PopupBg] = ImVec4(0.08f, 0.08f, 0.08f, 0.94f);
+ colors[ImGuiCol_Border] = ImVec4(0.43f, 0.43f, 0.50f, 0.50f);
+ colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
+ colors[ImGuiCol_FrameBg] = ImVec4(0.16f, 0.29f, 0.48f, 0.54f);
+ colors[ImGuiCol_FrameBgHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f);
+ colors[ImGuiCol_FrameBgActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f);
+ colors[ImGuiCol_TitleBg] = ImVec4(0.04f, 0.04f, 0.04f, 1.00f);
+ colors[ImGuiCol_TitleBgActive] = ImVec4(0.16f, 0.29f, 0.48f, 1.00f);
+ colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.00f, 0.00f, 0.00f, 0.51f);
+ colors[ImGuiCol_MenuBarBg] = ImVec4(0.14f, 0.14f, 0.14f, 1.00f);
+ colors[ImGuiCol_ScrollbarBg] = ImVec4(0.02f, 0.02f, 0.02f, 0.53f);
+ colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f);
+ colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.41f, 0.41f, 0.41f, 1.00f);
+ colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.51f, 0.51f, 0.51f, 1.00f);
+ colors[ImGuiCol_CheckMark] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
+ colors[ImGuiCol_SliderGrab] = ImVec4(0.24f, 0.52f, 0.88f, 1.00f);
+ colors[ImGuiCol_SliderGrabActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
+ colors[ImGuiCol_Button] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f);
+ colors[ImGuiCol_ButtonHovered] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
+ colors[ImGuiCol_ButtonActive] = ImVec4(0.06f, 0.53f, 0.98f, 1.00f);
+ colors[ImGuiCol_Header] = ImVec4(0.26f, 0.59f, 0.98f, 0.31f);
+ colors[ImGuiCol_HeaderHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.80f);
+ colors[ImGuiCol_HeaderActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
+ colors[ImGuiCol_Separator] = colors[ImGuiCol_Border];
+ colors[ImGuiCol_SeparatorHovered] = ImVec4(0.10f, 0.40f, 0.75f, 0.78f);
+ colors[ImGuiCol_SeparatorActive] = ImVec4(0.10f, 0.40f, 0.75f, 1.00f);
+ colors[ImGuiCol_ResizeGrip] = ImVec4(0.26f, 0.59f, 0.98f, 0.25f);
+ colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f);
+ colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f);
+ colors[ImGuiCol_PlotLines] = ImVec4(0.61f, 0.61f, 0.61f, 1.00f);
+ colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f);
+ colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
+ colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f);
+ colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f);
+ colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.80f, 0.80f, 0.80f, 0.35f);
+ colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f);
+ colors[ImGuiCol_NavHighlight] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
+ colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f);
+}
+
void ImGui::StyleColorsClassic(ImGuiStyle* dst)
{
ImGuiStyle* style = dst ? dst : &ImGui::GetStyle();
@@ -163,9 +225,6 @@ void ImGui::StyleColorsClassic(ImGuiStyle* dst)
colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.16f);
colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.78f, 0.82f, 1.00f, 0.60f);
colors[ImGuiCol_ResizeGripActive] = ImVec4(0.78f, 0.82f, 1.00f, 0.90f);
- colors[ImGuiCol_CloseButton] = ImVec4(0.50f, 0.50f, 0.90f, 0.50f);
- colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.70f, 0.70f, 0.90f, 0.60f);
- colors[ImGuiCol_CloseButtonActive] = ImVec4(0.70f, 0.70f, 0.70f, 1.00f);
colors[ImGuiCol_PlotLines] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
@@ -173,56 +232,8 @@ void ImGui::StyleColorsClassic(ImGuiStyle* dst)
colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f);
colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f);
colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f);
-}
-
-void ImGui::StyleColorsDark(ImGuiStyle* dst)
-{
- ImGuiStyle* style = dst ? dst : &ImGui::GetStyle();
- ImVec4* colors = style->Colors;
-
- colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
- colors[ImGuiCol_TextDisabled] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f);
- colors[ImGuiCol_WindowBg] = ImVec4(0.06f, 0.06f, 0.06f, 0.94f);
- colors[ImGuiCol_ChildBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.00f);
- colors[ImGuiCol_PopupBg] = ImVec4(0.08f, 0.08f, 0.08f, 0.94f);
- colors[ImGuiCol_Border] = ImVec4(0.43f, 0.43f, 0.50f, 0.50f);
- colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
- colors[ImGuiCol_FrameBg] = ImVec4(0.16f, 0.29f, 0.48f, 0.54f);
- colors[ImGuiCol_FrameBgHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f);
- colors[ImGuiCol_FrameBgActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f);
- colors[ImGuiCol_TitleBg] = ImVec4(0.04f, 0.04f, 0.04f, 1.00f);
- colors[ImGuiCol_TitleBgActive] = ImVec4(0.16f, 0.29f, 0.48f, 1.00f);
- colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.00f, 0.00f, 0.00f, 0.51f);
- colors[ImGuiCol_MenuBarBg] = ImVec4(0.14f, 0.14f, 0.14f, 1.00f);
- colors[ImGuiCol_ScrollbarBg] = ImVec4(0.02f, 0.02f, 0.02f, 0.53f);
- colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f);
- colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.41f, 0.41f, 0.41f, 1.00f);
- colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.51f, 0.51f, 0.51f, 1.00f);
- colors[ImGuiCol_CheckMark] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
- colors[ImGuiCol_SliderGrab] = ImVec4(0.24f, 0.52f, 0.88f, 1.00f);
- colors[ImGuiCol_SliderGrabActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
- colors[ImGuiCol_Button] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f);
- colors[ImGuiCol_ButtonHovered] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
- colors[ImGuiCol_ButtonActive] = ImVec4(0.06f, 0.53f, 0.98f, 1.00f);
- colors[ImGuiCol_Header] = ImVec4(0.26f, 0.59f, 0.98f, 0.31f);
- colors[ImGuiCol_HeaderHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.80f);
- colors[ImGuiCol_HeaderActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
- colors[ImGuiCol_Separator] = colors[ImGuiCol_Border];//ImVec4(0.61f, 0.61f, 0.61f, 1.00f);
- colors[ImGuiCol_SeparatorHovered] = ImVec4(0.10f, 0.40f, 0.75f, 0.78f);
- colors[ImGuiCol_SeparatorActive] = ImVec4(0.10f, 0.40f, 0.75f, 1.00f);
- colors[ImGuiCol_ResizeGrip] = ImVec4(0.26f, 0.59f, 0.98f, 0.25f);
- colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f);
- colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f);
- colors[ImGuiCol_CloseButton] = ImVec4(0.41f, 0.41f, 0.41f, 0.50f);
- colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.98f, 0.39f, 0.36f, 1.00f);
- colors[ImGuiCol_CloseButtonActive] = ImVec4(0.98f, 0.39f, 0.36f, 1.00f);
- colors[ImGuiCol_PlotLines] = ImVec4(0.61f, 0.61f, 0.61f, 1.00f);
- colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f);
- colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
- colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f);
- colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f);
- colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.80f, 0.80f, 0.80f, 0.35f);
- colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f);
+ colors[ImGuiCol_NavHighlight] = colors[ImGuiCol_HeaderHovered];
+ colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f);
}
// Those light colors are better suited with a thicker font than the default one + FrameBorder
@@ -266,9 +277,6 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst)
colors[ImGuiCol_ResizeGrip] = ImVec4(0.80f, 0.80f, 0.80f, 0.56f);
colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f);
colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f);
- colors[ImGuiCol_CloseButton] = ImVec4(0.59f, 0.59f, 0.59f, 0.50f);
- colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.98f, 0.39f, 0.36f, 1.00f);
- colors[ImGuiCol_CloseButtonActive] = ImVec4(0.98f, 0.39f, 0.36f, 1.00f);
colors[ImGuiCol_PlotLines] = ImVec4(0.39f, 0.39f, 0.39f, 1.00f);
colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f);
colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
@@ -276,6 +284,8 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst)
colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f);
colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f);
colors[ImGuiCol_DragDropTarget] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f);
+ colors[ImGuiCol_NavHighlight] = colors[ImGuiCol_HeaderHovered];
+ colors[ImGuiCol_NavWindowingHighlight] = ImVec4(0.70f, 0.70f, 0.70f, 0.70f);
}
//-----------------------------------------------------------------------------
@@ -340,6 +350,16 @@ void ImDrawList::ClearFreeMemory()
_Channels.clear();
}
+ImDrawList* ImDrawList::CloneOutput() const
+{
+ ImDrawList* dst = IM_NEW(ImDrawList(NULL));
+ dst->CmdBuffer = CmdBuffer;
+ dst->IdxBuffer = IdxBuffer;
+ dst->VtxBuffer = VtxBuffer;
+ dst->Flags = Flags;
+ return dst;
+}
+
// Using macros because C++ is a terrible language, we want guaranteed inline, no code in header, and no overhead in Debug builds
#define GetCurrentClipRect() (_ClipRectStack.Size ? _ClipRectStack.Data[_ClipRectStack.Size-1] : _Data->ClipRectFullscreen)
#define GetCurrentTextureId() (_TextureIdStack.Size ? _TextureIdStack.Data[_TextureIdStack.Size-1] : NULL)
@@ -442,7 +462,7 @@ void ImDrawList::PopClipRect()
UpdateClipRect();
}
-void ImDrawList::PushTextureID(const ImTextureID& texture_id)
+void ImDrawList::PushTextureID(ImTextureID texture_id)
{
_TextureIdStack.push_back(texture_id);
UpdateTextureID();
@@ -974,7 +994,10 @@ void ImDrawList::AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float roun
{
if ((col & IM_COL32_A_MASK) == 0)
return;
- PathRect(a + ImVec2(0.5f,0.5f), b - ImVec2(0.5f,0.5f), rounding, rounding_corners_flags);
+ if (Flags & ImDrawListFlags_AntiAliasedLines)
+ PathRect(a + ImVec2(0.5f,0.5f), b - ImVec2(0.50f,0.50f), rounding, rounding_corners_flags);
+ else
+ PathRect(a + ImVec2(0.5f,0.5f), b - ImVec2(0.49f,0.49f), rounding, rounding_corners_flags); // Better looking lower-right corner and rounded non-AA shapes.
PathStroke(col, true, thickness);
}
@@ -1338,28 +1361,30 @@ static const char FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[FONT_ATLAS_DEFAULT_TEX_DATA
" - XX XX - "
};
-static const ImVec2 FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[ImGuiMouseCursor_Count_][3] =
+static const ImVec2 FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[ImGuiMouseCursor_COUNT][3] =
{
// Pos ........ Size ......... Offset ......
{ ImVec2(0,3), ImVec2(12,19), ImVec2( 0, 0) }, // ImGuiMouseCursor_Arrow
{ ImVec2(13,0), ImVec2(7,16), ImVec2( 4, 8) }, // ImGuiMouseCursor_TextInput
- { ImVec2(31,0), ImVec2(23,23), ImVec2(11,11) }, // ImGuiMouseCursor_Move
+ { ImVec2(31,0), ImVec2(23,23), ImVec2(11,11) }, // ImGuiMouseCursor_ResizeAll
{ ImVec2(21,0), ImVec2( 9,23), ImVec2( 5,11) }, // ImGuiMouseCursor_ResizeNS
{ ImVec2(55,18),ImVec2(23, 9), ImVec2(11, 5) }, // ImGuiMouseCursor_ResizeEW
{ ImVec2(73,0), ImVec2(17,17), ImVec2( 9, 9) }, // ImGuiMouseCursor_ResizeNESW
{ ImVec2(55,0), ImVec2(17,17), ImVec2( 9, 9) }, // ImGuiMouseCursor_ResizeNWSE
};
-
ImFontAtlas::ImFontAtlas()
{
+ Flags = 0x00;
TexID = NULL;
TexDesiredWidth = 0;
TexGlyphPadding = 1;
+
TexPixelsAlpha8 = NULL;
TexPixelsRGBA32 = NULL;
TexWidth = TexHeight = 0;
- TexUvWhitePixel = ImVec2(0, 0);
+ TexUvScale = ImVec2(0.0f, 0.0f);
+ TexUvWhitePixel = ImVec2(0.0f, 0.0f);
for (int n = 0; n < IM_ARRAYSIZE(CustomRectIds); n++)
CustomRectIds[n] = -1;
}
@@ -1378,7 +1403,7 @@ void ImFontAtlas::ClearInputData()
ConfigData[i].FontData = NULL;
}
- // When clearing this we lose access to the font name and other information used to build the font.
+ // When clearing this we lose access to the font name and other information used to build the font.
for (int i = 0; i < Fonts.Size; i++)
if (Fonts[i]->ConfigData >= ConfigData.Data && Fonts[i]->ConfigData < ConfigData.Data + ConfigData.Size)
{
@@ -1437,13 +1462,16 @@ void ImFontAtlas::GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_wid
// Although it is likely to be the most commonly used format, our font rendering is 1 channel / 8 bpp
if (!TexPixelsRGBA32)
{
- unsigned char* pixels;
+ unsigned char* pixels = NULL;
GetTexDataAsAlpha8(&pixels, NULL, NULL);
- TexPixelsRGBA32 = (unsigned int*)ImGui::MemAlloc((size_t)(TexWidth * TexHeight * 4));
- const unsigned char* src = pixels;
- unsigned int* dst = TexPixelsRGBA32;
- for (int n = TexWidth * TexHeight; n > 0; n--)
- *dst++ = IM_COL32(255, 255, 255, (unsigned int)(*src++));
+ if (pixels)
+ {
+ TexPixelsRGBA32 = (unsigned int*)ImGui::MemAlloc((size_t)(TexWidth * TexHeight * 4));
+ const unsigned char* src = pixels;
+ unsigned int* dst = TexPixelsRGBA32;
+ for (int n = TexWidth * TexHeight; n > 0; n--)
+ *dst++ = IM_COL32(255, 255, 255, (unsigned int)(*src++));
+ }
}
*out_pixels = (unsigned char*)TexPixelsRGBA32;
@@ -1479,9 +1507,9 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg)
return new_font_cfg.DstFont;
}
-// Default font TTF is compressed with stb_compress then base85 encoded (see extra_fonts/binary_to_compressed_c.cpp for encoder)
-static unsigned int stb_decompress_length(unsigned char *input);
-static unsigned int stb_decompress(unsigned char *output, unsigned char *i, unsigned int length);
+// Default font TTF is compressed with stb_compress then base85 encoded (see misc/fonts/binary_to_compressed_c.cpp for encoder)
+static unsigned int stb_decompress_length(const unsigned char *input);
+static unsigned int stb_decompress(unsigned char *output, const unsigned char *input, unsigned int length);
static const char* GetDefaultCompressedFontDataTTFBase85();
static unsigned int Decode85Byte(char c) { return c >= '\\' ? c-36 : c-35; }
static void Decode85(const unsigned char* src, unsigned char* dst)
@@ -1509,6 +1537,7 @@ ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template)
const char* ttf_compressed_base85 = GetDefaultCompressedFontDataTTFBase85();
ImFont* font = AddFontFromMemoryCompressedBase85TTF(ttf_compressed_base85, font_cfg.SizePixels, &font_cfg, GetGlyphRangesDefault());
+ font->DisplayOffset.y = 1.0f;
return font;
}
@@ -1527,7 +1556,7 @@ ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels,
// Store a short copy of filename into into the font name for convenience
const char* p;
for (p = filename + strlen(filename); p > filename && p[-1] != '/' && p[-1] != '\\'; p--) {}
- snprintf(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "%s, %.0fpx", p, size_pixels);
+ ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "%s, %.0fpx", p, size_pixels);
}
return AddFontFromMemoryTTF(data, data_size, size_pixels, &font_cfg, glyph_ranges);
}
@@ -1547,9 +1576,9 @@ ImFont* ImFontAtlas::AddFontFromMemoryTTF(void* ttf_data, int ttf_size, float si
ImFont* ImFontAtlas::AddFontFromMemoryCompressedTTF(const void* compressed_ttf_data, int compressed_ttf_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges)
{
- const unsigned int buf_decompressed_size = stb_decompress_length((unsigned char*)compressed_ttf_data);
+ const unsigned int buf_decompressed_size = stb_decompress_length((const unsigned char*)compressed_ttf_data);
unsigned char* buf_decompressed_data = (unsigned char *)ImGui::MemAlloc(buf_decompressed_size);
- stb_decompress(buf_decompressed_data, (unsigned char*)compressed_ttf_data, (unsigned int)compressed_ttf_size);
+ stb_decompress(buf_decompressed_data, (const unsigned char*)compressed_ttf_data, (unsigned int)compressed_ttf_size);
ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig();
IM_ASSERT(font_cfg.FontData == NULL);
@@ -1600,8 +1629,30 @@ void ImFontAtlas::CalcCustomRectUV(const CustomRect* rect, ImVec2* out_uv_min, I
{
IM_ASSERT(TexWidth > 0 && TexHeight > 0); // Font atlas needs to be built before we can calculate UV coordinates
IM_ASSERT(rect->IsPacked()); // Make sure the rectangle has been packed
- *out_uv_min = ImVec2((float)rect->X / TexWidth, (float)rect->Y / TexHeight);
- *out_uv_max = ImVec2((float)(rect->X + rect->Width) / TexWidth, (float)(rect->Y + rect->Height) / TexHeight);
+ *out_uv_min = ImVec2((float)rect->X * TexUvScale.x, (float)rect->Y * TexUvScale.y);
+ *out_uv_max = ImVec2((float)(rect->X + rect->Width) * TexUvScale.x, (float)(rect->Y + rect->Height) * TexUvScale.y);
+}
+
+bool ImFontAtlas::GetMouseCursorTexData(ImGuiMouseCursor cursor_type, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2])
+{
+ if (cursor_type <= ImGuiMouseCursor_None || cursor_type >= ImGuiMouseCursor_COUNT)
+ return false;
+ if (Flags & ImFontAtlasFlags_NoMouseCursors)
+ return false;
+
+ IM_ASSERT(CustomRectIds[0] != -1);
+ ImFontAtlas::CustomRect& r = CustomRects[CustomRectIds[0]];
+ IM_ASSERT(r.ID == FONT_ATLAS_DEFAULT_TEX_DATA_ID);
+ ImVec2 pos = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][0] + ImVec2((float)r.X, (float)r.Y);
+ ImVec2 size = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][1];
+ *out_size = size;
+ *out_offset = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][2];
+ out_uv_border[0] = (pos) * TexUvScale;
+ out_uv_border[1] = (pos + size) * TexUvScale;
+ pos.x += FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF + 1;
+ out_uv_fill[0] = (pos) * TexUvScale;
+ out_uv_fill[1] = (pos + size) * TexUvScale;
+ return true;
}
bool ImFontAtlas::Build()
@@ -1634,7 +1685,8 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
atlas->TexID = NULL;
atlas->TexWidth = atlas->TexHeight = 0;
- atlas->TexUvWhitePixel = ImVec2(0, 0);
+ atlas->TexUvScale = ImVec2(0.0f, 0.0f);
+ atlas->TexUvWhitePixel = ImVec2(0.0f, 0.0f);
atlas->ClearTexData();
// Count glyphs/ranges
@@ -1657,7 +1709,8 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
// Start packing
const int max_tex_height = 1024*32;
stbtt_pack_context spc = {};
- stbtt_PackBegin(&spc, NULL, atlas->TexWidth, max_tex_height, 0, atlas->TexGlyphPadding, NULL);
+ if (!stbtt_PackBegin(&spc, NULL, atlas->TexWidth, max_tex_height, 0, atlas->TexGlyphPadding, NULL))
+ return false;
stbtt_PackSetOversampling(&spc, 1, 1);
// Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values).
@@ -1683,6 +1736,7 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
IM_ASSERT(font_offset >= 0);
if (!stbtt_InitFont(&tmp.FontInfo, (unsigned char*)cfg.FontData, font_offset))
{
+ atlas->TexWidth = atlas->TexHeight = 0; // Reset output on failure
ImGui::MemFree(tmp_array);
return false;
}
@@ -1741,7 +1795,8 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
IM_ASSERT(buf_ranges_n == total_ranges_count);
// Create texture
- atlas->TexHeight = ImUpperPowerOfTwo(atlas->TexHeight);
+ atlas->TexHeight = (atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) ? (atlas->TexHeight + 1) : ImUpperPowerOfTwo(atlas->TexHeight);
+ atlas->TexUvScale = ImVec2(1.0f / atlas->TexWidth, 1.0f / atlas->TexHeight);
atlas->TexPixelsAlpha8 = (unsigned char*)ImGui::MemAlloc(atlas->TexWidth * atlas->TexHeight);
memset(atlas->TexPixelsAlpha8, 0, atlas->TexWidth * atlas->TexHeight);
spc.pixels = atlas->TexPixelsAlpha8;
@@ -1776,13 +1831,15 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
ImFontConfig& cfg = atlas->ConfigData[input_i];
ImFontTempBuildData& tmp = tmp_array[input_i];
ImFont* dst_font = cfg.DstFont; // We can have multiple input fonts writing into a same destination font (when using MergeMode=true)
+ if (cfg.MergeMode)
+ dst_font->BuildLookupTable();
const float font_scale = stbtt_ScaleForPixelHeight(&tmp.FontInfo, cfg.SizePixels);
int unscaled_ascent, unscaled_descent, unscaled_line_gap;
stbtt_GetFontVMetrics(&tmp.FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap);
- const float ascent = unscaled_ascent * font_scale;
- const float descent = unscaled_descent * font_scale;
+ const float ascent = ImFloor(unscaled_ascent * font_scale + ((unscaled_ascent > 0.0f) ? +1 : -1));
+ const float descent = ImFloor(unscaled_descent * font_scale + ((unscaled_descent > 0.0f) ? +1 : -1));
ImFontAtlasBuildSetupFont(atlas, dst_font, &cfg, ascent, descent);
const float off_x = cfg.GlyphOffset.x;
const float off_y = cfg.GlyphOffset.y + (float)(int)(dst_font->Ascent + 0.5f);
@@ -1797,7 +1854,7 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
continue;
const int codepoint = range.first_unicode_codepoint_in_range + char_idx;
- if (cfg.MergeMode && dst_font->FindGlyph((unsigned short)codepoint))
+ if (cfg.MergeMode && dst_font->FindGlyphNoFallback((unsigned short)codepoint))
continue;
stbtt_aligned_quad q;
@@ -1820,8 +1877,12 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
void ImFontAtlasBuildRegisterDefaultCustomRects(ImFontAtlas* atlas)
{
- if (atlas->CustomRectIds[0] < 0)
+ if (atlas->CustomRectIds[0] >= 0)
+ return;
+ if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors))
atlas->CustomRectIds[0] = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_ID, FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF*2+1, FONT_ATLAS_DEFAULT_TEX_DATA_H);
+ else
+ atlas->CustomRectIds[0] = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_ID, 2, 2);
}
void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent)
@@ -1867,40 +1928,32 @@ void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* pack_context_opaq
static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas)
{
IM_ASSERT(atlas->CustomRectIds[0] >= 0);
+ IM_ASSERT(atlas->TexPixelsAlpha8 != NULL);
ImFontAtlas::CustomRect& r = atlas->CustomRects[atlas->CustomRectIds[0]];
IM_ASSERT(r.ID == FONT_ATLAS_DEFAULT_TEX_DATA_ID);
- IM_ASSERT(r.Width == FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF*2+1);
- IM_ASSERT(r.Height == FONT_ATLAS_DEFAULT_TEX_DATA_H);
IM_ASSERT(r.IsPacked());
- IM_ASSERT(atlas->TexPixelsAlpha8 != NULL);
- // Render/copy pixels
- for (int y = 0, n = 0; y < FONT_ATLAS_DEFAULT_TEX_DATA_H; y++)
- for (int x = 0; x < FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF; x++, n++)
- {
- const int offset0 = (int)(r.X + x) + (int)(r.Y + y) * atlas->TexWidth;
- const int offset1 = offset0 + FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF + 1;
- atlas->TexPixelsAlpha8[offset0] = FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[n] == '.' ? 0xFF : 0x00;
- atlas->TexPixelsAlpha8[offset1] = FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[n] == 'X' ? 0xFF : 0x00;
- }
- const ImVec2 tex_uv_scale(1.0f / atlas->TexWidth, 1.0f / atlas->TexHeight);
- atlas->TexUvWhitePixel = ImVec2((r.X + 0.5f) * tex_uv_scale.x, (r.Y + 0.5f) * tex_uv_scale.y);
-
- // Setup mouse cursors
- for (int type = 0; type < ImGuiMouseCursor_Count_; type++)
+ const int w = atlas->TexWidth;
+ if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors))
+ {
+ // Render/copy pixels
+ IM_ASSERT(r.Width == FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * 2 + 1 && r.Height == FONT_ATLAS_DEFAULT_TEX_DATA_H);
+ for (int y = 0, n = 0; y < FONT_ATLAS_DEFAULT_TEX_DATA_H; y++)
+ for (int x = 0; x < FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF; x++, n++)
+ {
+ const int offset0 = (int)(r.X + x) + (int)(r.Y + y) * w;
+ const int offset1 = offset0 + FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF + 1;
+ atlas->TexPixelsAlpha8[offset0] = FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[n] == '.' ? 0xFF : 0x00;
+ atlas->TexPixelsAlpha8[offset1] = FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[n] == 'X' ? 0xFF : 0x00;
+ }
+ }
+ else
{
- ImGuiMouseCursorData& cursor_data = GImGui->MouseCursorData[type];
- ImVec2 pos = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[type][0] + ImVec2((float)r.X, (float)r.Y);
- const ImVec2 size = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[type][1];
- cursor_data.Type = type;
- cursor_data.Size = size;
- cursor_data.HotOffset = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[type][2];
- cursor_data.TexUvMin[0] = (pos) * tex_uv_scale;
- cursor_data.TexUvMax[0] = (pos + size) * tex_uv_scale;
- pos.x += FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF + 1;
- cursor_data.TexUvMin[1] = (pos) * tex_uv_scale;
- cursor_data.TexUvMax[1] = (pos + size) * tex_uv_scale;
+ IM_ASSERT(r.Width == 2 && r.Height == 2);
+ const int offset = (int)(r.X) + (int)(r.Y) * w;
+ atlas->TexPixelsAlpha8[offset] = atlas->TexPixelsAlpha8[offset + 1] = atlas->TexPixelsAlpha8[offset + w] = atlas->TexPixelsAlpha8[offset + w + 1] = 0xFF;
}
+ atlas->TexUvWhitePixel = ImVec2((r.X + 0.5f) * atlas->TexUvScale.x, (r.Y + 0.5f) * atlas->TexUvScale.y);
}
void ImFontAtlasBuildFinish(ImFontAtlas* atlas)
@@ -1923,7 +1976,8 @@ void ImFontAtlasBuildFinish(ImFontAtlas* atlas)
// Build all fonts lookup tables
for (int i = 0; i < atlas->Fonts.Size; i++)
- atlas->Fonts[i]->BuildLookupTable();
+ if (atlas->Fonts[i]->DirtyLookupTables)
+ atlas->Fonts[i]->BuildLookupTable();
}
// Retrieve list of range (2 int per range, values are inclusive)
@@ -2019,7 +2073,7 @@ const ImWchar* ImFontAtlas::GetGlyphRangesJapanese()
// Unpack
int codepoint = 0x4e00;
memcpy(full_ranges, base_ranges, sizeof(base_ranges));
- ImWchar* dst = full_ranges + IM_ARRAYSIZE(base_ranges);;
+ ImWchar* dst = full_ranges + IM_ARRAYSIZE(base_ranges);
for (int n = 0; n < IM_ARRAYSIZE(offsets_from_0x4E00); n++, dst += 2)
dst[0] = dst[1] = (ImWchar)(codepoint += (offsets_from_0x4E00[n] + 1));
dst[0] = 0;
@@ -2099,7 +2153,7 @@ ImFont::ImFont()
{
Scale = 1.0f;
FallbackChar = (ImWchar)'?';
- DisplayOffset = ImVec2(0.0f, 1.0f);
+ DisplayOffset = ImVec2(0.0f, 0.0f);
ClearOutputData();
}
@@ -2128,6 +2182,7 @@ void ImFont::ClearOutputData()
ConfigData = NULL;
ContainerAtlas = NULL;
Ascent = Descent = 0.0f;
+ DirtyLookupTables = true;
MetricsTotalSurface = 0;
}
@@ -2140,6 +2195,7 @@ void ImFont::BuildLookupTable()
IM_ASSERT(Glyphs.Size < 0xFFFF); // -1 is reserved
IndexAdvanceX.clear();
IndexLookup.clear();
+ DirtyLookupTables = false;
GrowIndex(max_codepoint + 1);
for (int i = 0; i < Glyphs.Size; i++)
{
@@ -2162,8 +2218,7 @@ void ImFont::BuildLookupTable()
IndexLookup[(int)tab_glyph.Codepoint] = (unsigned short)(Glyphs.Size-1);
}
- FallbackGlyph = NULL;
- FallbackGlyph = FindGlyph(FallbackChar);
+ FallbackGlyph = FindGlyphNoFallback(FallbackChar);
FallbackAdvanceX = FallbackGlyph ? FallbackGlyph->AdvanceX : 0.0f;
for (int i = 0; i < max_codepoint + 1; i++)
if (IndexAdvanceX[i] < 0.0f)
@@ -2204,6 +2259,7 @@ void ImFont::AddGlyph(ImWchar codepoint, float x0, float y0, float x1, float y1,
glyph.AdvanceX = (float)(int)(glyph.AdvanceX + 0.5f);
// Compute rough surface usage metrics (+1 to account for average padding, +0.99 to round)
+ DirtyLookupTables = true;
MetricsTotalSurface += (int)((glyph.U1 - glyph.U0) * ContainerAtlas->TexWidth + 1.99f) * (int)((glyph.V1 - glyph.V0) * ContainerAtlas->TexHeight + 1.99f);
}
@@ -2224,13 +2280,22 @@ void ImFont::AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst)
const ImFontGlyph* ImFont::FindGlyph(ImWchar c) const
{
- if (c < IndexLookup.Size)
- {
- const unsigned short i = IndexLookup[c];
- if (i != (unsigned short)-1)
- return &Glyphs.Data[i];
- }
- return FallbackGlyph;
+ if (c >= IndexLookup.Size)
+ return FallbackGlyph;
+ const unsigned short i = IndexLookup[c];
+ if (i == (unsigned short)-1)
+ return FallbackGlyph;
+ return &Glyphs.Data[i];
+}
+
+const ImFontGlyph* ImFont::FindGlyphNoFallback(ImWchar c) const
+{
+ if (c >= IndexLookup.Size)
+ return NULL;
+ const unsigned short i = IndexLookup[c];
+ if (i == (unsigned short)-1)
+ return NULL;
+ return &Glyphs.Data[i];
}
const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const
@@ -2371,7 +2436,7 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons
while (s < text_end)
{
const char c = *s;
- if (ImCharIsSpace(c)) { s++; } else if (c == '\n') { s++; break; } else { break; }
+ if (ImCharIsSpace((unsigned int)c)) { s++; } else if (c == '\n') { s++; break; } else { break; }
}
continue;
}
@@ -2496,7 +2561,7 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col
while (s < text_end)
{
const char c = *s;
- if (ImCharIsSpace(c)) { s++; } else if (c == '\n') { s++; break; } else { break; }
+ if (ImCharIsSpace((unsigned int)c)) { s++; } else if (c == '\n') { s++; break; } else { break; }
}
continue;
}
@@ -2688,31 +2753,32 @@ void ImGui::RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, Im
// DEFAULT FONT DATA
//-----------------------------------------------------------------------------
// Compressed with stb_compress() then converted to a C array.
-// Use the program in extra_fonts/binary_to_compressed_c.cpp to create the array from a TTF file.
+// Use the program in misc/fonts/binary_to_compressed_c.cpp to create the array from a TTF file.
// Decompression from stb.h (public domain) by Sean Barrett https://github.com/nothings/stb/blob/master/stb.h
//-----------------------------------------------------------------------------
-static unsigned int stb_decompress_length(unsigned char *input)
+static unsigned int stb_decompress_length(const unsigned char *input)
{
return (input[8] << 24) + (input[9] << 16) + (input[10] << 8) + input[11];
}
-static unsigned char *stb__barrier, *stb__barrier2, *stb__barrier3, *stb__barrier4;
+static unsigned char *stb__barrier_out_e, *stb__barrier_out_b;
+static const unsigned char *stb__barrier_in_b;
static unsigned char *stb__dout;
-static void stb__match(unsigned char *data, unsigned int length)
+static void stb__match(const unsigned char *data, unsigned int length)
{
// INVERSE of memmove... write each byte before copying the next...
- IM_ASSERT (stb__dout + length <= stb__barrier);
- if (stb__dout + length > stb__barrier) { stb__dout += length; return; }
- if (data < stb__barrier4) { stb__dout = stb__barrier+1; return; }
+ IM_ASSERT(stb__dout + length <= stb__barrier_out_e);
+ if (stb__dout + length > stb__barrier_out_e) { stb__dout += length; return; }
+ if (data < stb__barrier_out_b) { stb__dout = stb__barrier_out_e+1; return; }
while (length--) *stb__dout++ = *data++;
}
-static void stb__lit(unsigned char *data, unsigned int length)
+static void stb__lit(const unsigned char *data, unsigned int length)
{
- IM_ASSERT (stb__dout + length <= stb__barrier);
- if (stb__dout + length > stb__barrier) { stb__dout += length; return; }
- if (data < stb__barrier2) { stb__dout = stb__barrier+1; return; }
+ IM_ASSERT(stb__dout + length <= stb__barrier_out_e);
+ if (stb__dout + length > stb__barrier_out_e) { stb__dout += length; return; }
+ if (data < stb__barrier_in_b) { stb__dout = stb__barrier_out_e+1; return; }
memcpy(stb__dout, data, length);
stb__dout += length;
}
@@ -2721,7 +2787,7 @@ static void stb__lit(unsigned char *data, unsigned int length)
#define stb__in3(x) ((i[x] << 16) + stb__in2((x)+1))
#define stb__in4(x) ((i[x] << 24) + stb__in3((x)+1))
-static unsigned char *stb_decompress_token(unsigned char *i)
+static const unsigned char *stb_decompress_token(const unsigned char *i)
{
if (*i >= 0x20) { // use fewer if's for cases that expand small
if (*i >= 0x80) stb__match(stb__dout-i[1]-1, i[0] - 0x80 + 1), i += 2;
@@ -2769,21 +2835,20 @@ static unsigned int stb_adler32(unsigned int adler32, unsigned char *buffer, uns
return (unsigned int)(s2 << 16) + (unsigned int)s1;
}
-static unsigned int stb_decompress(unsigned char *output, unsigned char *i, unsigned int length)
+static unsigned int stb_decompress(unsigned char *output, const unsigned char *i, unsigned int /*length*/)
{
unsigned int olen;
if (stb__in4(0) != 0x57bC0000) return 0;
if (stb__in4(4) != 0) return 0; // error! stream is > 4GB
olen = stb_decompress_length(i);
- stb__barrier2 = i;
- stb__barrier3 = i+length;
- stb__barrier = output + olen;
- stb__barrier4 = output;
+ stb__barrier_in_b = i;
+ stb__barrier_out_e = output + olen;
+ stb__barrier_out_b = output;
i += 16;
stb__dout = output;
for (;;) {
- unsigned char *old_i = i;
+ const unsigned char *old_i = i;
i = stb_decompress_token(i);
if (i == old_i) {
if (*i == 0x05 && i[1] == 0xfa) {
diff --git a/imgui/imgui_internal.h b/imgui/imgui_internal.h
index 80435390..0af53025 100644
--- a/imgui/imgui_internal.h
+++ b/imgui/imgui_internal.h
@@ -1,4 +1,4 @@
-// dear imgui, v1.53
+// dear imgui, v1.60
// (internals)
// You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility!
@@ -14,6 +14,7 @@
#include <stdio.h> // FILE*
#include <math.h> // sqrtf, fabsf, fmodf, powf, floorf, ceilf, cosf, sinf
+#include <limits.h> // INT_MIN, INT_MAX
#ifdef _MSC_VER
#pragma warning (push)
@@ -35,10 +36,9 @@ struct ImRect;
struct ImGuiColMod;
struct ImGuiStyleMod;
struct ImGuiGroupData;
-struct ImGuiSimpleColumns;
+struct ImGuiMenuColumns;
struct ImGuiDrawContext;
struct ImGuiTextEditState;
-struct ImGuiMouseCursorData;
struct ImGuiPopupRef;
struct ImGuiWindow;
struct ImGuiWindowSettings;
@@ -46,6 +46,9 @@ struct ImGuiWindowSettings;
typedef int ImGuiLayoutType; // enum: horizontal or vertical // enum ImGuiLayoutType_
typedef int ImGuiButtonFlags; // flags: for ButtonEx(), ButtonBehavior() // enum ImGuiButtonFlags_
typedef int ImGuiItemFlags; // flags: for PushItemFlag() // enum ImGuiItemFlags_
+typedef int ImGuiItemStatusFlags; // flags: storage for DC.LastItemXXX // enum ImGuiItemStatusFlags_
+typedef int ImGuiNavHighlightFlags; // flags: for RenderNavHighlight() // enum ImGuiNavHighlightFlags_
+typedef int ImGuiNavDirSourceFlags; // flags: for GetNavInputAmount2d() // enum ImGuiNavDirSourceFlags_
typedef int ImGuiSeparatorFlags; // flags: for Separator() - internal // enum ImGuiSeparatorFlags_
typedef int ImGuiSliderFlags; // flags: for SliderBehavior() // enum ImGuiSliderFlags_
@@ -77,8 +80,12 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit ImGui context pointe
// Helpers
//-----------------------------------------------------------------------------
-#define IM_PI 3.14159265358979323846f
-#define IM_OFFSETOF(_TYPE,_ELM) ((size_t)&(((_TYPE*)0)->_ELM))
+#define IM_PI 3.14159265358979323846f
+#ifdef _WIN32
+#define IM_NEWLINE "\r\n" // Play it nice with Windows users (2018: Notepad _still_ doesn't display files properly when they use Unix-style carriage returns)
+#else
+#define IM_NEWLINE "\n"
+#endif
// Helpers: UTF-8 <> wchar
IMGUI_API int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end); // return output UTF-8 bytes count
@@ -91,7 +98,7 @@ IMGUI_API int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, cons
IMGUI_API ImU32 ImHash(const void* data, int data_size, ImU32 seed = 0); // Pass data_size==0 for zero-terminated strings
IMGUI_API void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, int* out_file_size = NULL, int padding_bytes = 0);
IMGUI_API FILE* ImFileOpen(const char* filename, const char* file_open_mode);
-static inline bool ImCharIsSpace(int c) { return c == ' ' || c == '\t' || c == 0x3000; }
+static inline bool ImCharIsSpace(unsigned int c) { return c == ' ' || c == '\t' || c == 0x3000; }
static inline bool ImIsPowerOfTwo(int v) { return v != 0 && (v & (v - 1)) == 0; }
static inline int ImUpperPowerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; }
@@ -106,7 +113,7 @@ IMGUI_API int ImStricmp(const char* str1, const char* str2);
IMGUI_API int ImStrnicmp(const char* str1, const char* str2, size_t count);
IMGUI_API void ImStrncpy(char* dst, const char* src, size_t count);
IMGUI_API char* ImStrdup(const char* str);
-IMGUI_API char* ImStrchrRange(const char* str_begin, const char* str_end, char c);
+IMGUI_API const char* ImStrchrRange(const char* str_begin, const char* str_end, char c);
IMGUI_API int ImStrlenW(const ImWchar* str);
IMGUI_API const ImWchar*ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin); // Find beginning-of-line
IMGUI_API const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end);
@@ -135,8 +142,8 @@ static inline int ImMin(int lhs, int rhs)
static inline int ImMax(int lhs, int rhs) { return lhs >= rhs ? lhs : rhs; }
static inline float ImMin(float lhs, float rhs) { return lhs < rhs ? lhs : rhs; }
static inline float ImMax(float lhs, float rhs) { return lhs >= rhs ? lhs : rhs; }
-static inline ImVec2 ImMin(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMin(lhs.x,rhs.x), ImMin(lhs.y,rhs.y)); }
-static inline ImVec2 ImMax(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMax(lhs.x,rhs.x), ImMax(lhs.y,rhs.y)); }
+static inline ImVec2 ImMin(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x < rhs.x ? lhs.x : rhs.x, lhs.y < rhs.y ? lhs.y : rhs.y); }
+static inline ImVec2 ImMax(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x >= rhs.x ? lhs.x : rhs.x, lhs.y >= rhs.y ? lhs.y : rhs.y); }
static inline int ImClamp(int v, int mn, int mx) { return (v < mn) ? mn : (v > mx) ? mx : v; }
static inline float ImClamp(float v, float mn, float mx) { return (v < mn) ? mn : (v > mx) ? mx : v; }
static inline ImVec2 ImClamp(const ImVec2& f, const ImVec2& mn, ImVec2 mx) { return ImVec2(ImClamp(f.x,mn.x,mx.x), ImClamp(f.y,mn.y,mx.y)); }
@@ -158,22 +165,10 @@ static inline ImVec2 ImRotate(const ImVec2& v, float cos_a, float sin_a)
static inline float ImLinearSweep(float current, float target, float speed) { if (current < target) return ImMin(current + speed, target); if (current > target) return ImMax(current - speed, target); return current; }
static inline ImVec2 ImMul(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); }
-// We call C++ constructor on own allocated memory via the placement "new(ptr) Type()" syntax.
-// Defining a custom placement new() with a dummy parameter allows us to bypass including <new> which on some platforms complains when user has disabled exceptions.
-struct ImNewPlacementDummy {};
-inline void* operator new(size_t, ImNewPlacementDummy, void* ptr) { return ptr; }
-inline void operator delete(void*, ImNewPlacementDummy, void*) {} // This is only required so we can use the symetrical new()
-#define IM_PLACEMENT_NEW(_PTR) new(ImNewPlacementDummy(), _PTR)
-#define IM_NEW(_TYPE) new(ImNewPlacementDummy(), ImGui::MemAlloc(sizeof(_TYPE))) _TYPE
-template <typename T> void IM_DELETE(T*& p) { if (p) { p->~T(); ImGui::MemFree(p); p = NULL; } }
-
//-----------------------------------------------------------------------------
// Types
//-----------------------------------------------------------------------------
-// Internal Drag and Drop payload types. String starting with '_' are reserved for Dear ImGui.
-#define IMGUI_PAYLOAD_TYPE_DOCKABLE "_IMDOCK" // ImGuiWindow* // [Internal] Docking/tabs
-
enum ImGuiButtonFlags_
{
ImGuiButtonFlags_Repeat = 1 << 0, // hold to repeat
@@ -188,7 +183,8 @@ enum ImGuiButtonFlags_
ImGuiButtonFlags_AlignTextBaseLine = 1 << 9, // vertically align button to match text baseline - ButtonEx() only // FIXME: Should be removed and handled by SmallButton(), not possible currently because of DC.CursorPosPrevLine
ImGuiButtonFlags_NoKeyModifiers = 1 << 10, // disable interaction if a key modifier is held
ImGuiButtonFlags_NoHoldingActiveID = 1 << 11, // don't set ActiveId while holding the mouse (ImGuiButtonFlags_PressedOnClick only)
- ImGuiButtonFlags_PressedOnDragDropHold = 1 << 12 // press when held into while we are drag and dropping another item (used by e.g. tree nodes, collapsing headers)
+ ImGuiButtonFlags_PressedOnDragDropHold = 1 << 12, // press when held into while we are drag and dropping another item (used by e.g. tree nodes, collapsing headers)
+ ImGuiButtonFlags_NoNavFocus = 1 << 13 // don't override navigation focus when activated
};
enum ImGuiSliderFlags_
@@ -221,6 +217,13 @@ enum ImGuiSeparatorFlags_
ImGuiSeparatorFlags_Vertical = 1 << 1
};
+// Storage for LastItem data
+enum ImGuiItemStatusFlags_
+{
+ ImGuiItemStatusFlags_HoveredRect = 1 << 0,
+ ImGuiItemStatusFlags_HasDisplayRect = 1 << 1
+};
+
// FIXME: this is in development, not exposed/functional as a generic feature yet.
enum ImGuiLayoutType_
{
@@ -245,17 +248,51 @@ enum ImGuiDataType
{
ImGuiDataType_Int,
ImGuiDataType_Float,
- ImGuiDataType_Float2
+ ImGuiDataType_Double,
+ ImGuiDataType_COUNT
+};
+
+enum ImGuiInputSource
+{
+ ImGuiInputSource_None = 0,
+ ImGuiInputSource_Mouse,
+ ImGuiInputSource_Nav,
+ ImGuiInputSource_NavKeyboard, // Only used occasionally for storage, not tested/handled by most code
+ ImGuiInputSource_NavGamepad, // "
+ ImGuiInputSource_COUNT
+};
+
+// FIXME-NAV: Clarify/expose various repeat delay/rate
+enum ImGuiInputReadMode
+{
+ ImGuiInputReadMode_Down,
+ ImGuiInputReadMode_Pressed,
+ ImGuiInputReadMode_Released,
+ ImGuiInputReadMode_Repeat,
+ ImGuiInputReadMode_RepeatSlow,
+ ImGuiInputReadMode_RepeatFast
+};
+
+enum ImGuiNavHighlightFlags_
+{
+ ImGuiNavHighlightFlags_TypeDefault = 1 << 0,
+ ImGuiNavHighlightFlags_TypeThin = 1 << 1,
+ ImGuiNavHighlightFlags_AlwaysDraw = 1 << 2,
+ ImGuiNavHighlightFlags_NoRounding = 1 << 3
};
-enum ImGuiDir
+enum ImGuiNavDirSourceFlags_
{
- ImGuiDir_None = -1,
- ImGuiDir_Left = 0,
- ImGuiDir_Right = 1,
- ImGuiDir_Up = 2,
- ImGuiDir_Down = 3,
- ImGuiDir_Count_
+ ImGuiNavDirSourceFlags_Keyboard = 1 << 0,
+ ImGuiNavDirSourceFlags_PadDPad = 1 << 1,
+ ImGuiNavDirSourceFlags_PadLStick = 1 << 2
+};
+
+enum ImGuiNavForward
+{
+ ImGuiNavForward_None,
+ ImGuiNavForward_ForwardQueued,
+ ImGuiNavForward_ForwardActive
};
// 2D axis aligned bounding-box
@@ -270,36 +307,27 @@ struct IMGUI_API ImRect
ImRect(const ImVec4& v) : Min(v.x, v.y), Max(v.z, v.w) {}
ImRect(float x1, float y1, float x2, float y2) : Min(x1, y1), Max(x2, y2) {}
- ImVec2 GetCenter() const { return ImVec2((Min.x+Max.x)*0.5f, (Min.y+Max.y)*0.5f); }
- ImVec2 GetSize() const { return ImVec2(Max.x-Min.x, Max.y-Min.y); }
- float GetWidth() const { return Max.x-Min.x; }
- float GetHeight() const { return Max.y-Min.y; }
- ImVec2 GetTL() const { return Min; } // Top-left
- ImVec2 GetTR() const { return ImVec2(Max.x, Min.y); } // Top-right
- ImVec2 GetBL() const { return ImVec2(Min.x, Max.y); } // Bottom-left
- ImVec2 GetBR() const { return Max; } // Bottom-right
- bool Contains(const ImVec2& p) const { return p.x >= Min.x && p.y >= Min.y && p.x < Max.x && p.y < Max.y; }
- bool Contains(const ImRect& r) const { return r.Min.x >= Min.x && r.Min.y >= Min.y && r.Max.x < Max.x && r.Max.y < Max.y; }
- bool Overlaps(const ImRect& r) const { return r.Min.y < Max.y && r.Max.y > Min.y && r.Min.x < Max.x && r.Max.x > Min.x; }
- void Add(const ImVec2& rhs) { if (Min.x > rhs.x) Min.x = rhs.x; if (Min.y > rhs.y) Min.y = rhs.y; if (Max.x < rhs.x) Max.x = rhs.x; if (Max.y < rhs.y) Max.y = rhs.y; }
- void Add(const ImRect& rhs) { if (Min.x > rhs.Min.x) Min.x = rhs.Min.x; if (Min.y > rhs.Min.y) Min.y = rhs.Min.y; if (Max.x < rhs.Max.x) Max.x = rhs.Max.x; if (Max.y < rhs.Max.y) Max.y = rhs.Max.y; }
- void Expand(const float amount) { Min.x -= amount; Min.y -= amount; Max.x += amount; Max.y += amount; }
- void Expand(const ImVec2& amount) { Min.x -= amount.x; Min.y -= amount.y; Max.x += amount.x; Max.y += amount.y; }
- void Translate(const ImVec2& v) { Min.x += v.x; Min.y += v.y; Max.x += v.x; Max.y += v.y; }
- void ClipWith(const ImRect& clip) { if (Min.x < clip.Min.x) Min.x = clip.Min.x; if (Min.y < clip.Min.y) Min.y = clip.Min.y; if (Max.x > clip.Max.x) Max.x = clip.Max.x; if (Max.y > clip.Max.y) Max.y = clip.Max.y; }
- void Floor() { Min.x = (float)(int)Min.x; Min.y = (float)(int)Min.y; Max.x = (float)(int)Max.x; Max.y = (float)(int)Max.y; }
- void FixInverted() { if (Min.x > Max.x) ImSwap(Min.x, Max.x); if (Min.y > Max.y) ImSwap(Min.y, Max.y); }
- bool IsFinite() const { return Min.x != FLT_MAX; }
- ImVec2 GetClosestPoint(ImVec2 p, bool on_edge) const
- {
- if (!on_edge && Contains(p))
- return p;
- if (p.x > Max.x) p.x = Max.x;
- else if (p.x < Min.x) p.x = Min.x;
- if (p.y > Max.y) p.y = Max.y;
- else if (p.y < Min.y) p.y = Min.y;
- return p;
- }
+ ImVec2 GetCenter() const { return ImVec2((Min.x + Max.x) * 0.5f, (Min.y + Max.y) * 0.5f); }
+ ImVec2 GetSize() const { return ImVec2(Max.x - Min.x, Max.y - Min.y); }
+ float GetWidth() const { return Max.x - Min.x; }
+ float GetHeight() const { return Max.y - Min.y; }
+ ImVec2 GetTL() const { return Min; } // Top-left
+ ImVec2 GetTR() const { return ImVec2(Max.x, Min.y); } // Top-right
+ ImVec2 GetBL() const { return ImVec2(Min.x, Max.y); } // Bottom-left
+ ImVec2 GetBR() const { return Max; } // Bottom-right
+ bool Contains(const ImVec2& p) const { return p.x >= Min.x && p.y >= Min.y && p.x < Max.x && p.y < Max.y; }
+ bool Contains(const ImRect& r) const { return r.Min.x >= Min.x && r.Min.y >= Min.y && r.Max.x <= Max.x && r.Max.y <= Max.y; }
+ bool Overlaps(const ImRect& r) const { return r.Min.y < Max.y && r.Max.y > Min.y && r.Min.x < Max.x && r.Max.x > Min.x; }
+ void Add(const ImVec2& p) { if (Min.x > p.x) Min.x = p.x; if (Min.y > p.y) Min.y = p.y; if (Max.x < p.x) Max.x = p.x; if (Max.y < p.y) Max.y = p.y; }
+ void Add(const ImRect& r) { if (Min.x > r.Min.x) Min.x = r.Min.x; if (Min.y > r.Min.y) Min.y = r.Min.y; if (Max.x < r.Max.x) Max.x = r.Max.x; if (Max.y < r.Max.y) Max.y = r.Max.y; }
+ void Expand(const float amount) { Min.x -= amount; Min.y -= amount; Max.x += amount; Max.y += amount; }
+ void Expand(const ImVec2& amount) { Min.x -= amount.x; Min.y -= amount.y; Max.x += amount.x; Max.y += amount.y; }
+ void Translate(const ImVec2& v) { Min.x += v.x; Min.y += v.y; Max.x += v.x; Max.y += v.y; }
+ void ClipWith(const ImRect& r) { Min = ImMax(Min, r.Min); Max = ImMin(Max, r.Max); } // Simple version, may lead to an inverted rectangle, which is fine for Contains/Overlaps test but not for display.
+ void ClipWithFull(const ImRect& r) { Min = ImClamp(Min, r.Min, r.Max); Max = ImClamp(Max, r.Min, r.Max); } // Full version, ensure both points are fully clipped.
+ void Floor() { Min.x = (float)(int)Min.x; Min.y = (float)(int)Min.y; Max.x = (float)(int)Max.x; Max.y = (float)(int)Max.y; }
+ void FixInverted() { if (Min.x > Max.x) ImSwap(Min.x, Max.x); if (Min.y > Max.y) ImSwap(Min.y, Max.y); }
+ bool IsInverted() const { return Min.x > Max.x || Min.y > Max.y; }
};
// Stacked color modifier, backup of modified data so we can restore it
@@ -334,14 +362,14 @@ struct ImGuiGroupData
};
// Simple column measurement currently used for MenuItem() only. This is very short-sighted/throw-away code and NOT a generic helper.
-struct IMGUI_API ImGuiSimpleColumns
+struct IMGUI_API ImGuiMenuColumns
{
int Count;
float Spacing;
float Width, NextWidth;
- float Pos[8], NextWidths[8];
+ float Pos[4], NextWidths[4];
- ImGuiSimpleColumns();
+ ImGuiMenuColumns();
void Update(int count, float spacing, bool clear);
float DeclColumns(float w0, float w1, float w2);
float CalcExtraSpace(float avail_w);
@@ -367,7 +395,7 @@ struct IMGUI_API ImGuiTextEditState
void CursorClamp() { StbState.cursor = ImMin(StbState.cursor, CurLenW); StbState.select_start = ImMin(StbState.select_start, CurLenW); StbState.select_end = ImMin(StbState.select_end, CurLenW); }
bool HasSelection() const { return StbState.select_start != StbState.select_end; }
void ClearSelection() { StbState.select_start = StbState.select_end = StbState.cursor; }
- void SelectAll() { StbState.select_start = 0; StbState.select_end = CurLenW; StbState.cursor = StbState.select_end; StbState.has_preferred_x = false; }
+ void SelectAll() { StbState.select_start = 0; StbState.cursor = StbState.select_end = CurLenW; StbState.has_preferred_x = false; }
void OnKeyPressed(int key);
};
@@ -387,19 +415,12 @@ struct ImGuiSettingsHandler
{
const char* TypeName; // Short description stored in .ini file. Disallowed characters: '[' ']'
ImGuiID TypeHash; // == ImHash(TypeName, 0, 0)
- void* (*ReadOpenFn)(ImGuiContext& ctx, const char* name);
- void (*ReadLineFn)(ImGuiContext& ctx, void* entry, const char* line);
- void (*WriteAllFn)(ImGuiContext& ctx, ImGuiTextBuffer* out_buf);
-};
+ void* (*ReadOpenFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, const char* name);
+ void (*ReadLineFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, void* entry, const char* line);
+ void (*WriteAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* out_buf);
+ void* UserData;
-// Mouse cursor data (used when io.MouseDrawCursor is set)
-struct ImGuiMouseCursorData
-{
- ImGuiMouseCursor Type;
- ImVec2 HotOffset;
- ImVec2 Size;
- ImVec2 TexUvMin[2];
- ImVec2 TexUvMax[2];
+ ImGuiSettingsHandler() { memset(this, 0, sizeof(*this)); }
};
// Storage for current popup stack
@@ -408,10 +429,10 @@ struct ImGuiPopupRef
ImGuiID PopupId; // Set on OpenPopup()
ImGuiWindow* Window; // Resolved on BeginPopup() - may stay unresolved if user never calls OpenPopup()
ImGuiWindow* ParentWindow; // Set on OpenPopup()
- ImGuiID ParentMenuSet; // Set on OpenPopup()
- ImVec2 MousePosOnOpen; // Copy of mouse position at the time of opening popup
-
- ImGuiPopupRef(ImGuiID id, ImGuiWindow* parent_window, ImGuiID parent_menu_set, const ImVec2& mouse_pos) { PopupId = id; Window = NULL; ParentWindow = parent_window; ParentMenuSet = parent_menu_set; MousePosOnOpen = mouse_pos; }
+ int OpenFrameCount; // Set on OpenPopup()
+ ImGuiID OpenParentId; // Set on OpenPopup(), we need this to differenciate multiple menu sets from each others (e.g. inside menu bar vs loose menu items)
+ ImVec2 OpenPopupPos; // Set on OpenPopup(), preferred popup position (typically == OpenMousePos when using mouse)
+ ImVec2 OpenMousePos; // Set on OpenPopup(), copy of mouse position at the time of opening popup
};
struct ImGuiColumnData
@@ -433,9 +454,9 @@ struct ImGuiColumnsSet
int Current;
int Count;
float MinX, MaxX;
- float StartPosY;
- float StartMaxPosX; // Backup of CursorMaxPos
- float CellMinY, CellMaxY;
+ float LineMinY, LineMaxY;
+ float StartPosY; // Copy of CursorPos
+ float StartMaxPosX; // Copy of CursorMaxPos
ImVector<ImGuiColumnData> Columns;
ImGuiColumnsSet() { Clear(); }
@@ -448,14 +469,14 @@ struct ImGuiColumnsSet
Current = 0;
Count = 1;
MinX = MaxX = 0.0f;
+ LineMinY = LineMaxY = 0.0f;
StartPosY = 0.0f;
StartMaxPosX = 0.0f;
- CellMinY = CellMaxY = 0.0f;
Columns.clear();
}
};
-struct ImDrawListSharedData
+struct IMGUI_API ImDrawListSharedData
{
ImVec2 TexUvWhitePixel; // UV of white pixel in the atlas
ImFont* Font; // Current/default font (optional, for simplified AddText overload)
@@ -470,10 +491,72 @@ struct ImDrawListSharedData
ImDrawListSharedData();
};
+struct ImDrawDataBuilder
+{
+ ImVector<ImDrawList*> Layers[2]; // Global layers for: regular, tooltip
+
+ void Clear() { for (int n = 0; n < IM_ARRAYSIZE(Layers); n++) Layers[n].resize(0); }
+ void ClearFreeMemory() { for (int n = 0; n < IM_ARRAYSIZE(Layers); n++) Layers[n].clear(); }
+ IMGUI_API void FlattenIntoSingleLayer();
+};
+
+struct ImGuiNavMoveResult
+{
+ ImGuiID ID; // Best candidate
+ ImGuiID ParentID; // Best candidate window->IDStack.back() - to compare context
+ ImGuiWindow* Window; // Best candidate window
+ float DistBox; // Best candidate box distance to current NavId
+ float DistCenter; // Best candidate center distance to current NavId
+ float DistAxial;
+ ImRect RectRel; // Best candidate bounding box in window relative space
+
+ ImGuiNavMoveResult() { Clear(); }
+ void Clear() { ID = ParentID = 0; Window = NULL; DistBox = DistCenter = DistAxial = FLT_MAX; RectRel = ImRect(); }
+};
+
+// Storage for SetNexWindow** functions
+struct ImGuiNextWindowData
+{
+ ImGuiCond PosCond;
+ ImGuiCond SizeCond;
+ ImGuiCond ContentSizeCond;
+ ImGuiCond CollapsedCond;
+ ImGuiCond SizeConstraintCond;
+ ImGuiCond FocusCond;
+ ImGuiCond BgAlphaCond;
+ ImVec2 PosVal;
+ ImVec2 PosPivotVal;
+ ImVec2 SizeVal;
+ ImVec2 ContentSizeVal;
+ bool CollapsedVal;
+ ImRect SizeConstraintRect; // Valid if 'SetNextWindowSizeConstraint' is true
+ ImGuiSizeCallback SizeCallback;
+ void* SizeCallbackUserData;
+ float BgAlphaVal;
+
+ ImGuiNextWindowData()
+ {
+ PosCond = SizeCond = ContentSizeCond = CollapsedCond = SizeConstraintCond = FocusCond = BgAlphaCond = 0;
+ PosVal = PosPivotVal = SizeVal = ImVec2(0.0f, 0.0f);
+ ContentSizeVal = ImVec2(0.0f, 0.0f);
+ CollapsedVal = false;
+ SizeConstraintRect = ImRect();
+ SizeCallback = NULL;
+ SizeCallbackUserData = NULL;
+ BgAlphaVal = FLT_MAX;
+ }
+
+ void Clear()
+ {
+ PosCond = SizeCond = ContentSizeCond = CollapsedCond = SizeConstraintCond = FocusCond = BgAlphaCond = 0;
+ }
+};
+
// Main state for ImGui
struct ImGuiContext
{
bool Initialized;
+ bool FontAtlasOwnedByContext; // Io.Fonts-> is owned by the ImGuiContext and will be destructed along with it.
ImGuiIO IO;
ImGuiStyle Style;
ImFont* Font; // (Shortcut) == FontStack.empty() ? IO.Font : FontStack.back()
@@ -491,7 +574,6 @@ struct ImGuiContext
ImGuiStorage WindowsById;
int WindowsActiveCount;
ImGuiWindow* CurrentWindow; // Being drawn into
- ImGuiWindow* NavWindow; // Nav/focused window for navigation
ImGuiWindow* HoveredWindow; // Will catch mouse inputs
ImGuiWindow* HoveredRootWindow; // Will catch mouse inputs (for focus/move only)
ImGuiID HoveredId; // Hovered widget
@@ -504,41 +586,61 @@ struct ImGuiContext
bool ActiveIdIsAlive; // Active widget has been seen this frame
bool ActiveIdIsJustActivated; // Set at the time of activation for one frame
bool ActiveIdAllowOverlap; // Active widget allows another widget to steal active id (generally for overlapping widgets, but not always)
+ int ActiveIdAllowNavDirFlags; // Active widget allows using directional navigation (e.g. can activate a button and move away from it)
ImVec2 ActiveIdClickOffset; // Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior)
ImGuiWindow* ActiveIdWindow;
- ImGuiWindow* MovingWindow; // Track the child window we clicked on to move a window.
- ImGuiID MovingWindowMoveId; // == MovingWindow->MoveId
+ ImGuiInputSource ActiveIdSource; // Activating with mouse or nav (gamepad/keyboard)
+ ImGuiWindow* MovingWindow; // Track the window we clicked on (in order to preserve focus). The actually window that is moved is generally MovingWindow->RootWindow.
ImVector<ImGuiColMod> ColorModifiers; // Stack for PushStyleColor()/PopStyleColor()
ImVector<ImGuiStyleMod> StyleModifiers; // Stack for PushStyleVar()/PopStyleVar()
ImVector<ImFont*> FontStack; // Stack for PushFont()/PopFont()
ImVector<ImGuiPopupRef> OpenPopupStack; // Which popups are open (persistent)
ImVector<ImGuiPopupRef> CurrentPopupStack; // Which level of BeginPopup() we are in (reset every frame)
-
- // Storage for SetNexWindow** and SetNextTreeNode*** functions
- ImVec2 SetNextWindowPosVal;
- ImVec2 SetNextWindowPosPivot;
- ImVec2 SetNextWindowSizeVal;
- ImVec2 SetNextWindowContentSizeVal;
- bool SetNextWindowCollapsedVal;
- ImGuiCond SetNextWindowPosCond;
- ImGuiCond SetNextWindowSizeCond;
- ImGuiCond SetNextWindowContentSizeCond;
- ImGuiCond SetNextWindowCollapsedCond;
- ImRect SetNextWindowSizeConstraintRect; // Valid if 'SetNextWindowSizeConstraint' is true
- ImGuiSizeConstraintCallback SetNextWindowSizeConstraintCallback;
- void* SetNextWindowSizeConstraintCallbackUserData;
- bool SetNextWindowSizeConstraint;
- bool SetNextWindowFocus;
- bool SetNextTreeNodeOpenVal;
- ImGuiCond SetNextTreeNodeOpenCond;
+ ImGuiNextWindowData NextWindowData; // Storage for SetNextWindow** functions
+ bool NextTreeNodeOpenVal; // Storage for SetNextTreeNode** functions
+ ImGuiCond NextTreeNodeOpenCond;
+
+ // Navigation data (for gamepad/keyboard)
+ ImGuiWindow* NavWindow; // Focused window for navigation. Could be called 'FocusWindow'
+ ImGuiID NavId; // Focused item for navigation
+ ImGuiID NavActivateId; // ~~ (g.ActiveId == 0) && IsNavInputPressed(ImGuiNavInput_Activate) ? NavId : 0, also set when calling ActivateItem()
+ ImGuiID NavActivateDownId; // ~~ IsNavInputDown(ImGuiNavInput_Activate) ? NavId : 0
+ ImGuiID NavActivatePressedId; // ~~ IsNavInputPressed(ImGuiNavInput_Activate) ? NavId : 0
+ ImGuiID NavInputId; // ~~ IsNavInputPressed(ImGuiNavInput_Input) ? NavId : 0
+ ImGuiID NavJustTabbedId; // Just tabbed to this id.
+ ImGuiID NavJustMovedToId; // Just navigated to this id (result of a successfully MoveRequest)
+ ImGuiID NavNextActivateId; // Set by ActivateItem(), queued until next frame
+ ImGuiInputSource NavInputSource; // Keyboard or Gamepad mode?
+ ImRect NavScoringRectScreen; // Rectangle used for scoring, in screen space. Based of window->DC.NavRefRectRel[], modified for directional navigation scoring.
+ int NavScoringCount; // Metrics for debugging
+ ImGuiWindow* NavWindowingTarget; // When selecting a window (holding Menu+FocusPrev/Next, or equivalent of CTRL-TAB) this window is temporarily displayed front-most.
+ float NavWindowingHighlightTimer;
+ float NavWindowingHighlightAlpha;
+ bool NavWindowingToggleLayer;
+ int NavLayer; // Layer we are navigating on. For now the system is hard-coded for 0=main contents and 1=menu/title bar, may expose layers later.
+ int NavIdTabCounter; // == NavWindow->DC.FocusIdxTabCounter at time of NavId processing
+ bool NavIdIsAlive; // Nav widget has been seen this frame ~~ NavRefRectRel is valid
+ bool NavMousePosDirty; // When set we will update mouse position if (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) if set (NB: this not enabled by default)
+ bool NavDisableHighlight; // When user starts using mouse, we hide gamepad/keyboard highlight (NB: but they are still available, which is why NavDisableHighlight isn't always != NavDisableMouseHover)
+ bool NavDisableMouseHover; // When user starts using gamepad/keyboard, we hide mouse hovering highlight until mouse is touched again.
+ bool NavAnyRequest; // ~~ NavMoveRequest || NavInitRequest
+ bool NavInitRequest; // Init request for appearing window to select first item
+ bool NavInitRequestFromMove;
+ ImGuiID NavInitResultId;
+ ImRect NavInitResultRectRel;
+ bool NavMoveFromClampedRefRect; // Set by manual scrolling, if we scroll to a point where NavId isn't visible we reset navigation from visible items
+ bool NavMoveRequest; // Move request for this frame
+ ImGuiNavForward NavMoveRequestForward; // None / ForwardQueued / ForwardActive (this is used to navigate sibling parent menus from a child menu)
+ ImGuiDir NavMoveDir, NavMoveDirLast; // Direction of the move request (left/right/up/down), direction of the previous move request
+ ImGuiNavMoveResult NavMoveResultLocal; // Best move request candidate within NavWindow
+ ImGuiNavMoveResult NavMoveResultOther; // Best move request candidate within NavWindow's flattened hierarchy (when using the NavFlattened flag)
// Render
- ImDrawData RenderDrawData; // Main ImDrawData instance to pass render information to the user
- ImVector<ImDrawList*> RenderDrawLists[3];
+ ImDrawData DrawData; // Main ImDrawData instance to pass render information to the user
+ ImDrawDataBuilder DrawDataBuilder;
float ModalWindowDarkeningRatio;
ImDrawList OverlayDrawList; // Optional software render of mouse cursors, if io.MouseDrawCursor is set + a few debug overlays
ImGuiMouseCursor MouseCursor;
- ImGuiMouseCursorData MouseCursorData[ImGuiMouseCursor_Count_];
// Drag and Drop
bool DragDropActive;
@@ -552,7 +654,7 @@ struct ImGuiContext
ImGuiID DragDropAcceptIdPrev; // Target item id from previous frame (we need to store this to allow for overlapping drag and drop targets)
int DragDropAcceptFrameCount; // Last time a target expressed a desire to accept the source
ImVector<unsigned char> DragDropPayloadBufHeap; // We don't expose the ImVector<> directly
- unsigned char DragDropPayloadBufLocal[8];
+ unsigned char DragDropPayloadBufLocal[8]; // Local buffer for small payloads
// Widget state
ImGuiTextEditState InputTextState;
@@ -571,6 +673,7 @@ struct ImGuiContext
ImVec2 OsImePosRequest, OsImePosSet; // Cursor position request & last passed to the OS Input Method Editor
// Settings
+ bool SettingsLoaded;
float SettingsDirtyTimer; // Save .ini Settings on disk when time reaches zero
ImVector<ImGuiWindowSettings> SettingsWindows; // .ini settings for ImGuiWindow
ImVector<ImGuiSettingsHandler> SettingsHandlers; // List of .ini settings handlers
@@ -591,18 +694,19 @@ struct ImGuiContext
int WantTextInputNextFrame;
char TempBuffer[1024*3+1]; // temporary text buffer
- ImGuiContext() : OverlayDrawList(NULL)
+ ImGuiContext(ImFontAtlas* shared_font_atlas) : OverlayDrawList(NULL)
{
Initialized = false;
Font = NULL;
FontSize = FontBaseSize = 0.0f;
+ FontAtlasOwnedByContext = shared_font_atlas ? false : true;
+ IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)();
Time = 0.0f;
FrameCount = 0;
FrameCountEnded = FrameCountRendered = -1;
WindowsActiveCount = 0;
CurrentWindow = NULL;
- NavWindow = NULL;
HoveredWindow = NULL;
HoveredRootWindow = NULL;
HoveredId = 0;
@@ -615,30 +719,48 @@ struct ImGuiContext
ActiveIdIsAlive = false;
ActiveIdIsJustActivated = false;
ActiveIdAllowOverlap = false;
+ ActiveIdAllowNavDirFlags = 0;
ActiveIdClickOffset = ImVec2(-1,-1);
ActiveIdWindow = NULL;
+ ActiveIdSource = ImGuiInputSource_None;
MovingWindow = NULL;
- MovingWindowMoveId = 0;
-
- SetNextWindowPosVal = ImVec2(0.0f, 0.0f);
- SetNextWindowSizeVal = ImVec2(0.0f, 0.0f);
- SetNextWindowCollapsedVal = false;
- SetNextWindowPosCond = 0;
- SetNextWindowSizeCond = 0;
- SetNextWindowContentSizeCond = 0;
- SetNextWindowCollapsedCond = 0;
- SetNextWindowSizeConstraintRect = ImRect();
- SetNextWindowSizeConstraintCallback = NULL;
- SetNextWindowSizeConstraintCallbackUserData = NULL;
- SetNextWindowSizeConstraint = false;
- SetNextWindowFocus = false;
- SetNextTreeNodeOpenVal = false;
- SetNextTreeNodeOpenCond = 0;
+ NextTreeNodeOpenVal = false;
+ NextTreeNodeOpenCond = 0;
+
+ NavWindow = NULL;
+ NavId = NavActivateId = NavActivateDownId = NavActivatePressedId = NavInputId = 0;
+ NavJustTabbedId = NavJustMovedToId = NavNextActivateId = 0;
+ NavInputSource = ImGuiInputSource_None;
+ NavScoringRectScreen = ImRect();
+ NavScoringCount = 0;
+ NavWindowingTarget = NULL;
+ NavWindowingHighlightTimer = NavWindowingHighlightAlpha = 0.0f;
+ NavWindowingToggleLayer = false;
+ NavLayer = 0;
+ NavIdTabCounter = INT_MAX;
+ NavIdIsAlive = false;
+ NavMousePosDirty = false;
+ NavDisableHighlight = true;
+ NavDisableMouseHover = false;
+ NavAnyRequest = false;
+ NavInitRequest = false;
+ NavInitRequestFromMove = false;
+ NavInitResultId = 0;
+ NavMoveFromClampedRefRect = false;
+ NavMoveRequest = false;
+ NavMoveRequestForward = ImGuiNavForward_None;
+ NavMoveDir = NavMoveDirLast = ImGuiDir_None;
+
+ ModalWindowDarkeningRatio = 0.0f;
+ OverlayDrawList._Data = &DrawListSharedData;
+ OverlayDrawList._OwnerName = "##Overlay"; // Give it a name for debugging
+ MouseCursor = ImGuiMouseCursor_Arrow;
DragDropActive = false;
DragDropSourceFlags = 0;
DragDropMouseButton = -1;
DragDropTargetId = 0;
+ DragDropAcceptIdCurrRectSurface = 0.0f;
DragDropAcceptIdPrev = DragDropAcceptIdCurr = 0;
DragDropAcceptFrameCount = -1;
memset(DragDropPayloadBufLocal, 0, sizeof(DragDropPayloadBufLocal));
@@ -654,12 +776,7 @@ struct ImGuiContext
TooltipOverrideCount = 0;
OsImePosRequest = OsImePosSet = ImVec2(-1.0f, -1.0f);
- ModalWindowDarkeningRatio = 0.0f;
- OverlayDrawList._Data = &DrawListSharedData;
- OverlayDrawList._OwnerName = "##Overlay"; // Give it a name for debugging
- MouseCursor = ImGuiMouseCursor_Arrow;
- memset(MouseCursorData, 0, sizeof(MouseCursorData));
-
+ SettingsLoaded = false;
SettingsDirtyTimer = 0.0f;
LogEnabled = false;
@@ -677,13 +794,14 @@ struct ImGuiContext
};
// Transient per-window flags, reset at the beginning of the frame. For child window, inherited from parent on first Begin().
+// This is going to be exposed in imgui.h when stabilized enough.
enum ImGuiItemFlags_
{
ImGuiItemFlags_AllowKeyboardFocus = 1 << 0, // true
ImGuiItemFlags_ButtonRepeat = 1 << 1, // false // Button() will return true multiple times based on io.KeyRepeatDelay and io.KeyRepeatRate settings.
ImGuiItemFlags_Disabled = 1 << 2, // false // FIXME-WIP: Disable interactions but doesn't affect visuals. Should be: grey out and disable interactions with widgets that affect data + view widgets (WIP)
- //ImGuiItemFlags_NoNav = 1 << 3, // false
- //ImGuiItemFlags_NoNavDefaultFocus = 1 << 4, // false
+ ImGuiItemFlags_NoNav = 1 << 3, // false
+ ImGuiItemFlags_NoNavDefaultFocus = 1 << 4, // false
ImGuiItemFlags_SelectableDontClosePopup = 1 << 5, // false // MenuItem/Selectable() automatically closes current Popup window
ImGuiItemFlags_Default_ = ImGuiItemFlags_AllowKeyboardFocus
};
@@ -702,14 +820,23 @@ struct IMGUI_API ImGuiDrawContext
float PrevLineTextBaseOffset;
float LogLinePosY;
int TreeDepth;
+ ImU32 TreeDepthMayJumpToParentOnPop; // Store a copy of !g.NavIdIsAlive for TreeDepth 0..31
ImGuiID LastItemId;
- ImRect LastItemRect;
- bool LastItemRectHoveredRect;
- bool MenuBarAppending;
+ ImGuiItemStatusFlags LastItemStatusFlags;
+ ImRect LastItemRect; // Interaction rect
+ ImRect LastItemDisplayRect; // End-user display rect (only valid if LastItemStatusFlags & ImGuiItemStatusFlags_HasDisplayRect)
+ bool NavHideHighlightOneFrame;
+ bool NavHasScroll; // Set when scrolling can be used (ScrollMax > 0.0f)
+ int NavLayerCurrent; // Current layer, 0..31 (we currently only use 0..1)
+ int NavLayerCurrentMask; // = (1 << NavLayerCurrent) used by ItemAdd prior to clipping.
+ int NavLayerActiveMask; // Which layer have been written to (result from previous frame)
+ int NavLayerActiveMaskNext; // Which layer have been written to (buffer for current frame)
+ bool MenuBarAppending; // FIXME: Remove this
float MenuBarOffsetX;
ImVector<ImGuiWindow*> ChildWindows;
ImGuiStorage* StateStorage;
ImGuiLayoutType LayoutType;
+ ImGuiLayoutType ParentLayoutType; // Layout type of parent window at the time of Begin()
// We store the current settings outside of the vectors to increase memory locality (reduce cache misses). The vectors are rarely modified. Also it allows us to not heap allocate for short-lived windows which are not using those settings.
ImGuiItemFlags ItemFlags; // == ItemFlagsStack.back() [empty == ImGuiItemFlags_Default]
@@ -733,13 +860,19 @@ struct IMGUI_API ImGuiDrawContext
CurrentLineTextBaseOffset = PrevLineTextBaseOffset = 0.0f;
LogLinePosY = -1.0f;
TreeDepth = 0;
+ TreeDepthMayJumpToParentOnPop = 0x00;
LastItemId = 0;
- LastItemRect = ImRect();
- LastItemRectHoveredRect = false;
+ LastItemStatusFlags = 0;
+ LastItemRect = LastItemDisplayRect = ImRect();
+ NavHideHighlightOneFrame = false;
+ NavHasScroll = false;
+ NavLayerActiveMask = NavLayerActiveMaskNext = 0x00;
+ NavLayerCurrent = 0;
+ NavLayerCurrentMask = 1 << 0;
MenuBarAppending = false;
MenuBarOffsetX = 0.0f;
StateStorage = NULL;
- LayoutType = ImGuiLayoutType_Vertical;
+ LayoutType = ParentLayoutType = ImGuiLayoutType_Vertical;
ItemWidth = 0.0f;
ItemFlags = ImGuiItemFlags_Default_;
TextWrapPos = -1.0f;
@@ -770,15 +903,17 @@ struct IMGUI_API ImGuiWindow
float WindowRounding; // Window rounding at the time of begin.
float WindowBorderSize; // Window border size at the time of begin.
ImGuiID MoveId; // == window->GetID("#MOVE")
+ ImGuiID ChildId; // Id of corresponding item in parent window (for child windows)
ImVec2 Scroll;
ImVec2 ScrollTarget; // target scroll position. stored as cursor position with scrolling canceled out, so the highest point is always 0.0f. (FLT_MAX for no change)
ImVec2 ScrollTargetCenterRatio; // 0.0f = scroll so that target position is at top, 0.5f = scroll so that target position is centered
bool ScrollbarX, ScrollbarY;
ImVec2 ScrollbarSizes;
- bool Active; // Set to true on Begin()
+ bool Active; // Set to true on Begin(), unless Collapsed
bool WasActive;
bool WriteAccessed; // Set to true when any widget access the current window
bool Collapsed; // Set when collapsing window to become only title-bar
+ bool CollapseToggleWanted;
bool SkipItems; // Set when items can safely be all clipped (e.g. window not visible or collapsed)
bool Appearing; // Set during the frame where the window is appearing (or re-appearing)
bool CloseButton; // Set when the window has a close button (p_open != NULL)
@@ -801,19 +936,26 @@ struct IMGUI_API ImGuiWindow
ImVector<ImGuiID> IDStack; // ID stack. ID are hashes seeded with the value at the top of the stack
ImRect ClipRect; // = DrawList->clip_rect_stack.back(). Scissoring / clipping rectangle. x1, y1, x2, y2.
ImRect WindowRectClipped; // = WindowRect just after setup in Begin(). == window->Rect() for root window.
- ImRect InnerRect;
+ ImRect InnerRect, InnerClipRect;
int LastFrameActive;
float ItemWidthDefault;
- ImGuiSimpleColumns MenuColumns; // Simplified columns storage for menu items
+ ImGuiMenuColumns MenuColumns; // Simplified columns storage for menu items
ImGuiStorage StateStorage;
ImVector<ImGuiColumnsSet> ColumnsStorage;
float FontWindowScale; // Scale multiplier per-window
ImDrawList* DrawList;
ImGuiWindow* ParentWindow; // If we are a child _or_ popup window, this is pointing to our parent. Otherwise NULL.
- ImGuiWindow* RootWindow; // Generally point to ourself. If we are a child window, this is pointing to the first non-child parent window.
- ImGuiWindow* RootNonPopupWindow; // Generally point to ourself. Used to display TitleBgActive color and for selecting which window to use for NavWindowing
+ ImGuiWindow* RootWindow; // Point to ourself or first ancestor that is not a child window.
+ ImGuiWindow* RootWindowForTitleBarHighlight; // Point to ourself or first ancestor which will display TitleBgActive color when this window is active.
+ ImGuiWindow* RootWindowForTabbing; // Point to ourself or first ancestor which can be CTRL-Tabbed into.
+ ImGuiWindow* RootWindowForNav; // Point to ourself or first ancestor which doesn't have the NavFlattened flag.
+
+ ImGuiWindow* NavLastChildNavWindow; // When going to the menu bar, we remember the child window we came from. (This could probably be made implicit if we kept g.Windows sorted by last focused including child window.)
+ ImGuiID NavLastIds[2]; // Last known NavId for this window, per layer (0/1)
+ ImRect NavRectRel[2]; // Reference rectangle, in window relative space
// Navigation / Focus
+ // FIXME-NAV: Merge all this with the new Nav system, at least the request variables should be moved to ImGuiContext
int FocusIdxAllCounter; // Start at -1 and increase as assigned via FocusItemRegister()
int FocusIdxTabCounter; // (same, but only count widgets which you can Tab through)
int FocusIdxAllRequestCurrent; // Item being requested for focus
@@ -842,13 +984,14 @@ public:
// Backup and restore just enough data to be able to use IsItemHovered() on item A after another B in the same window has overwritten the data.
struct ImGuiItemHoveredDataBackup
{
- ImGuiID LastItemId;
- ImRect LastItemRect;
- bool LastItemRectHoveredRect;
+ ImGuiID LastItemId;
+ ImGuiItemStatusFlags LastItemStatusFlags;
+ ImRect LastItemRect;
+ ImRect LastItemDisplayRect;
ImGuiItemHoveredDataBackup() { Backup(); }
- void Backup() { ImGuiWindow* window = GImGui->CurrentWindow; LastItemId = window->DC.LastItemId; LastItemRect = window->DC.LastItemRect; LastItemRectHoveredRect = window->DC.LastItemRectHoveredRect; }
- void Restore() const { ImGuiWindow* window = GImGui->CurrentWindow; window->DC.LastItemId = LastItemId; window->DC.LastItemRect = LastItemRect; window->DC.LastItemRectHoveredRect = LastItemRectHoveredRect; }
+ void Backup() { ImGuiWindow* window = GImGui->CurrentWindow; LastItemId = window->DC.LastItemId; LastItemStatusFlags = window->DC.LastItemStatusFlags; LastItemRect = window->DC.LastItemRect; LastItemDisplayRect = window->DC.LastItemDisplayRect; }
+ void Restore() const { ImGuiWindow* window = GImGui->CurrentWindow; window->DC.LastItemId = LastItemId; window->DC.LastItemStatusFlags = LastItemStatusFlags; window->DC.LastItemRect = LastItemRect; window->DC.LastItemDisplayRect = LastItemDisplayRect; }
};
//-----------------------------------------------------------------------------
@@ -869,21 +1012,28 @@ namespace ImGui
IMGUI_API void BringWindowToFront(ImGuiWindow* window);
IMGUI_API void BringWindowToBack(ImGuiWindow* window);
IMGUI_API bool IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent);
+ IMGUI_API bool IsWindowNavFocusable(ImGuiWindow* window);
- IMGUI_API void Initialize();
+ IMGUI_API void Initialize(ImGuiContext* context);
+ IMGUI_API void Shutdown(ImGuiContext* context); // Since 1.60 this is a _private_ function. You can call DestroyContext() to destroy the context created by CreateContext().
+
+ IMGUI_API void NewFrameUpdateHoveredWindowAndCaptureFlags();
IMGUI_API void MarkIniSettingsDirty();
- IMGUI_API ImGuiSettingsHandler* FindSettingsHandler(ImGuiID type_id);
+ IMGUI_API ImGuiSettingsHandler* FindSettingsHandler(const char* type_name);
IMGUI_API ImGuiWindowSettings* FindWindowSettings(ImGuiID id);
IMGUI_API void SetActiveID(ImGuiID id, ImGuiWindow* window);
+ IMGUI_API ImGuiID GetActiveID();
+ IMGUI_API void SetFocusID(ImGuiID id, ImGuiWindow* window);
IMGUI_API void ClearActiveID();
IMGUI_API void SetHoveredID(ImGuiID id);
+ IMGUI_API ImGuiID GetHoveredID();
IMGUI_API void KeepAliveID(ImGuiID id);
IMGUI_API void ItemSize(const ImVec2& size, float text_offset_y = 0.0f);
IMGUI_API void ItemSize(const ImRect& bb, float text_offset_y = 0.0f);
- IMGUI_API bool ItemAdd(const ImRect& bb, ImGuiID id);
+ IMGUI_API bool ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb = NULL);
IMGUI_API bool ItemHoverable(const ImRect& bb, ImGuiID id);
IMGUI_API bool IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged);
IMGUI_API bool FocusableItemRegister(ImGuiWindow* window, ImGuiID id, bool tab_stop = true); // Return true if focus is requested
@@ -894,12 +1044,21 @@ namespace ImGui
IMGUI_API void PushItemFlag(ImGuiItemFlags option, bool enabled);
IMGUI_API void PopItemFlag();
- IMGUI_API void OpenPopupEx(ImGuiID id, bool reopen_existing);
+ IMGUI_API void SetCurrentFont(ImFont* font);
+
+ IMGUI_API void OpenPopupEx(ImGuiID id);
IMGUI_API void ClosePopup(ImGuiID id);
+ IMGUI_API void ClosePopupsOverWindow(ImGuiWindow* ref_window);
IMGUI_API bool IsPopupOpen(ImGuiID id);
IMGUI_API bool BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags);
IMGUI_API void BeginTooltipEx(ImGuiWindowFlags extra_flags, bool override_previous_tooltip = true);
+ IMGUI_API void NavInitWindow(ImGuiWindow* window, bool force_reinit);
+ IMGUI_API void NavMoveRequestCancel();
+ IMGUI_API void ActivateItem(ImGuiID id); // Remotely activate a button, checkbox, tree node etc. given its unique ID. activation is queued and processed on the next frame when the item is encountered again.
+
+ IMGUI_API float GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode);
+ IMGUI_API ImVec2 GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInputReadMode mode, float slow_factor = 0.0f, float fast_factor = 0.0f);
IMGUI_API int CalcTypematicPressedRepeatAmount(float t, float t_prev, float repeat_delay, float repeat_rate);
IMGUI_API void Scrollbar(ImGuiLayoutType direction);
@@ -923,16 +1082,16 @@ namespace ImGui
IMGUI_API void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border = true, float rounding = 0.0f);
IMGUI_API void RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding = 0.0f);
IMGUI_API void RenderColorRectWithAlphaCheckerboard(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, float grid_step, ImVec2 grid_off, float rounding = 0.0f, int rounding_corners_flags = ~0);
- IMGUI_API void RenderTriangle(ImVec2 pos, ImGuiDir dir, float scale = 1.0f);
+ IMGUI_API void RenderArrow(ImVec2 pos, ImGuiDir dir, float scale = 1.0f);
IMGUI_API void RenderBullet(ImVec2 pos);
IMGUI_API void RenderCheckMark(ImVec2 pos, ImU32 col, float sz);
+ IMGUI_API void RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags = ImGuiNavHighlightFlags_TypeDefault); // Navigation highlight
IMGUI_API void RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float x_start_norm, float x_end_norm, float rounding);
IMGUI_API const char* FindRenderedTextEnd(const char* text, const char* text_end = NULL); // Find the optional ## from which we stop displaying text.
IMGUI_API bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags = 0);
IMGUI_API bool ButtonEx(const char* label, const ImVec2& size_arg = ImVec2(0,0), ImGuiButtonFlags flags = 0);
IMGUI_API bool CloseButton(ImGuiID id, const ImVec2& pos, float radius);
- IMGUI_API bool ArrowButton(ImGuiID id, ImGuiDir dir, ImVec2 padding, ImGuiButtonFlags flags = 0);
IMGUI_API bool SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_min, float v_max, float power, int decimal_precision, ImGuiSliderFlags flags = 0);
IMGUI_API bool SliderFloatN(const char* label, float* v, int components, float v_min, float v_max, const char* display_format, float power);
@@ -960,7 +1119,7 @@ namespace ImGui
IMGUI_API int ParseFormatPrecision(const char* fmt, int default_value);
IMGUI_API float RoundScalar(float value, int decimal_precision);
- // Shade functions
+ // Shade functions (write over already created vertices)
IMGUI_API void ShadeVertsLinearColorGradientKeepAlpha(ImDrawVert* vert_start, ImDrawVert* vert_end, ImVec2 gradient_p0, ImVec2 gradient_p1, ImU32 col0, ImU32 col1);
IMGUI_API void ShadeVertsLinearAlphaGradientForLeftToRightText(ImDrawVert* vert_start, ImDrawVert* vert_end, float gradient_p0_x, float gradient_p1_x);
IMGUI_API void ShadeVertsLinearUV(ImDrawVert* vert_start, ImDrawVert* vert_end, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, bool clamp);
diff --git a/imgui/stb_rect_pack.h b/imgui/stb_rect_pack.h
index c75527da..2b07dcc8 100644
--- a/imgui/stb_rect_pack.h
+++ b/imgui/stb_rect_pack.h
@@ -1,4 +1,4 @@
-// stb_rect_pack.h - v0.10 - public domain - rectangle packing
+// stb_rect_pack.h - v0.11 - public domain - rectangle packing
// Sean Barrett 2014
//
// Useful for e.g. packing rectangular textures into an atlas.
@@ -27,11 +27,14 @@
// Sean Barrett
// Minor features
// Martins Mozeiko
+// github:IntellectualKitty
+//
// Bugfixes / warning fixes
// Jeremy Jaussaud
//
// Version history:
//
+// 0.11 (2017-03-03) return packing success/fail result
// 0.10 (2016-10-25) remove cast-away-const to avoid warnings
// 0.09 (2016-08-27) fix compiler warnings
// 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0)
@@ -43,9 +46,7 @@
//
// LICENSE
//
-// This software is dual-licensed to the public domain and under the following
-// license: you are granted a perpetual, irrevocable license to copy, modify,
-// publish, and distribute this file as you see fit.
+// See end of file for license information.
//////////////////////////////////////////////////////////////////////////////
//
@@ -77,7 +78,7 @@ typedef int stbrp_coord;
typedef unsigned short stbrp_coord;
#endif
-STBRP_DEF void stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects);
+STBRP_DEF int stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects);
// Assign packed locations to rectangles. The rectangles are of type
// 'stbrp_rect' defined below, stored in the array 'rects', and there
// are 'num_rects' many of them.
@@ -98,6 +99,9 @@ STBRP_DEF void stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int
// arrays will probably produce worse packing results than calling it
// a single time with the full rectangle array, but the option is
// available.
+//
+// The function returns 1 if all of the rectangles were successfully
+// packed and 0 otherwise.
struct stbrp_rect
{
@@ -202,8 +206,10 @@ struct stbrp_context
#ifdef _MSC_VER
#define STBRP__NOTUSED(v) (void)(v)
+#define STBRP__CDECL __cdecl
#else
#define STBRP__NOTUSED(v) (void)sizeof(v)
+#define STBRP__CDECL
#endif
enum
@@ -488,17 +494,14 @@ static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, i
STBRP_ASSERT(cur->next == NULL);
{
- stbrp_node *L1 = NULL, *L2 = NULL;
int count=0;
cur = context->active_head;
while (cur) {
- L1 = cur;
cur = cur->next;
++count;
}
cur = context->free_head;
while (cur) {
- L2 = cur;
cur = cur->next;
++count;
}
@@ -509,7 +512,7 @@ static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, i
return res;
}
-static int rect_height_compare(const void *a, const void *b)
+static int STBRP__CDECL rect_height_compare(const void *a, const void *b)
{
const stbrp_rect *p = (const stbrp_rect *) a;
const stbrp_rect *q = (const stbrp_rect *) b;
@@ -520,18 +523,7 @@ static int rect_height_compare(const void *a, const void *b)
return (p->w > q->w) ? -1 : (p->w < q->w);
}
-static int rect_width_compare(const void *a, const void *b)
-{
- const stbrp_rect *p = (const stbrp_rect *) a;
- const stbrp_rect *q = (const stbrp_rect *) b;
- if (p->w > q->w)
- return -1;
- if (p->w < q->w)
- return 1;
- return (p->h > q->h) ? -1 : (p->h < q->h);
-}
-
-static int rect_original_order(const void *a, const void *b)
+static int STBRP__CDECL rect_original_order(const void *a, const void *b)
{
const stbrp_rect *p = (const stbrp_rect *) a;
const stbrp_rect *q = (const stbrp_rect *) b;
@@ -544,9 +536,9 @@ static int rect_original_order(const void *a, const void *b)
#define STBRP__MAXVAL 0xffff
#endif
-STBRP_DEF void stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects)
+STBRP_DEF int stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects)
{
- int i;
+ int i, all_rects_packed = 1;
// we use the 'was_packed' field internally to allow sorting/unsorting
for (i=0; i < num_rects; ++i) {
@@ -576,8 +568,56 @@ STBRP_DEF void stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int n
// unsort
STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order);
- // set was_packed flags
- for (i=0; i < num_rects; ++i)
+ // set was_packed flags and all_rects_packed status
+ for (i=0; i < num_rects; ++i) {
rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL);
+ if (!rects[i].was_packed)
+ all_rects_packed = 0;
+ }
+
+ // return the all_rects_packed status
+ return all_rects_packed;
}
#endif
+
+/*
+------------------------------------------------------------------------------
+This software is available under 2 licenses -- choose whichever you prefer.
+------------------------------------------------------------------------------
+ALTERNATIVE A - MIT License
+Copyright (c) 2017 Sean Barrett
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+------------------------------------------------------------------------------
+ALTERNATIVE B - Public Domain (www.unlicense.org)
+This is free and unencumbered software released into the public domain.
+Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
+software, either in source code form or as a compiled binary, for any purpose,
+commercial or non-commercial, and by any means.
+In jurisdictions that recognize copyright laws, the author or authors of this
+software dedicate any and all copyright interest in the software to the public
+domain. We make this dedication for the benefit of the public at large and to
+the detriment of our heirs and successors. We intend this dedication to be an
+overt act of relinquishment in perpetuity of all present and future rights to
+this software under copyright law.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+------------------------------------------------------------------------------
+*/
diff --git a/imgui/stb_textedit.h b/imgui/stb_textedit.h
index 4b731a0c..7324fb6b 100644
--- a/imgui/stb_textedit.h
+++ b/imgui/stb_textedit.h
@@ -677,9 +677,8 @@ static int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)
}
// API paste: replace existing selection with passed-in text
-static int stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE const *ctext, int len)
+static int stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE const *text, int len)
{
- STB_TEXTEDIT_CHARTYPE *text = (STB_TEXTEDIT_CHARTYPE *) ctext;
// if there's a selection, the paste should delete it
stb_textedit_clamp(str, state);
stb_textedit_delete_selection(str,state);
diff --git a/imgui/stb_truetype.h b/imgui/stb_truetype.h
index 92b9a875..f65deb50 100644
--- a/imgui/stb_truetype.h
+++ b/imgui/stb_truetype.h
@@ -1,4 +1,4 @@
-// stb_truetype.h - v1.14 - public domain
+// stb_truetype.h - v1.19 - public domain
// authored from 2009-2016 by Sean Barrett / RAD Game Tools
//
// This library processes TrueType files:
@@ -6,6 +6,7 @@
// extract glyph metrics
// extract glyph shapes
// render glyphs to one-channel bitmaps with antialiasing (box filter)
+// render glyphs to one-channel SDF bitmaps (signed-distance field/function)
//
// Todo:
// non-MS cmaps
@@ -21,39 +22,40 @@
// Mikko Mononen: compound shape support, more cmap formats
// Tor Andersson: kerning, subpixel rendering
// Dougall Johnson: OpenType / Type 2 font handling
+// Daniel Ribeiro Maciel: basic GPOS-based kerning
//
// Misc other:
// Ryan Gordon
// Simon Glass
// github:IntellectualKitty
+// Imanol Celaya
+// Daniel Ribeiro Maciel
//
// Bug/warning reports/fixes:
-// "Zer" on mollyrocket (with fix)
-// Cass Everitt
-// stoiko (Haemimont Games)
-// Brian Hook
-// Walter van Niftrik
-// David Gow
-// David Given
-// Ivan-Assen Ivanov
-// Anthony Pesch
-// Johan Duparc
-// Hou Qiming
-// Fabian "ryg" Giesen
-// Martins Mozeiko
-// Cap Petschulat
-// Omar Cornut
-// github:aloucks
-// Peter LaValle
-// Sergey Popov
-// Giumo X. Clanjor
-// Higor Euripedes
-// Thomas Fields
-// Derek Vinyard
-//
+// "Zer" on mollyrocket Fabian "ryg" Giesen
+// Cass Everitt Martins Mozeiko
+// stoiko (Haemimont Games) Cap Petschulat
+// Brian Hook Omar Cornut
+// Walter van Niftrik github:aloucks
+// David Gow Peter LaValle
+// David Given Sergey Popov
+// Ivan-Assen Ivanov Giumo X. Clanjor
+// Anthony Pesch Higor Euripedes
+// Johan Duparc Thomas Fields
+// Hou Qiming Derek Vinyard
+// Rob Loach Cort Stratton
+// Kenney Phillis Jr. github:oyvindjam
+// Brian Costabile github:vassvik
+//
// VERSION HISTORY
//
-// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts, num-fonts-in-TTC function
+// 1.19 (2018-02-11) GPOS kerning, STBTT_fmod
+// 1.18 (2018-01-29) add missing function
+// 1.17 (2017-07-23) make more arguments const; doc fix
+// 1.16 (2017-07-12) SDF support
+// 1.15 (2017-03-03) make more arguments const
+// 1.14 (2017-01-16) num-fonts-in-TTC function
+// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts
// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual
// 1.11 (2016-04-02) fix unused-variable warning
// 1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef
@@ -69,9 +71,7 @@
//
// LICENSE
//
-// This software is dual-licensed to the public domain and under the following
-// license: you are granted a perpetual, irrevocable license to copy, modify,
-// publish, and distribute this file as you see fit.
+// See end of file for license information.
//
// USAGE
//
@@ -91,7 +91,7 @@
// Improved 3D API (more shippable):
// #include "stb_rect_pack.h" -- optional, but you really want it
// stbtt_PackBegin()
-// stbtt_PackSetOversample() -- for improved quality on small fonts
+// stbtt_PackSetOversampling() -- for improved quality on small fonts
// stbtt_PackFontRanges() -- pack and renders
// stbtt_PackEnd()
// stbtt_GetPackedQuad()
@@ -109,6 +109,7 @@
// Character advance/positioning
// stbtt_GetCodepointHMetrics()
// stbtt_GetFontVMetrics()
+// stbtt_GetFontVMetricsOS2()
// stbtt_GetCodepointKernAdvance()
//
// Starting with version 1.06, the rasterizer was replaced with a new,
@@ -164,7 +165,7 @@
// measurement for describing font size, defined as 72 points per inch.
// stb_truetype provides a point API for compatibility. However, true
// "per inch" conventions don't make much sense on computer displays
-// since they different monitors have different number of pixels per
+// since different monitors have different number of pixels per
// inch. For example, Windows traditionally uses a convention that
// there are 96 pixels per inch, thus making 'inch' measurements have
// nothing to do with inches, and thus effectively defining a point to
@@ -174,6 +175,39 @@
// for non-commercial fonts, thus making fonts scaled in points
// according to the TrueType spec incoherently sized in practice.
//
+// DETAILED USAGE:
+//
+// Scale:
+// Select how high you want the font to be, in points or pixels.
+// Call ScaleForPixelHeight or ScaleForMappingEmToPixels to compute
+// a scale factor SF that will be used by all other functions.
+//
+// Baseline:
+// You need to select a y-coordinate that is the baseline of where
+// your text will appear. Call GetFontBoundingBox to get the baseline-relative
+// bounding box for all characters. SF*-y0 will be the distance in pixels
+// that the worst-case character could extend above the baseline, so if
+// you want the top edge of characters to appear at the top of the
+// screen where y=0, then you would set the baseline to SF*-y0.
+//
+// Current point:
+// Set the current point where the first character will appear. The
+// first character could extend left of the current point; this is font
+// dependent. You can either choose a current point that is the leftmost
+// point and hope, or add some padding, or check the bounding box or
+// left-side-bearing of the first character to be displayed and set
+// the current point based on that.
+//
+// Displaying a character:
+// Compute the bounding box of the character. It will contain signed values
+// relative to <current_point, baseline>. I.e. if it returns x0,y0,x1,y1,
+// then the character should be displayed in the rectangle from
+// <current_point+SF*x0, baseline+SF*y0> to <current_point+SF*x1,baseline+SF*y1).
+//
+// Advancing for the next character:
+// Call GlyphHMetrics, and compute 'current_point += SF * advance'.
+//
+//
// ADVANCED USAGE
//
// Quality:
@@ -380,7 +414,8 @@ int main(int arg, char **argv)
//// INTEGRATION WITH YOUR CODEBASE
////
//// The following sections allow you to supply alternate definitions
-//// of C library functions used by stb_truetype.
+//// of C library functions used by stb_truetype, e.g. if you don't
+//// link with the C runtime library.
#ifdef STB_TRUETYPE_IMPLEMENTATION
// #define your own (u)stbtt_int8/16/32 before including to override this
@@ -396,7 +431,7 @@ int main(int arg, char **argv)
typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1];
typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1];
- // #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h
+ // e.g. #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h
#ifndef STBTT_ifloor
#include <math.h>
#define STBTT_ifloor(x) ((int) floor(x))
@@ -406,6 +441,18 @@ int main(int arg, char **argv)
#ifndef STBTT_sqrt
#include <math.h>
#define STBTT_sqrt(x) sqrt(x)
+ #define STBTT_pow(x,y) pow(x,y)
+ #endif
+
+ #ifndef STBTT_fmod
+ #include <math.h>
+ #define STBTT_fmod(x,y) fmod(x,y)
+ #endif
+
+ #ifndef STBTT_cos
+ #include <math.h>
+ #define STBTT_cos(x) cos(x)
+ #define STBTT_acos(x) acos(x)
#endif
#ifndef STBTT_fabs
@@ -431,7 +478,7 @@ int main(int arg, char **argv)
#endif
#ifndef STBTT_memcpy
- #include <memory.h>
+ #include <string.h>
#define STBTT_memcpy memcpy
#define STBTT_memset memset
#endif
@@ -494,7 +541,7 @@ typedef struct
float x1,y1,s1,t1; // bottom-right
} stbtt_aligned_quad;
-STBTT_DEF void stbtt_GetBakedQuad(stbtt_bakedchar *chardata, int pw, int ph, // same data as above
+STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, // same data as above
int char_index, // character to display
float *xpos, float *ypos, // pointers to current position in screen pixel space
stbtt_aligned_quad *q, // output: quad to draw
@@ -547,7 +594,7 @@ STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc);
#define STBTT_POINT_SIZE(x) (-(x))
-STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, float font_size,
+STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size,
int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range);
// Creates character bitmaps from the font_index'th font found in fontdata (use
// font_index=0 if you don't know what that is). It creates num_chars_in_range
@@ -572,7 +619,7 @@ typedef struct
unsigned char h_oversample, v_oversample; // don't set these, they're used internally
} stbtt_pack_range;
-STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges);
+STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges);
// Creates character bitmaps from multiple ranges of characters stored in
// ranges. This will usually create a better-packed bitmap than multiple
// calls to stbtt_PackFontRange. Note that you can call this multiple
@@ -594,7 +641,7 @@ STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h
// To use with PackFontRangesGather etc., you must set it before calls
// call to PackFontRangesGatherRects.
-STBTT_DEF void stbtt_GetPackedQuad(stbtt_packedchar *chardata, int pw, int ph, // same data as above
+STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, // same data as above
int char_index, // character to display
float *xpos, float *ypos, // pointers to current position in screen pixel space
stbtt_aligned_quad *q, // output: quad to draw
@@ -657,7 +704,7 @@ struct stbtt_fontinfo
int numGlyphs; // number of glyphs, needed for range checking
- int loca,head,glyf,hhea,hmtx,kern; // table locations as offset from start of .ttf
+ int loca,head,glyf,hhea,hmtx,kern,gpos; // table locations as offset from start of .ttf
int index_map; // a cmap mapping for our chosen character encoding
int indexToLocFormat; // format needed to map from glyph index to glyph
@@ -714,6 +761,12 @@ STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, in
// these are expressed in unscaled coordinates, so you must multiply by
// the scale factor for a given size
+STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap);
+// analogous to GetFontVMetrics, but returns the "typographic" values from the OS/2
+// table (specific to MS/Windows TTF files).
+//
+// Returns 1 on success (table present), 0 on failure.
+
STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1);
// the bounding box around all possible characters
@@ -808,6 +861,10 @@ STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, uns
// same as stbtt_MakeCodepointBitmap, but you can specify a subpixel
// shift for the character
+STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint);
+// same as stbtt_MakeCodepointBitmapSubpixel, but prefiltering
+// is performed (see stbtt_PackSetOversampling)
+
STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);
// get the bbox of the bitmap centered around the glyph origin; so the
// bitmap width is ix1-ix0, height is iy1-iy0, and location to place
@@ -825,6 +882,7 @@ STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float
STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff);
STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph);
STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph);
+STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int glyph);
STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);
STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1);
@@ -849,6 +907,64 @@ STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, // 1-channel bitmap
//////////////////////////////////////////////////////////////////////////////
//
+// Signed Distance Function (or Field) rendering
+
+STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata);
+// frees the SDF bitmap allocated below
+
+STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff);
+STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff);
+// These functions compute a discretized SDF field for a single character, suitable for storing
+// in a single-channel texture, sampling with bilinear filtering, and testing against
+// larger than some threshhold to produce scalable fonts.
+// info -- the font
+// scale -- controls the size of the resulting SDF bitmap, same as it would be creating a regular bitmap
+// glyph/codepoint -- the character to generate the SDF for
+// padding -- extra "pixels" around the character which are filled with the distance to the character (not 0),
+// which allows effects like bit outlines
+// onedge_value -- value 0-255 to test the SDF against to reconstruct the character (i.e. the isocontour of the character)
+// pixel_dist_scale -- what value the SDF should increase by when moving one SDF "pixel" away from the edge (on the 0..255 scale)
+// if positive, > onedge_value is inside; if negative, < onedge_value is inside
+// width,height -- output height & width of the SDF bitmap (including padding)
+// xoff,yoff -- output origin of the character
+// return value -- a 2D array of bytes 0..255, width*height in size
+//
+// pixel_dist_scale & onedge_value are a scale & bias that allows you to make
+// optimal use of the limited 0..255 for your application, trading off precision
+// and special effects. SDF values outside the range 0..255 are clamped to 0..255.
+//
+// Example:
+// scale = stbtt_ScaleForPixelHeight(22)
+// padding = 5
+// onedge_value = 180
+// pixel_dist_scale = 180/5.0 = 36.0
+//
+// This will create an SDF bitmap in which the character is about 22 pixels
+// high but the whole bitmap is about 22+5+5=32 pixels high. To produce a filled
+// shape, sample the SDF at each pixel and fill the pixel if the SDF value
+// is greater than or equal to 180/255. (You'll actually want to antialias,
+// which is beyond the scope of this example.) Additionally, you can compute
+// offset outlines (e.g. to stroke the character border inside & outside,
+// or only outside). For example, to fill outside the character up to 3 SDF
+// pixels, you would compare against (180-36.0*3)/255 = 72/255. The above
+// choice of variables maps a range from 5 pixels outside the shape to
+// 2 pixels inside the shape to 0..255; this is intended primarily for apply
+// outside effects only (the interior range is needed to allow proper
+// antialiasing of the font at *smaller* sizes)
+//
+// The function computes the SDF analytically at each SDF pixel, not by e.g.
+// building a higher-res bitmap and approximating it. In theory the quality
+// should be as high as possible for an SDF of this size & representation, but
+// unclear if this is true in practice (perhaps building a higher-res bitmap
+// and computing from that can allow drop-out prevention).
+//
+// The algorithm has not been optimized at all, so expect it to be slow
+// if computing lots of characters or very large sizes.
+
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
// Finding the right font...
//
// You should really just solve this offline, keep your own tables
@@ -1231,6 +1347,7 @@ static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, in
info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required
info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required
info->kern = stbtt__find_table(data, fontstart, "kern"); // not required
+ info->gpos = stbtt__find_table(data, fontstart, "GPOS"); // not required
if (!cmap || !info->head || !info->hhea || !info->hmtx)
return 0;
@@ -2084,7 +2201,7 @@ static int stbtt__run_charstring(const stbtt_fontinfo *info, int glyph_index, st
// push immediate
if (b0 == 255) {
- f = (float)stbtt__buf_get32(&b) / 0x10000;
+ f = (float)(stbtt_int32)stbtt__buf_get32(&b) / 0x10000;
} else {
stbtt__buf_skip(&b, -1);
f = (float)(stbtt_int16)stbtt__cff_int(&b);
@@ -2122,12 +2239,10 @@ static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, in
{
stbtt__csctx c = STBTT__CSCTX_INIT(1);
int r = stbtt__run_charstring(info, glyph_index, &c);
- if (x0) {
- *x0 = r ? c.min_x : 0;
- *y0 = r ? c.min_y : 0;
- *x1 = r ? c.max_x : 0;
- *y1 = r ? c.max_y : 0;
- }
+ if (x0) *x0 = r ? c.min_x : 0;
+ if (y0) *y0 = r ? c.min_y : 0;
+ if (x1) *x1 = r ? c.max_x : 0;
+ if (y1) *y1 = r ? c.max_y : 0;
return r ? c.num_vertices : 0;
}
@@ -2151,7 +2266,7 @@ STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_inde
}
}
-STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2)
+static int stbtt__GetGlyphKernInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2)
{
stbtt_uint8 *data = info->data + info->kern;
stbtt_uint32 needle, straw;
@@ -2181,9 +2296,261 @@ STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1,
return 0;
}
+static stbtt_int32 stbtt__GetCoverageIndex(stbtt_uint8 *coverageTable, int glyph)
+{
+ stbtt_uint16 coverageFormat = ttUSHORT(coverageTable);
+ switch(coverageFormat) {
+ case 1: {
+ stbtt_uint16 glyphCount = ttUSHORT(coverageTable + 2);
+
+ // Binary search.
+ stbtt_int32 l=0, r=glyphCount-1, m;
+ int straw, needle=glyph;
+ while (l <= r) {
+ stbtt_uint8 *glyphArray = coverageTable + 4;
+ stbtt_uint16 glyphID;
+ m = (l + r) >> 1;
+ glyphID = ttUSHORT(glyphArray + 2 * m);
+ straw = glyphID;
+ if (needle < straw)
+ r = m - 1;
+ else if (needle > straw)
+ l = m + 1;
+ else {
+ return m;
+ }
+ }
+ } break;
+
+ case 2: {
+ stbtt_uint16 rangeCount = ttUSHORT(coverageTable + 2);
+ stbtt_uint8 *rangeArray = coverageTable + 4;
+
+ // Binary search.
+ stbtt_int32 l=0, r=rangeCount-1, m;
+ int strawStart, strawEnd, needle=glyph;
+ while (l <= r) {
+ stbtt_uint8 *rangeRecord;
+ m = (l + r) >> 1;
+ rangeRecord = rangeArray + 6 * m;
+ strawStart = ttUSHORT(rangeRecord);
+ strawEnd = ttUSHORT(rangeRecord + 2);
+ if (needle < strawStart)
+ r = m - 1;
+ else if (needle > strawEnd)
+ l = m + 1;
+ else {
+ stbtt_uint16 startCoverageIndex = ttUSHORT(rangeRecord + 4);
+ return startCoverageIndex + glyph - strawStart;
+ }
+ }
+ } break;
+
+ default: {
+ // There are no other cases.
+ STBTT_assert(0);
+ } break;
+ }
+
+ return -1;
+}
+
+static stbtt_int32 stbtt__GetGlyphClass(stbtt_uint8 *classDefTable, int glyph)
+{
+ stbtt_uint16 classDefFormat = ttUSHORT(classDefTable);
+ switch(classDefFormat)
+ {
+ case 1: {
+ stbtt_uint16 startGlyphID = ttUSHORT(classDefTable + 2);
+ stbtt_uint16 glyphCount = ttUSHORT(classDefTable + 4);
+ stbtt_uint8 *classDef1ValueArray = classDefTable + 6;
+
+ if (glyph >= startGlyphID && glyph < startGlyphID + glyphCount)
+ return (stbtt_int32)ttUSHORT(classDef1ValueArray + 2 * (glyph - startGlyphID));
+
+ classDefTable = classDef1ValueArray + 2 * glyphCount;
+ } break;
+
+ case 2: {
+ stbtt_uint16 classRangeCount = ttUSHORT(classDefTable + 2);
+ stbtt_uint8 *classRangeRecords = classDefTable + 4;
+
+ // Binary search.
+ stbtt_int32 l=0, r=classRangeCount-1, m;
+ int strawStart, strawEnd, needle=glyph;
+ while (l <= r) {
+ stbtt_uint8 *classRangeRecord;
+ m = (l + r) >> 1;
+ classRangeRecord = classRangeRecords + 6 * m;
+ strawStart = ttUSHORT(classRangeRecord);
+ strawEnd = ttUSHORT(classRangeRecord + 2);
+ if (needle < strawStart)
+ r = m - 1;
+ else if (needle > strawEnd)
+ l = m + 1;
+ else
+ return (stbtt_int32)ttUSHORT(classRangeRecord + 4);
+ }
+
+ classDefTable = classRangeRecords + 6 * classRangeCount;
+ } break;
+
+ default: {
+ // There are no other cases.
+ STBTT_assert(0);
+ } break;
+ }
+
+ return -1;
+}
+
+// Define to STBTT_assert(x) if you want to break on unimplemented formats.
+#define STBTT_GPOS_TODO_assert(x)
+
+static stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2)
+{
+ stbtt_uint16 lookupListOffset;
+ stbtt_uint8 *lookupList;
+ stbtt_uint16 lookupCount;
+ stbtt_uint8 *data;
+ stbtt_int32 i;
+
+ if (!info->gpos) return 0;
+
+ data = info->data + info->gpos;
+
+ if (ttUSHORT(data+0) != 1) return 0; // Major version 1
+ if (ttUSHORT(data+2) != 0) return 0; // Minor version 0
+
+ lookupListOffset = ttUSHORT(data+8);
+ lookupList = data + lookupListOffset;
+ lookupCount = ttUSHORT(lookupList);
+
+ for (i=0; i<lookupCount; ++i) {
+ stbtt_uint16 lookupOffset = ttUSHORT(lookupList + 2 + 2 * i);
+ stbtt_uint8 *lookupTable = lookupList + lookupOffset;
+
+ stbtt_uint16 lookupType = ttUSHORT(lookupTable);
+ stbtt_uint16 subTableCount = ttUSHORT(lookupTable + 4);
+ stbtt_uint8 *subTableOffsets = lookupTable + 6;
+ switch(lookupType) {
+ case 2: { // Pair Adjustment Positioning Subtable
+ stbtt_int32 sti;
+ for (sti=0; sti<subTableCount; sti++) {
+ stbtt_uint16 subtableOffset = ttUSHORT(subTableOffsets + 2 * sti);
+ stbtt_uint8 *table = lookupTable + subtableOffset;
+ stbtt_uint16 posFormat = ttUSHORT(table);
+ stbtt_uint16 coverageOffset = ttUSHORT(table + 2);
+ stbtt_int32 coverageIndex = stbtt__GetCoverageIndex(table + coverageOffset, glyph1);
+ if (coverageIndex == -1) continue;
+
+ switch (posFormat) {
+ case 1: {
+ stbtt_int32 l, r, m;
+ int straw, needle;
+ stbtt_uint16 valueFormat1 = ttUSHORT(table + 4);
+ stbtt_uint16 valueFormat2 = ttUSHORT(table + 6);
+ stbtt_int32 valueRecordPairSizeInBytes = 2;
+ stbtt_uint16 pairSetCount = ttUSHORT(table + 8);
+ stbtt_uint16 pairPosOffset = ttUSHORT(table + 10 + 2 * coverageIndex);
+ stbtt_uint8 *pairValueTable = table + pairPosOffset;
+ stbtt_uint16 pairValueCount = ttUSHORT(pairValueTable);
+ stbtt_uint8 *pairValueArray = pairValueTable + 2;
+ // TODO: Support more formats.
+ STBTT_GPOS_TODO_assert(valueFormat1 == 4);
+ if (valueFormat1 != 4) return 0;
+ STBTT_GPOS_TODO_assert(valueFormat2 == 0);
+ if (valueFormat2 != 0) return 0;
+
+ STBTT_assert(coverageIndex < pairSetCount);
+ STBTT__NOTUSED(pairSetCount);
+
+ needle=glyph2;
+ r=pairValueCount-1;
+ l=0;
+
+ // Binary search.
+ while (l <= r) {
+ stbtt_uint16 secondGlyph;
+ stbtt_uint8 *pairValue;
+ m = (l + r) >> 1;
+ pairValue = pairValueArray + (2 + valueRecordPairSizeInBytes) * m;
+ secondGlyph = ttUSHORT(pairValue);
+ straw = secondGlyph;
+ if (needle < straw)
+ r = m - 1;
+ else if (needle > straw)
+ l = m + 1;
+ else {
+ stbtt_int16 xAdvance = ttSHORT(pairValue + 2);
+ return xAdvance;
+ }
+ }
+ } break;
+
+ case 2: {
+ stbtt_uint16 valueFormat1 = ttUSHORT(table + 4);
+ stbtt_uint16 valueFormat2 = ttUSHORT(table + 6);
+
+ stbtt_uint16 classDef1Offset = ttUSHORT(table + 8);
+ stbtt_uint16 classDef2Offset = ttUSHORT(table + 10);
+ int glyph1class = stbtt__GetGlyphClass(table + classDef1Offset, glyph1);
+ int glyph2class = stbtt__GetGlyphClass(table + classDef2Offset, glyph2);
+
+ stbtt_uint16 class1Count = ttUSHORT(table + 12);
+ stbtt_uint16 class2Count = ttUSHORT(table + 14);
+ STBTT_assert(glyph1class < class1Count);
+ STBTT_assert(glyph2class < class2Count);
+
+ // TODO: Support more formats.
+ STBTT_GPOS_TODO_assert(valueFormat1 == 4);
+ if (valueFormat1 != 4) return 0;
+ STBTT_GPOS_TODO_assert(valueFormat2 == 0);
+ if (valueFormat2 != 0) return 0;
+
+ if (glyph1class >= 0 && glyph1class < class1Count && glyph2class >= 0 && glyph2class < class2Count) {
+ stbtt_uint8 *class1Records = table + 16;
+ stbtt_uint8 *class2Records = class1Records + 2 * (glyph1class * class2Count);
+ stbtt_int16 xAdvance = ttSHORT(class2Records + 2 * glyph2class);
+ return xAdvance;
+ }
+ } break;
+
+ default: {
+ // There are no other cases.
+ STBTT_assert(0);
+ break;
+ };
+ }
+ }
+ break;
+ };
+
+ default:
+ // TODO: Implement other stuff.
+ break;
+ }
+ }
+
+ return 0;
+}
+
+STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int g1, int g2)
+{
+ int xAdvance = 0;
+
+ if (info->gpos)
+ xAdvance += stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2);
+
+ if (info->kern)
+ xAdvance += stbtt__GetGlyphKernInfoAdvance(info, g1, g2);
+
+ return xAdvance;
+}
+
STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2)
{
- if (!info->kern) // if no kerning table, don't waste time looking up both codepoint->glyphs
+ if (!info->kern && !info->gpos) // if no kerning table, don't waste time looking up both codepoint->glyphs
return 0;
return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2));
}
@@ -2200,6 +2567,17 @@ STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, in
if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8);
}
+STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap)
+{
+ int tab = stbtt__find_table(info->data, info->fontstart, "OS/2");
+ if (!tab)
+ return 0;
+ if (typoAscent ) *typoAscent = ttSHORT(info->data+tab + 68);
+ if (typoDescent) *typoDescent = ttSHORT(info->data+tab + 70);
+ if (typoLineGap) *typoLineGap = ttSHORT(info->data+tab + 72);
+ return 1;
+}
+
STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1)
{
*x0 = ttSHORT(info->data + info->head + 36);
@@ -2296,7 +2674,7 @@ static void *stbtt__hheap_alloc(stbtt__hheap *hh, size_t size, void *userdata)
hh->num_remaining_in_head_chunk = count;
}
--hh->num_remaining_in_head_chunk;
- return (char *) (hh->head) + size * hh->num_remaining_in_head_chunk;
+ return (char *) (hh->head) + sizeof(stbtt__hheap_chunk) + size * hh->num_remaining_in_head_chunk;
}
}
@@ -2692,19 +3070,18 @@ static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill,
// from the other y segment, and it might ignored as an empty segment. to avoid
// that, we need to explicitly produce segments based on x positions.
- // rename variables to clear pairs
+ // rename variables to clearly-defined pairs
float y0 = y_top;
float x1 = (float) (x);
float x2 = (float) (x+1);
float x3 = xb;
float y3 = y_bottom;
- float y1,y2;
// x = e->x + e->dx * (y-y_top)
// (y-y_top) = (x - e->x) / e->dx
// y = (x - e->x) / e->dx + y_top
- y1 = (x - x0) / dx + y_top;
- y2 = (x+1 - x0) / dx + y_top;
+ float y1 = (x - x0) / dx + y_top;
+ float y2 = (x+1 - x0) / dx + y_top;
if (x0 < x1 && x3 > x2) { // three segments descending down-right
stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);
@@ -3131,8 +3508,9 @@ error:
STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata)
{
- float scale = scale_x > scale_y ? scale_y : scale_x;
- int winding_count, *winding_lengths;
+ float scale = scale_x > scale_y ? scale_y : scale_x;
+ int winding_count = 0;
+ int *winding_lengths = NULL;
stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata);
if (windings) {
stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata);
@@ -3220,6 +3598,11 @@ STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *
return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff);
}
+STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint)
+{
+ stbtt_MakeGlyphBitmapSubpixelPrefilter(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, oversample_x, oversample_y, sub_x, sub_y, stbtt_FindGlyphIndex(info,codepoint));
+}
+
STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint)
{
stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint));
@@ -3287,11 +3670,11 @@ static int stbtt_BakeFontBitmap_internal(unsigned char *data, int offset, // fo
return bottom_y;
}
-STBTT_DEF void stbtt_GetBakedQuad(stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule)
+STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule)
{
float d3d_bias = opengl_fillrule ? 0 : -0.5f;
float ipw = 1.0f / pw, iph = 1.0f / ph;
- stbtt_bakedchar *b = chardata + char_index;
+ const stbtt_bakedchar *b = chardata + char_index;
int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f);
int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f);
@@ -3599,6 +3982,29 @@ STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stb
return k;
}
+STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int prefilter_x, int prefilter_y, float *sub_x, float *sub_y, int glyph)
+{
+ stbtt_MakeGlyphBitmapSubpixel(info,
+ output,
+ out_w - (prefilter_x - 1),
+ out_h - (prefilter_y - 1),
+ out_stride,
+ scale_x,
+ scale_y,
+ shift_x,
+ shift_y,
+ glyph);
+
+ if (prefilter_x > 1)
+ stbtt__h_prefilter(output, out_w, out_h, out_stride, prefilter_x);
+
+ if (prefilter_y > 1)
+ stbtt__v_prefilter(output, out_w, out_h, out_stride, prefilter_y);
+
+ *sub_x = stbtt__oversample_shift(prefilter_x);
+ *sub_y = stbtt__oversample_shift(prefilter_y);
+}
+
// rects array must be big enough to accommodate all characters in the given ranges
STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects)
{
@@ -3687,7 +4093,7 @@ STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect
stbrp_pack_rects((stbrp_context *) spc->pack_info, rects, num_rects);
}
-STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges)
+STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges)
{
stbtt_fontinfo info;
int i,j,n, return_value = 1;
@@ -3723,7 +4129,7 @@ STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, unsigned char *fontd
return return_value;
}
-STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, float font_size,
+STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size,
int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range)
{
stbtt_pack_range range;
@@ -3735,10 +4141,10 @@ STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, unsigned char *fontda
return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1);
}
-STBTT_DEF void stbtt_GetPackedQuad(stbtt_packedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int align_to_integer)
+STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int align_to_integer)
{
float ipw = 1.0f / pw, iph = 1.0f / ph;
- stbtt_packedchar *b = chardata + char_index;
+ const stbtt_packedchar *b = chardata + char_index;
if (align_to_integer) {
float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5f);
@@ -3762,6 +4168,387 @@ STBTT_DEF void stbtt_GetPackedQuad(stbtt_packedchar *chardata, int pw, int ph, i
*xpos += b->xadvance;
}
+//////////////////////////////////////////////////////////////////////////////
+//
+// sdf computation
+//
+
+#define STBTT_min(a,b) ((a) < (b) ? (a) : (b))
+#define STBTT_max(a,b) ((a) < (b) ? (b) : (a))
+
+static int stbtt__ray_intersect_bezier(float orig[2], float ray[2], float q0[2], float q1[2], float q2[2], float hits[2][2])
+{
+ float q0perp = q0[1]*ray[0] - q0[0]*ray[1];
+ float q1perp = q1[1]*ray[0] - q1[0]*ray[1];
+ float q2perp = q2[1]*ray[0] - q2[0]*ray[1];
+ float roperp = orig[1]*ray[0] - orig[0]*ray[1];
+
+ float a = q0perp - 2*q1perp + q2perp;
+ float b = q1perp - q0perp;
+ float c = q0perp - roperp;
+
+ float s0 = 0., s1 = 0.;
+ int num_s = 0;
+
+ if (a != 0.0) {
+ float discr = b*b - a*c;
+ if (discr > 0.0) {
+ float rcpna = -1 / a;
+ float d = (float) STBTT_sqrt(discr);
+ s0 = (b+d) * rcpna;
+ s1 = (b-d) * rcpna;
+ if (s0 >= 0.0 && s0 <= 1.0)
+ num_s = 1;
+ if (d > 0.0 && s1 >= 0.0 && s1 <= 1.0) {
+ if (num_s == 0) s0 = s1;
+ ++num_s;
+ }
+ }
+ } else {
+ // 2*b*s + c = 0
+ // s = -c / (2*b)
+ s0 = c / (-2 * b);
+ if (s0 >= 0.0 && s0 <= 1.0)
+ num_s = 1;
+ }
+
+ if (num_s == 0)
+ return 0;
+ else {
+ float rcp_len2 = 1 / (ray[0]*ray[0] + ray[1]*ray[1]);
+ float rayn_x = ray[0] * rcp_len2, rayn_y = ray[1] * rcp_len2;
+
+ float q0d = q0[0]*rayn_x + q0[1]*rayn_y;
+ float q1d = q1[0]*rayn_x + q1[1]*rayn_y;
+ float q2d = q2[0]*rayn_x + q2[1]*rayn_y;
+ float rod = orig[0]*rayn_x + orig[1]*rayn_y;
+
+ float q10d = q1d - q0d;
+ float q20d = q2d - q0d;
+ float q0rd = q0d - rod;
+
+ hits[0][0] = q0rd + s0*(2.0f - 2.0f*s0)*q10d + s0*s0*q20d;
+ hits[0][1] = a*s0+b;
+
+ if (num_s > 1) {
+ hits[1][0] = q0rd + s1*(2.0f - 2.0f*s1)*q10d + s1*s1*q20d;
+ hits[1][1] = a*s1+b;
+ return 2;
+ } else {
+ return 1;
+ }
+ }
+}
+
+static int equal(float *a, float *b)
+{
+ return (a[0] == b[0] && a[1] == b[1]);
+}
+
+static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex *verts)
+{
+ int i;
+ float orig[2], ray[2] = { 1, 0 };
+ float y_frac;
+ int winding = 0;
+
+ orig[0] = x;
+ orig[1] = y;
+
+ // make sure y never passes through a vertex of the shape
+ y_frac = (float) STBTT_fmod(y, 1.0f);
+ if (y_frac < 0.01f)
+ y += 0.01f;
+ else if (y_frac > 0.99f)
+ y -= 0.01f;
+ orig[1] = y;
+
+ // test a ray from (-infinity,y) to (x,y)
+ for (i=0; i < nverts; ++i) {
+ if (verts[i].type == STBTT_vline) {
+ int x0 = (int) verts[i-1].x, y0 = (int) verts[i-1].y;
+ int x1 = (int) verts[i ].x, y1 = (int) verts[i ].y;
+ if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) {
+ float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0;
+ if (x_inter < x)
+ winding += (y0 < y1) ? 1 : -1;
+ }
+ }
+ if (verts[i].type == STBTT_vcurve) {
+ int x0 = (int) verts[i-1].x , y0 = (int) verts[i-1].y ;
+ int x1 = (int) verts[i ].cx, y1 = (int) verts[i ].cy;
+ int x2 = (int) verts[i ].x , y2 = (int) verts[i ].y ;
+ int ax = STBTT_min(x0,STBTT_min(x1,x2)), ay = STBTT_min(y0,STBTT_min(y1,y2));
+ int by = STBTT_max(y0,STBTT_max(y1,y2));
+ if (y > ay && y < by && x > ax) {
+ float q0[2],q1[2],q2[2];
+ float hits[2][2];
+ q0[0] = (float)x0;
+ q0[1] = (float)y0;
+ q1[0] = (float)x1;
+ q1[1] = (float)y1;
+ q2[0] = (float)x2;
+ q2[1] = (float)y2;
+ if (equal(q0,q1) || equal(q1,q2)) {
+ x0 = (int)verts[i-1].x;
+ y0 = (int)verts[i-1].y;
+ x1 = (int)verts[i ].x;
+ y1 = (int)verts[i ].y;
+ if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) {
+ float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0;
+ if (x_inter < x)
+ winding += (y0 < y1) ? 1 : -1;
+ }
+ } else {
+ int num_hits = stbtt__ray_intersect_bezier(orig, ray, q0, q1, q2, hits);
+ if (num_hits >= 1)
+ if (hits[0][0] < 0)
+ winding += (hits[0][1] < 0 ? -1 : 1);
+ if (num_hits >= 2)
+ if (hits[1][0] < 0)
+ winding += (hits[1][1] < 0 ? -1 : 1);
+ }
+ }
+ }
+ }
+ return winding;
+}
+
+static float stbtt__cuberoot( float x )
+{
+ if (x<0)
+ return -(float) STBTT_pow(-x,1.0f/3.0f);
+ else
+ return (float) STBTT_pow( x,1.0f/3.0f);
+}
+
+// x^3 + c*x^2 + b*x + a = 0
+static int stbtt__solve_cubic(float a, float b, float c, float* r)
+{
+ float s = -a / 3;
+ float p = b - a*a / 3;
+ float q = a * (2*a*a - 9*b) / 27 + c;
+ float p3 = p*p*p;
+ float d = q*q + 4*p3 / 27;
+ if (d >= 0) {
+ float z = (float) STBTT_sqrt(d);
+ float u = (-q + z) / 2;
+ float v = (-q - z) / 2;
+ u = stbtt__cuberoot(u);
+ v = stbtt__cuberoot(v);
+ r[0] = s + u + v;
+ return 1;
+ } else {
+ float u = (float) STBTT_sqrt(-p/3);
+ float v = (float) STBTT_acos(-STBTT_sqrt(-27/p3) * q / 2) / 3; // p3 must be negative, since d is negative
+ float m = (float) STBTT_cos(v);
+ float n = (float) STBTT_cos(v-3.141592/2)*1.732050808f;
+ r[0] = s + u * 2 * m;
+ r[1] = s - u * (m + n);
+ r[2] = s - u * (m - n);
+
+ //STBTT_assert( STBTT_fabs(((r[0]+a)*r[0]+b)*r[0]+c) < 0.05f); // these asserts may not be safe at all scales, though they're in bezier t parameter units so maybe?
+ //STBTT_assert( STBTT_fabs(((r[1]+a)*r[1]+b)*r[1]+c) < 0.05f);
+ //STBTT_assert( STBTT_fabs(((r[2]+a)*r[2]+b)*r[2]+c) < 0.05f);
+ return 3;
+ }
+}
+
+STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff)
+{
+ float scale_x = scale, scale_y = scale;
+ int ix0,iy0,ix1,iy1;
+ int w,h;
+ unsigned char *data;
+
+ // if one scale is 0, use same scale for both
+ if (scale_x == 0) scale_x = scale_y;
+ if (scale_y == 0) {
+ if (scale_x == 0) return NULL; // if both scales are 0, return NULL
+ scale_y = scale_x;
+ }
+
+ stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale, scale, 0.0f,0.0f, &ix0,&iy0,&ix1,&iy1);
+
+ // if empty, return NULL
+ if (ix0 == ix1 || iy0 == iy1)
+ return NULL;
+
+ ix0 -= padding;
+ iy0 -= padding;
+ ix1 += padding;
+ iy1 += padding;
+
+ w = (ix1 - ix0);
+ h = (iy1 - iy0);
+
+ if (width ) *width = w;
+ if (height) *height = h;
+ if (xoff ) *xoff = ix0;
+ if (yoff ) *yoff = iy0;
+
+ // invert for y-downwards bitmaps
+ scale_y = -scale_y;
+
+ {
+ int x,y,i,j;
+ float *precompute;
+ stbtt_vertex *verts;
+ int num_verts = stbtt_GetGlyphShape(info, glyph, &verts);
+ data = (unsigned char *) STBTT_malloc(w * h, info->userdata);
+ precompute = (float *) STBTT_malloc(num_verts * sizeof(float), info->userdata);
+
+ for (i=0,j=num_verts-1; i < num_verts; j=i++) {
+ if (verts[i].type == STBTT_vline) {
+ float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y;
+ float x1 = verts[j].x*scale_x, y1 = verts[j].y*scale_y;
+ float dist = (float) STBTT_sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0));
+ precompute[i] = (dist == 0) ? 0.0f : 1.0f / dist;
+ } else if (verts[i].type == STBTT_vcurve) {
+ float x2 = verts[j].x *scale_x, y2 = verts[j].y *scale_y;
+ float x1 = verts[i].cx*scale_x, y1 = verts[i].cy*scale_y;
+ float x0 = verts[i].x *scale_x, y0 = verts[i].y *scale_y;
+ float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2;
+ float len2 = bx*bx + by*by;
+ if (len2 != 0.0f)
+ precompute[i] = 1.0f / (bx*bx + by*by);
+ else
+ precompute[i] = 0.0f;
+ } else
+ precompute[i] = 0.0f;
+ }
+
+ for (y=iy0; y < iy1; ++y) {
+ for (x=ix0; x < ix1; ++x) {
+ float val;
+ float min_dist = 999999.0f;
+ float sx = (float) x + 0.5f;
+ float sy = (float) y + 0.5f;
+ float x_gspace = (sx / scale_x);
+ float y_gspace = (sy / scale_y);
+
+ int winding = stbtt__compute_crossings_x(x_gspace, y_gspace, num_verts, verts); // @OPTIMIZE: this could just be a rasterization, but needs to be line vs. non-tesselated curves so a new path
+
+ for (i=0; i < num_verts; ++i) {
+ float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y;
+
+ // check against every point here rather than inside line/curve primitives -- @TODO: wrong if multiple 'moves' in a row produce a garbage point, and given culling, probably more efficient to do within line/curve
+ float dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy);
+ if (dist2 < min_dist*min_dist)
+ min_dist = (float) STBTT_sqrt(dist2);
+
+ if (verts[i].type == STBTT_vline) {
+ float x1 = verts[i-1].x*scale_x, y1 = verts[i-1].y*scale_y;
+
+ // coarse culling against bbox
+ //if (sx > STBTT_min(x0,x1)-min_dist && sx < STBTT_max(x0,x1)+min_dist &&
+ // sy > STBTT_min(y0,y1)-min_dist && sy < STBTT_max(y0,y1)+min_dist)
+ float dist = (float) STBTT_fabs((x1-x0)*(y0-sy) - (y1-y0)*(x0-sx)) * precompute[i];
+ STBTT_assert(i != 0);
+ if (dist < min_dist) {
+ // check position along line
+ // x' = x0 + t*(x1-x0), y' = y0 + t*(y1-y0)
+ // minimize (x'-sx)*(x'-sx)+(y'-sy)*(y'-sy)
+ float dx = x1-x0, dy = y1-y0;
+ float px = x0-sx, py = y0-sy;
+ // minimize (px+t*dx)^2 + (py+t*dy)^2 = px*px + 2*px*dx*t + t^2*dx*dx + py*py + 2*py*dy*t + t^2*dy*dy
+ // derivative: 2*px*dx + 2*py*dy + (2*dx*dx+2*dy*dy)*t, set to 0 and solve
+ float t = -(px*dx + py*dy) / (dx*dx + dy*dy);
+ if (t >= 0.0f && t <= 1.0f)
+ min_dist = dist;
+ }
+ } else if (verts[i].type == STBTT_vcurve) {
+ float x2 = verts[i-1].x *scale_x, y2 = verts[i-1].y *scale_y;
+ float x1 = verts[i ].cx*scale_x, y1 = verts[i ].cy*scale_y;
+ float box_x0 = STBTT_min(STBTT_min(x0,x1),x2);
+ float box_y0 = STBTT_min(STBTT_min(y0,y1),y2);
+ float box_x1 = STBTT_max(STBTT_max(x0,x1),x2);
+ float box_y1 = STBTT_max(STBTT_max(y0,y1),y2);
+ // coarse culling against bbox to avoid computing cubic unnecessarily
+ if (sx > box_x0-min_dist && sx < box_x1+min_dist && sy > box_y0-min_dist && sy < box_y1+min_dist) {
+ int num=0;
+ float ax = x1-x0, ay = y1-y0;
+ float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2;
+ float mx = x0 - sx, my = y0 - sy;
+ float res[3],px,py,t,it;
+ float a_inv = precompute[i];
+ if (a_inv == 0.0) { // if a_inv is 0, it's 2nd degree so use quadratic formula
+ float a = 3*(ax*bx + ay*by);
+ float b = 2*(ax*ax + ay*ay) + (mx*bx+my*by);
+ float c = mx*ax+my*ay;
+ if (a == 0.0) { // if a is 0, it's linear
+ if (b != 0.0) {
+ res[num++] = -c/b;
+ }
+ } else {
+ float discriminant = b*b - 4*a*c;
+ if (discriminant < 0)
+ num = 0;
+ else {
+ float root = (float) STBTT_sqrt(discriminant);
+ res[0] = (-b - root)/(2*a);
+ res[1] = (-b + root)/(2*a);
+ num = 2; // don't bother distinguishing 1-solution case, as code below will still work
+ }
+ }
+ } else {
+ float b = 3*(ax*bx + ay*by) * a_inv; // could precompute this as it doesn't depend on sample point
+ float c = (2*(ax*ax + ay*ay) + (mx*bx+my*by)) * a_inv;
+ float d = (mx*ax+my*ay) * a_inv;
+ num = stbtt__solve_cubic(b, c, d, res);
+ }
+ if (num >= 1 && res[0] >= 0.0f && res[0] <= 1.0f) {
+ t = res[0], it = 1.0f - t;
+ px = it*it*x0 + 2*t*it*x1 + t*t*x2;
+ py = it*it*y0 + 2*t*it*y1 + t*t*y2;
+ dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy);
+ if (dist2 < min_dist * min_dist)
+ min_dist = (float) STBTT_sqrt(dist2);
+ }
+ if (num >= 2 && res[1] >= 0.0f && res[1] <= 1.0f) {
+ t = res[1], it = 1.0f - t;
+ px = it*it*x0 + 2*t*it*x1 + t*t*x2;
+ py = it*it*y0 + 2*t*it*y1 + t*t*y2;
+ dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy);
+ if (dist2 < min_dist * min_dist)
+ min_dist = (float) STBTT_sqrt(dist2);
+ }
+ if (num >= 3 && res[2] >= 0.0f && res[2] <= 1.0f) {
+ t = res[2], it = 1.0f - t;
+ px = it*it*x0 + 2*t*it*x1 + t*t*x2;
+ py = it*it*y0 + 2*t*it*y1 + t*t*y2;
+ dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy);
+ if (dist2 < min_dist * min_dist)
+ min_dist = (float) STBTT_sqrt(dist2);
+ }
+ }
+ }
+ }
+ if (winding == 0)
+ min_dist = -min_dist; // if outside the shape, value is negative
+ val = onedge_value + pixel_dist_scale * min_dist;
+ if (val < 0)
+ val = 0;
+ else if (val > 255)
+ val = 255;
+ data[(y-iy0)*w+(x-ix0)] = (unsigned char) val;
+ }
+ }
+ STBTT_free(precompute, info->userdata);
+ STBTT_free(verts, info->userdata);
+ }
+ return data;
+}
+
+STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff)
+{
+ return stbtt_GetGlyphSDF(info, scale, stbtt_FindGlyphIndex(info, codepoint), padding, onedge_value, pixel_dist_scale, width, height, xoff, yoff);
+}
+
+STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata)
+{
+ STBTT_free(bitmap, userdata);
+}
//////////////////////////////////////////////////////////////////////////////
//
@@ -3969,6 +4756,13 @@ STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const
// FULL VERSION HISTORY
//
+// 1.19 (2018-02-11) OpenType GPOS kerning (horizontal only), STBTT_fmod
+// 1.18 (2018-01-29) add missing function
+// 1.17 (2017-07-23) make more arguments const; doc fix
+// 1.16 (2017-07-12) SDF support
+// 1.15 (2017-03-03) make more arguments const
+// 1.14 (2017-01-16) num-fonts-in-TTC function
+// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts
// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual
// 1.11 (2016-04-02) fix unused-variable warning
// 1.10 (2016-04-02) allow user-defined fabs() replacement
@@ -4016,3 +4810,45 @@ STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const
// 0.2 (2009-03-11) Fix unsigned/signed char warnings
// 0.1 (2009-03-09) First public release
//
+
+/*
+------------------------------------------------------------------------------
+This software is available under 2 licenses -- choose whichever you prefer.
+------------------------------------------------------------------------------
+ALTERNATIVE A - MIT License
+Copyright (c) 2017 Sean Barrett
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+------------------------------------------------------------------------------
+ALTERNATIVE B - Public Domain (www.unlicense.org)
+This is free and unencumbered software released into the public domain.
+Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
+software, either in source code form or as a compiled binary, for any purpose,
+commercial or non-commercial, and by any means.
+In jurisdictions that recognize copyright laws, the author or authors of this
+software dedicate any and all copyright interest in the software to the public
+domain. We make this dedication for the benefit of the public at large and to
+the detriment of our heirs and successors. We intend this dedication to be an
+overt act of relinquishment in perpetuity of all present and future rights to
+this software under copyright law.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+------------------------------------------------------------------------------
+*/