diff --git a/dep/imgui/CMakeLists.txt b/dep/imgui/CMakeLists.txt
index 0f1bebf41..b9adb44cf 100644
--- a/dep/imgui/CMakeLists.txt
+++ b/dep/imgui/CMakeLists.txt
@@ -7,9 +7,10 @@ set(SRCS
src/imgui.cpp
src/imgui_demo.cpp
src/imgui_draw.cpp
+ src/imgui_stdlib.cpp
+ src/imgui_tables.cpp
src/imgui_widgets.cpp
src/imstb_rectpack.h
- src/imgui_stdlib.cpp
src/imstb_truetype.h
)
diff --git a/dep/imgui/imgui.vcxproj b/dep/imgui/imgui.vcxproj
index fcbf84c79..536d14a6a 100644
--- a/dep/imgui/imgui.vcxproj
+++ b/dep/imgui/imgui.vcxproj
@@ -63,6 +63,7 @@
+
diff --git a/dep/imgui/imgui.vcxproj.filters b/dep/imgui/imgui.vcxproj.filters
index 0257cb6dd..9c124bbd5 100644
--- a/dep/imgui/imgui.vcxproj.filters
+++ b/dep/imgui/imgui.vcxproj.filters
@@ -14,5 +14,6 @@
+
\ No newline at end of file
diff --git a/dep/imgui/include/imconfig.h b/dep/imgui/include/imconfig.h
index 45e75ecfc..c5e1650a0 100644
--- a/dep/imgui/include/imconfig.h
+++ b/dep/imgui/include/imconfig.h
@@ -3,10 +3,11 @@
// 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 Dear 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"
-// If you do so you need to make sure that configuration settings are defined consistently _everywhere_ Dear ImGui is used, which include
-// the imgui*.cpp files but also _any_ of your code that uses Dear ImGui. This is because some compile-time options have an affect on data structures.
+// A) You may edit imconfig.h (and not overwrite it when updating Dear ImGui, or maintain a patch/rebased branch with your modifications to it)
+// B) or '#define IMGUI_USER_CONFIG "my_imgui_config.h"' in your project and then add directives in your own file without touching this template.
+//-----------------------------------------------------------------------------
+// You need to make sure that configuration settings are defined consistently _everywhere_ Dear ImGui is used, which include the imgui*.cpp
+// files but also _any_ of your code that uses Dear ImGui. This is because some compile-time options have an affect on data structures.
// Defining those options in imconfig.h will ensure every compilation unit gets to see the same data structure layouts.
// Call IMGUI_CHECKVERSION() from your .cpp files to verify that the data structures your files are using are matching the ones imgui.cpp is using.
//-----------------------------------------------------------------------------
@@ -14,6 +15,7 @@
#pragma once
//---- Define assertion handler. Defaults to calling assert().
+// If your macro uses multiple statements, make sure is enclosed in a 'do { .. } while (0)' block so it can be used as a single statement.
//#define IM_ASSERT(_EXPR) MyAssert(_EXPR)
//#define IM_ASSERT(_EXPR) ((void)(_EXPR)) // Disable asserts
@@ -22,21 +24,23 @@
//#define IMGUI_API __declspec( dllexport )
//#define IMGUI_API __declspec( dllimport )
-//---- Don't define obsolete functions/enums names. Consider enabling from time to time after updating to avoid using soon-to-be obsolete function/names.
+//---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to avoid using soon-to-be obsolete function/names.
//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS
-//---- Don't implement demo windows functionality (ShowDemoWindow()/ShowStyleEditor()/ShowUserGuide() methods will be empty)
-// 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
-//#define IMGUI_DISABLE_METRICS_WINDOW
+//---- Disable all of Dear ImGui or don't implement standard windows.
+// It is very strongly recommended to NOT disable the demo windows during development. Please read comments in imgui_demo.cpp.
+//#define IMGUI_DISABLE // Disable everything: all headers and source files will be empty.
+//#define IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: ShowDemoWindow()/ShowStyleEditor() will be empty. Not recommended.
+//#define IMGUI_DISABLE_METRICS_WINDOW // Disable metrics/debugger window: ShowMetricsWindow() will be empty.
//---- Don't implement some functions to reduce linkage requirements.
//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc.
//#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] Don't implement default IME handler. Won't use and link with ImmGetContext/ImmSetCompositionWindow.
//#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function (clipboard, ime).
-//#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] Implement default OSX clipboard handler (need to link with '-framework ApplicationServices').
-//#define IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself if you don't want to link with vsnprintf.
-//#define IMGUI_DISABLE_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 wrapper so you can implement them yourself. Declare your prototypes in imconfig.h.
+//#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] Implement default OSX clipboard handler (need to link with '-framework ApplicationServices', this is why this is not the default).
+//#define IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself (e.g. if you don't want to link with vsnprintf)
+//#define IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself.
+//#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite so you can implement them yourself if you don't want to link with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function.
//#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions().
//---- Include imgui_user.h at the end of imgui.h as a convenience
@@ -45,13 +49,29 @@
//---- Pack colors to BGRA8 instead of RGBA8 (to avoid converting from one to another)
//#define IMGUI_USE_BGRA_PACKED_COLOR
+//---- Use 32-bit for ImWchar (default is 16-bit) to support unicode planes 1-16. (e.g. point beyond 0xFFFF like emoticons, dingbats, symbols, shapes, ancient languages, etc...)
+//#define IMGUI_USE_WCHAR32
+
//---- 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.
+// By default the embedded implementations are declared static and not available outside of Dear ImGui sources 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
+//---- Use stb_printf's faster implementation of vsnprintf instead of the one from libc (unless IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS is defined)
+// Requires 'stb_sprintf.h' to be available in the include path. Compatibility checks of arguments and formats done by clang and GCC will be disabled in order to support the extra formats provided by STB sprintf.
+// #define IMGUI_USE_STB_SPRINTF
+
+//---- Use FreeType to build and rasterize the font atlas (instead of stb_truetype which is embedded by default in Dear ImGui)
+// Requires FreeType headers to be available in the include path. Requires program to be compiled with 'misc/freetype/imgui_freetype.cpp' (in this repository) + the FreeType library (not provided).
+// On Windows you may use vcpkg with 'vcpkg install freetype' + 'vcpkg integrate install'.
+//#define IMGUI_ENABLE_FREETYPE
+
+//---- Use stb_truetype to build and rasterize the font atlas (default)
+// The only purpose of this define is if you want force compilation of the stb_truetype backend ALONG with the FreeType backend.
+//#define IMGUI_ENABLE_STB_TRUETYPE
+
//---- Define constructor and implicit cast operators to convert back<>forth between your math types and ImVec2/ImVec4.
// This will be inlined as part of ImVec2 and ImVec4 class declarations.
/*
@@ -64,26 +84,31 @@
operator MyVec4() const { return MyVec4(x,y,z,w); }
*/
-//---- Using 32-bits vertex indices (default is 16-bits) is one way to allow large meshes with more than 64K vertices.
-// Your renderer back-end will need to support it (most example renderer back-ends support both 16/32-bits indices).
-// Another way to allow large meshes while keeping 16-bits indices is to handle ImDrawCmd::VtxOffset in your renderer.
+//---- Use 32-bit vertex indices (default is 16-bit) is one way to allow large meshes with more than 64K vertices.
+// Your renderer backend will need to support it (most example renderer backends support both 16/32-bit indices).
+// Another way to allow large meshes while keeping 16-bit indices is to handle ImDrawCmd::VtxOffset in your renderer.
// Read about ImGuiBackendFlags_RendererHasVtxOffset for details.
//#define ImDrawIdx unsigned int
-//---- Override ImDrawCallback signature (will need to modify renderer back-ends accordingly)
+//---- Override ImDrawCallback signature (will need to modify renderer backends accordingly)
//struct ImDrawList;
//struct ImDrawCmd;
//typedef void (*MyImDrawCallback)(const ImDrawList* draw_list, const ImDrawCmd* cmd, void* my_renderer_user_data);
//#define ImDrawCallback MyImDrawCallback
-//---- Debug Tools
-// Use 'Metrics->Tools->Item Picker' to pick widgets with the mouse and break into them for easy debugging.
+//---- Debug Tools: Macro to break in Debugger
+// (use 'Metrics->Tools->Item Picker' to pick widgets with the mouse and break into them for easy debugging.)
//#define IM_DEBUG_BREAK IM_ASSERT(0)
//#define IM_DEBUG_BREAK __debugbreak()
-// Have the Item Picker break in the ItemAdd() function instead of ItemHoverable() - which is earlier in the code, will catch a few extra items, allow picking items other than Hovered one.
+
+//---- Debug Tools: Have the Item Picker break in the ItemAdd() function instead of ItemHoverable(),
+// (which comes earlier in the code, will catch a few extra items, allow picking items other than Hovered one.)
// This adds a small runtime cost which is why it is not enabled by default.
//#define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX
+//---- Debug Tools: Enable slower asserts
+//#define IMGUI_DEBUG_PARANOID
+
//---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files.
/*
namespace ImGui
diff --git a/dep/imgui/include/imgui.h b/dep/imgui/include/imgui.h
index 9200af598..6bfe7532f 100644
--- a/dep/imgui/include/imgui.h
+++ b/dep/imgui/include/imgui.h
@@ -1,34 +1,42 @@
-// dear imgui, v1.74 WIP
+// dear imgui, v1.81 WIP
// (headers)
-// See imgui.cpp file for documentation.
-// Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code.
-// Newcomers, read 'Programmer guide' in imgui.cpp for notes on how to setup Dear ImGui in your codebase.
-// Get latest version at https://github.com/ocornut/imgui
+// Help:
+// - Read FAQ at http://dearimgui.org/faq
+// - Newcomers, read 'Programmer guide' in imgui.cpp for notes on how to setup Dear ImGui in your codebase.
+// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
+// Read imgui.cpp for details, links and comments.
+
+// Resources:
+// - FAQ http://dearimgui.org/faq
+// - Homepage & latest https://github.com/ocornut/imgui
+// - Releases & changelog https://github.com/ocornut/imgui/releases
+// - Gallery https://github.com/ocornut/imgui/issues/3488 (please post your screenshots/video there!)
+// - Glossary https://github.com/ocornut/imgui/wiki/Glossary
+// - Wiki https://github.com/ocornut/imgui/wiki
+// - Issues & support https://github.com/ocornut/imgui/issues
/*
Index of this file:
-// Header mess
-// Forward declarations and basic types
-// ImGui API (Dear ImGui end-user API)
-// Flags & Enumerations
-// Memory allocations macros
-// ImVector<>
-// ImGuiStyle
-// ImGuiIO
-// Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiWindowClass, ImGuiPayload)
-// Obsolete functions
-// Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, ImColor)
-// Draw List API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawListFlags, ImDrawList, ImDrawData)
-// Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFont)
-// Platform interface for multi-viewport support (ImGuiPlatformMonitor, ImGuiPlatformIO, ImGuiViewport)
+// [SECTION] Header mess
+// [SECTION] Forward declarations and basic types
+// [SECTION] Dear ImGui end-user API functions
+// [SECTION] Flags & Enumerations
+// [SECTION] Helpers: Memory allocations macros, ImVector<>
+// [SECTION] ImGuiStyle
+// [SECTION] ImGuiIO
+// [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload, ImGuiTableSortSpecs, ImGuiTableColumnSortSpecs)
+// [SECTION] Obsolete functions
+// [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, ImColor)
+// [SECTION] Drawing API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawListFlags, ImDrawList, ImDrawData)
+// [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFont)
*/
#pragma once
-// Configuration file with compile-time options (edit imconfig.h or #define IMGUI_USER_CONFIG to your own filename)
+// Configuration file with compile-time options (edit imconfig.h or '#define IMGUI_USER_CONFIG "myfilename.h" from your build system')
#ifdef IMGUI_USER_CONFIG
#include IMGUI_USER_CONFIG
#endif
@@ -36,8 +44,10 @@ Index of this file:
#include "imconfig.h"
#endif
+#ifndef IMGUI_DISABLE
+
//-----------------------------------------------------------------------------
-// Header mess
+// [SECTION] Header mess
//-----------------------------------------------------------------------------
// Includes
@@ -48,15 +58,14 @@ Index of this file:
// Version
// (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens)
-#define IMGUI_VERSION "1.74 WIP"
-#define IMGUI_VERSION_NUM 17301
+#define IMGUI_VERSION "1.81 WIP"
+#define IMGUI_VERSION_NUM 18002
#define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx))
-#define IMGUI_HAS_VIEWPORT 1 // Viewport WIP branch
-#define IMGUI_HAS_DOCK 1 // Docking WIP branch
+#define IMGUI_HAS_TABLE
// Define attributes of all API symbols declarations (e.g. for DLL under Windows)
-// IMGUI_API is used for core imgui functions, IMGUI_IMPL_API is used for the default bindings files (imgui_impl_xxx.h)
-// Using dear imgui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
+// IMGUI_API is used for core imgui functions, IMGUI_IMPL_API is used for the default backends files (imgui_impl_xxx.h)
+// Using dear imgui via a shared library is not recommended, because we don't guarantee backward nor forward ABI compatibility (also function call overhead, as dear imgui is a call-heavy API)
#ifndef IMGUI_API
#define IMGUI_API
#endif
@@ -69,21 +78,26 @@ Index of this file:
#include
#define IM_ASSERT(_EXPR) assert(_EXPR) // You can override the default assert handler by editing imconfig.h
#endif
-#if defined(__clang__) || defined(__GNUC__)
-#define IM_FMTARGS(FMT) __attribute__((format(printf, FMT, FMT+1))) // To apply printf-style warnings to our 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))) // Size of a static C-style array. Don't use on pointers!
-#define IM_UNUSED(_VAR) ((void)_VAR) // Used to silence "unused variable warnings". Often useful as asserts may be stripped out from final builds.
-#if (__cplusplus >= 201100)
+#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR) / sizeof(*(_ARR)))) // Size of a static C-style array. Don't use on pointers!
+#define IM_UNUSED(_VAR) ((void)(_VAR)) // Used to silence "unused variable warnings". Often useful as asserts may be stripped out from final builds.
+#if (__cplusplus >= 201100) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201100)
#define IM_OFFSETOF(_TYPE,_MEMBER) offsetof(_TYPE, _MEMBER) // Offset of _MEMBER within _TYPE. Standardized as offsetof() in C++11
#else
#define IM_OFFSETOF(_TYPE,_MEMBER) ((size_t)&(((_TYPE*)0)->_MEMBER)) // Offset of _MEMBER within _TYPE. Old style macro.
#endif
+// Helper Macros - IM_FMTARGS, IM_FMTLIST: Apply printf-style warnings to our formatting functions.
+#if !defined(IMGUI_USE_STB_SPRINTF) && defined(__clang__)
+#define IM_FMTARGS(FMT) __attribute__((format(printf, FMT, FMT+1)))
+#define IM_FMTLIST(FMT) __attribute__((format(printf, FMT, 0)))
+#elif !defined(IMGUI_USE_STB_SPRINTF) && defined(__GNUC__) && defined(__MINGW32__)
+#define IM_FMTARGS(FMT) __attribute__((format(gnu_printf, FMT, FMT+1)))
+#define IM_FMTLIST(FMT) __attribute__((format(gnu_printf, FMT, 0)))
+#else
+#define IM_FMTARGS(FMT)
+#define IM_FMTLIST(FMT)
+#endif
+
// Warnings
#if defined(__clang__)
#pragma clang diagnostic push
@@ -93,14 +107,15 @@ Index of this file:
#endif
#elif defined(__GNUC__)
#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
-#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
+#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
+#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
#endif
//-----------------------------------------------------------------------------
-// Forward declarations and basic types
+// [SECTION] Forward declarations and basic types
//-----------------------------------------------------------------------------
+// Forward declarations
struct ImDrawChannel; // Temporary storage to output draw commands out of order, used by ImDrawListSplitter and ImDrawList::ChannelsSplit()
struct ImDrawCmd; // A single draw command within a parent ImDrawList (generally maps to 1 GPU draw call, unless it is a callback)
struct ImDrawData; // All draw command lists required to render the frame + pos/size coordinates to use for the projection matrix.
@@ -110,6 +125,7 @@ struct ImDrawListSplitter; // Helper to split a draw list into differen
struct ImDrawVert; // A single vertex (pos + uv + col = 20 bytes by default. Override layout with IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT)
struct ImFont; // Runtime data for a single font within a parent ImFontAtlas
struct ImFontAtlas; // Runtime data for multiple fonts, bake multiple fonts into a single texture, TTF/OTF font loader
+struct ImFontBuilderIO; // Opaque interface to a font builder (stb_truetype or FreeType).
struct ImFontConfig; // Configuration data when adding a font or merging fonts
struct ImFontGlyph; // A single font glyph (code point + coordinates within in ImFontAtlas + offset)
struct ImFontGlyphRangesBuilder; // Helper to build glyph ranges from text/string data
@@ -120,53 +136,72 @@ struct ImGuiInputTextCallbackData; // Shared state of InputText() when using cu
struct ImGuiListClipper; // Helper to manually clip large list of items
struct ImGuiOnceUponAFrame; // Helper for running a block of code not more than once a frame, used by IMGUI_ONCE_UPON_A_FRAME macro
struct ImGuiPayload; // User data payload for drag and drop operations
-struct ImGuiPlatformIO; // Multi-viewport support: interface for Platform/Renderer back-ends + viewports to render
-struct ImGuiPlatformMonitor; // Multi-viewport support: user-provided bounds for each connected monitor/display. Used when positioning popups and tooltips to avoid them straddling monitors
struct ImGuiSizeCallbackData; // Callback data when using SetNextWindowSizeConstraints() (rare/advanced use)
struct ImGuiStorage; // Helper for key->value storage
struct ImGuiStyle; // Runtime data for styling/colors
+struct ImGuiTableSortSpecs; // Sorting specifications for a table (often handling sort specs for a single column, occasionally more)
+struct ImGuiTableColumnSortSpecs; // Sorting specification for one column of a table
struct ImGuiTextBuffer; // Helper to hold and append into a text buffer (~string builder)
-struct ImGuiTextFilter; // Helper to parse and apply text filters (e.g. "aaaaa[,bbbb][,ccccc]")
-struct ImGuiViewport; // Viewport (generally ~1 per window to output to at the OS level. Need per-platform support to use multiple viewports)
-struct ImGuiWindowClass; // Window class (rare/advanced uses: provide hints to the platform back-end via altered viewport flags and parent/child info)
+struct ImGuiTextFilter; // Helper to parse and apply text filters (e.g. "aaaaa[,bbbbb][,ccccc]")
-// Typedefs and Enums/Flags (declared as int for compatibility with old C++, to allow using as flags and to not pollute the top of this file)
-// Use your programming IDE "Go to definition" facility on the names in the central column below to find the actual flags/enum lists.
-#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
-typedef unsigned int ImGuiID; // Unique ID used by widgets (typically hashed from a stack of string)
-typedef unsigned short ImWchar; // A single U16 character for keyboard input/display. We encode them as multi bytes UTF-8 when used in strings.
+// Enums/Flags (declared as int for compatibility with old C++, to allow using as flags and to not pollute the top of this file)
+// - Tip: Use your programming IDE navigation facilities on the names in the _central column_ below to find the actual flags/enum lists!
+// In Visual Studio IDE: CTRL+comma ("Edit.NavigateTo") can follow symbols in comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot.
+// With Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols in comments.
typedef int ImGuiCol; // -> enum ImGuiCol_ // Enum: A color identifier for styling
typedef int ImGuiCond; // -> enum ImGuiCond_ // Enum: A condition for many Set*() functions
typedef int ImGuiDataType; // -> enum ImGuiDataType_ // Enum: A primary data type
typedef int ImGuiDir; // -> enum ImGuiDir_ // Enum: A cardinal direction
typedef int ImGuiKey; // -> enum ImGuiKey_ // Enum: A key identifier (ImGui-side enum)
typedef int ImGuiNavInput; // -> enum ImGuiNavInput_ // Enum: An input identifier for navigation
+typedef int ImGuiMouseButton; // -> enum ImGuiMouseButton_ // Enum: A mouse button identifier (0=left, 1=right, 2=middle)
typedef int ImGuiMouseCursor; // -> enum ImGuiMouseCursor_ // Enum: A mouse cursor identifier
+typedef int ImGuiSortDirection; // -> enum ImGuiSortDirection_ // Enum: A sorting direction (ascending or descending)
typedef int ImGuiStyleVar; // -> enum ImGuiStyleVar_ // Enum: A variable identifier for styling
+typedef int ImGuiTableBgTarget; // -> enum ImGuiTableBgTarget_ // Enum: A color target for TableSetBgColor()
typedef int ImDrawCornerFlags; // -> enum ImDrawCornerFlags_ // Flags: for ImDrawList::AddRect(), AddRectFilled() etc.
typedef int ImDrawListFlags; // -> enum ImDrawListFlags_ // Flags: for ImDrawList
-typedef int ImFontAtlasFlags; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas
+typedef int ImFontAtlasFlags; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas build
typedef int ImGuiBackendFlags; // -> enum ImGuiBackendFlags_ // Flags: for io.BackendFlags
+typedef int ImGuiButtonFlags; // -> enum ImGuiButtonFlags_ // Flags: for InvisibleButton()
typedef int ImGuiColorEditFlags; // -> enum ImGuiColorEditFlags_ // Flags: for ColorEdit4(), ColorPicker4() etc.
typedef int ImGuiConfigFlags; // -> enum ImGuiConfigFlags_ // Flags: for io.ConfigFlags
typedef int ImGuiComboFlags; // -> enum ImGuiComboFlags_ // Flags: for BeginCombo()
-typedef int ImGuiDockNodeFlags; // -> enum ImGuiDockNodeFlags_ // Flags: for DockSpace()
typedef int ImGuiDragDropFlags; // -> enum ImGuiDragDropFlags_ // Flags: for BeginDragDropSource(), AcceptDragDropPayload()
typedef int ImGuiFocusedFlags; // -> enum ImGuiFocusedFlags_ // Flags: for IsWindowFocused()
typedef int ImGuiHoveredFlags; // -> enum ImGuiHoveredFlags_ // Flags: for IsItemHovered(), IsWindowHovered() etc.
typedef int ImGuiInputTextFlags; // -> enum ImGuiInputTextFlags_ // Flags: for InputText(), InputTextMultiline()
+typedef int ImGuiKeyModFlags; // -> enum ImGuiKeyModFlags_ // Flags: for io.KeyMods (Ctrl/Shift/Alt/Super)
+typedef int ImGuiPopupFlags; // -> enum ImGuiPopupFlags_ // Flags: for OpenPopup*(), BeginPopupContext*(), IsPopupOpen()
typedef int ImGuiSelectableFlags; // -> enum ImGuiSelectableFlags_ // Flags: for Selectable()
+typedef int ImGuiSliderFlags; // -> enum ImGuiSliderFlags_ // Flags: for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc.
typedef int ImGuiTabBarFlags; // -> enum ImGuiTabBarFlags_ // Flags: for BeginTabBar()
typedef int ImGuiTabItemFlags; // -> enum ImGuiTabItemFlags_ // Flags: for BeginTabItem()
+typedef int ImGuiTableFlags; // -> enum ImGuiTableFlags_ // Flags: For BeginTable()
+typedef int ImGuiTableColumnFlags; // -> enum ImGuiTableColumnFlags_// Flags: For TableSetupColumn()
+typedef int ImGuiTableRowFlags; // -> enum ImGuiTableRowFlags_ // Flags: For TableNextRow()
typedef int ImGuiTreeNodeFlags; // -> enum ImGuiTreeNodeFlags_ // Flags: for TreeNode(), TreeNodeEx(), CollapsingHeader()
-typedef int ImGuiViewportFlags; // -> enum ImGuiViewportFlags_ // Flags: for ImGuiViewport
typedef int ImGuiWindowFlags; // -> enum ImGuiWindowFlags_ // Flags: for Begin(), BeginChild()
-typedef int (*ImGuiInputTextCallback)(ImGuiInputTextCallbackData *data);
-typedef void (*ImGuiSizeCallback)(ImGuiSizeCallbackData* data);
-// Scalar data types
+// Other types
+#ifndef ImTextureID // ImTextureID [configurable type: override in imconfig.h with '#define ImTextureID xxx']
+typedef void* ImTextureID; // User data for rendering backend to identify a texture. This is whatever to you want it to be! read the FAQ about ImTextureID for details.
+#endif
+typedef unsigned int ImGuiID; // A unique ID used by widgets, typically hashed from a stack of string.
+typedef int (*ImGuiInputTextCallback)(ImGuiInputTextCallbackData* data); // Callback function for ImGui::InputText()
+typedef void (*ImGuiSizeCallback)(ImGuiSizeCallbackData* data); // Callback function for ImGui::SetNextWindowSizeConstraints()
+
+// Character types
+// (we generally use UTF-8 encoded string in the API. This is storage specifically for a decoded character used for keyboard input and display)
+typedef unsigned short ImWchar16; // A single decoded U16 character/code point. We encode them as multi bytes UTF-8 when used in strings.
+typedef unsigned int ImWchar32; // A single decoded U32 character/code point. We encode them as multi bytes UTF-8 when used in strings.
+#ifdef IMGUI_USE_WCHAR32 // ImWchar [configurable type: override in imconfig.h with '#define IMGUI_USE_WCHAR32' to support Unicode planes 1-16]
+typedef ImWchar32 ImWchar;
+#else
+typedef ImWchar16 ImWchar;
+#endif
+
+// Basic scalar data types
typedef signed char ImS8; // 8-bit signed integer
typedef unsigned char ImU8; // 8-bit unsigned integer
typedef signed short ImS16; // 16-bit signed integer
@@ -185,14 +220,14 @@ typedef signed long long ImS64; // 64-bit signed integer (post C++11)
typedef unsigned long long ImU64; // 64-bit unsigned integer (post C++11)
#endif
-// 2D vector (often used to store positions, sizes, etc.)
+// 2D vector (often used to store positions or sizes)
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.
- float& operator[] (size_t idx) { IM_ASSERT(idx <= 1); return (&x)[idx]; } // We very rarely use this [] operator, the assert overhead is fine.
+ 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.
+ float& operator[] (size_t idx) { IM_ASSERT(idx <= 1); return (&x)[idx]; } // We very rarely use this [] operator, the assert overhead is fine.
#ifdef IM_VEC2_CLASS_EXTRA
IM_VEC2_CLASS_EXTRA // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math types and ImVec2.
#endif
@@ -201,17 +236,17 @@ struct ImVec2
// 4D vector (often used to store floating-point colors)
struct ImVec4
{
- float x, y, z, w;
- ImVec4() { x = y = z = w = 0.0f; }
- ImVec4(float _x, float _y, float _z, float _w) { x = _x; y = _y; z = _z; w = _w; }
+ float x, y, z, w;
+ ImVec4() { x = y = z = w = 0.0f; }
+ ImVec4(float _x, float _y, float _z, float _w) { x = _x; y = _y; z = _z; w = _w; }
#ifdef IM_VEC4_CLASS_EXTRA
IM_VEC4_CLASS_EXTRA // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math types and ImVec4.
#endif
};
//-----------------------------------------------------------------------------
-// ImGui: Dear ImGui end-user API
-// (Inside a namespace so you can add extra functions in your own separate file. Please don't modify imgui source files!)
+// [SECTION] Dear ImGui end-user API functions
+// (Note that ImGui:: being a namespace, you can add extra ImGui:: functions in your own separate file. Please don't modify imgui source files!)
//-----------------------------------------------------------------------------
namespace ImGui
@@ -223,36 +258,36 @@ namespace ImGui
IMGUI_API void DestroyContext(ImGuiContext* ctx = NULL); // NULL = destroy current context
IMGUI_API ImGuiContext* GetCurrentContext();
IMGUI_API void SetCurrentContext(ImGuiContext* ctx);
- IMGUI_API bool DebugCheckVersionAndDataLayout(const char* version_str, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_drawvert, size_t sz_drawidx);
// Main
IMGUI_API ImGuiIO& GetIO(); // access the IO structure (mouse/keyboard/gamepad inputs, time, various configuration options/flags)
- IMGUI_API ImGuiStyle& GetStyle(); // access the Style structure (colors, sizes). Always use PushStyleCol(), PushStyleVar() to modify style mid-frame.
+ IMGUI_API ImGuiStyle& GetStyle(); // access the Style structure (colors, sizes). Always use PushStyleCol(), PushStyleVar() to modify style mid-frame!
IMGUI_API void NewFrame(); // start a new Dear ImGui frame, you can submit any command from this point until Render()/EndFrame().
- IMGUI_API void EndFrame(); // ends the Dear ImGui frame. automatically called by Render(), you likely don't need to call that yourself directly. If you don't need to render data (skipping rendering) 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 and not call NewFrame() at all!
- IMGUI_API void Render(); // ends the Dear ImGui frame, finalize the draw data. You can get call GetDrawData() to obtain it and run your rendering function. (Obsolete: this used to call io.RenderDrawListsFn(). Nowadays, we allow and prefer calling your render function yourself.)
+ IMGUI_API void EndFrame(); // ends the Dear ImGui frame. automatically called by Render(). If you don't need to render data (skipping rendering) you may call EndFrame() without Render()... but you'll have wasted CPU already! If you don't need to render, better to not create any windows and not call NewFrame() at all!
+ IMGUI_API void Render(); // ends the Dear ImGui frame, finalize the draw data. You can then get call GetDrawData().
IMGUI_API ImDrawData* GetDrawData(); // valid after Render() and until the next call to NewFrame(). this is what you have to render.
// Demo, Debug, Information
- IMGUI_API void ShowDemoWindow(bool* p_open = NULL); // create Demo 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 ShowDemoWindow(bool* p_open = NULL); // create Demo window. 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/Debugger window. display Dear ImGui internals: windows, draw commands, various internal state, etc.
IMGUI_API void ShowAboutWindow(bool* p_open = NULL); // create About window. display Dear ImGui version, credits and build/system information.
- IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // create Metrics/Debug window. display Dear 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); // 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 the compiled version string e.g. "1.23" (essentially the compiled value for IMGUI_VERSION)
+ IMGUI_API const char* GetVersion(); // get the compiled version string e.g. "1.80 WIP" (essentially the value for IMGUI_VERSION from the compiled version of imgui.cpp)
// 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
+ IMGUI_API void StyleColorsClassic(ImGuiStyle* dst = NULL); // classic imgui style
// 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.
// - Passing 'bool* p_open != NULL' shows a window-closing widget in the upper-right corner of the window,
// which clicking will set the boolean to false when clicked.
+ // - You may append multiple times to the same window during the same frame by calling Begin()/End() pairs multiple times.
+ // Some information such as 'flags' or 'p_open' will only be considered by the first call to Begin().
// - Begin() return false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting
// anything to the window. Always call a matching End() for each Begin() call, regardless of its return value!
// [Important: due to legacy reason, this is inconsistent with most other functions such as BeginMenu/EndMenu,
@@ -266,9 +301,12 @@ namespace ImGui
// - Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window. Child windows can embed their own child.
// - For each independent axis of 'size': ==0.0f: use remaining host window size / >0.0f: fixed size / <0.0f: use remaining window size minus abs(size) / Each axis can use a different mode, e.g. ImVec2(0,400).
// - BeginChild() returns false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting anything to the window.
- // Always call a matching EndChild() for each BeginChild() call, regardless of its return value [as with Begin: this is due to legacy reason and inconsistent with most BeginXXX functions apart from the regular Begin() which behaves like BeginChild().]
- IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags flags = 0);
- IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags flags = 0);
+ // Always call a matching EndChild() for each BeginChild() call, regardless of its return value.
+ // [Important: due to legacy reason, this is inconsistent with most other functions such as BeginMenu/EndMenu,
+ // BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding BeginXXX function
+ // returned true. Begin and BeginChild are the only odd ones out. Will be fixed in a future update.]
+ IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0, 0), bool border = false, ImGuiWindowFlags flags = 0);
+ IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0, 0), bool border = false, ImGuiWindowFlags flags = 0);
IMGUI_API void EndChild();
// Windows Utilities
@@ -278,24 +316,21 @@ namespace ImGui
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 current window, to append your own drawing primitives
- IMGUI_API float GetWindowDpiScale(); // get DPI scale currently associated to the current window's viewport.
- IMGUI_API ImGuiViewport*GetWindowViewport(); // get viewport currently associated to the current window.
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)
// Prefer using SetNextXXX functions (before Begin) rather that SetXXX functions (after Begin).
- 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 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, 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. Sizes will be rounded down. Use callback to apply non-trivial programmatic constraints.
IMGUI_API void SetNextWindowContentSize(const ImVec2& size); // set next window content size (~ scrollable client area, which enforce the range of scrollbars). Not including window decorations (title bar, menu bar, etc.) nor WindowPadding. 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 / top-most. call before Begin()
- IMGUI_API void SetNextWindowBgAlpha(float alpha); // set next window background color alpha. helper to easily modify ImGuiCol_WindowBg/ChildBg/PopupBg. you may also use ImGuiWindowFlags_NoBackground.
- IMGUI_API void SetNextWindowViewport(ImGuiID viewport_id); // set next window viewport
+ IMGUI_API void SetNextWindowBgAlpha(float alpha); // set next window background color alpha. helper to easily override the Alpha component of ImGuiCol_WindowBg/ChildBg/PopupBg. you may also use ImGuiWindowFlags_NoBackground.
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 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 / top-most. prefer using SetNextWindowFocus().
IMGUI_API void SetWindowFontScale(float scale); // set font scale. Adjust IO.FontGlobalScale if you want to scale all windows. This is an old API! For correct scaling, prefer to reload font + rebuild ImFontAtlas + call style.ScaleAllSizes().
@@ -305,20 +340,21 @@ namespace ImGui
IMGUI_API void SetWindowFocus(const char* name); // set named window to be focused / top-most. use NULL to remove focus.
// Content region
- // - Those functions are bound to be redesigned soon (they are confusing, incomplete and return values in local window coordinates which increases confusion)
- IMGUI_API ImVec2 GetContentRegionMax(); // current content boundaries (typically window boundaries including scrolling, or current column boundaries), in windows coordinates
+ // - Retrieve available space from a given point. GetContentRegionAvail() is frequently useful.
+ // - Those functions are bound to be redesigned (they are confusing, incomplete and the Min/Max return values are in local window coordinates which increases confusion)
IMGUI_API ImVec2 GetContentRegionAvail(); // == GetContentRegionMax() - GetCursorPos()
+ IMGUI_API ImVec2 GetContentRegionMax(); // current content boundaries (typically window boundaries including scrolling, or current column boundaries), in windows coordinates
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(); //
// 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 float GetScrollX(); // get scrolling amount [0 .. GetScrollMaxX()]
+ IMGUI_API float GetScrollY(); // get scrolling amount [0 .. GetScrollMaxY()]
+ 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 float GetScrollMaxX(); // get maximum scrolling amount ~~ ContentSize.x - WindowSize.x - DecorationsSize.x
+ IMGUI_API float GetScrollMaxY(); // get maximum scrolling amount ~~ ContentSize.y - WindowSize.y - DecorationsSize.y
IMGUI_API void SetScrollHereX(float center_x_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_x_ratio=0.0: left, 0.5: center, 1.0: right. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead.
IMGUI_API void SetScrollHereY(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 SetScrollFromPosX(float local_x, float center_x_ratio = 0.5f); // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position.
@@ -327,43 +363,48 @@ namespace ImGui
// Parameters stacks (shared)
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, ImU32 col); // modify a style color. always use this if you modify the style after NewFrame().
IMGUI_API void PushStyleColor(ImGuiCol idx, const ImVec4& col);
IMGUI_API void PopStyleColor(int count = 1);
- IMGUI_API void PushStyleVar(ImGuiStyleVar idx, float val);
- IMGUI_API void PushStyleVar(ImGuiStyleVar idx, const ImVec2& val);
+ IMGUI_API void PushStyleVar(ImGuiStyleVar idx, float val); // modify a style float variable. always use this if you modify the style after NewFrame().
+ IMGUI_API void PushStyleVar(ImGuiStyleVar idx, const ImVec2& val); // modify a style ImVec2 variable. always use this if you modify the style after NewFrame().
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(), otherwise 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); // set width of items for common large "item+label" widgets. >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). 0.0f = default to ~2/3 of windows width,
- IMGUI_API void PopItemWidth();
- IMGUI_API void SetNextItemWidth(float item_width); // set width of the _next_ common large "item+label" widget. >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 float CalcItemWidth(); // width of item given pushed settings and current cursor position. NOT necessarily the width of last item unlike most 'Item' functions.
- IMGUI_API void PushTextWrapPos(float wrap_local_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 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 PopButtonRepeat();
+ // Parameters stacks (current window)
+ IMGUI_API void PushItemWidth(float item_width); // push width of items for common large "item+label" widgets. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -FLT_MIN always align width to the right side).
+ IMGUI_API void PopItemWidth();
+ IMGUI_API void SetNextItemWidth(float item_width); // set width of the _next_ common large "item+label" widget. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -FLT_MIN always align width to the right side)
+ IMGUI_API float CalcItemWidth(); // width of item given pushed settings and current cursor position. NOT necessarily the width of last item unlike most 'Item' functions.
+ IMGUI_API void PushTextWrapPos(float wrap_local_pos_x = 0.0f); // push word-wrapping position 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();
+
+ // Style read access
+ 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, packed as a 32-bit value suitable for ImDrawList
+ IMGUI_API ImU32 GetColorU32(const ImVec4& col); // retrieve given color with style alpha applied, packed as a 32-bit value suitable for ImDrawList
+ IMGUI_API ImU32 GetColorU32(ImU32 col); // retrieve given color with style alpha applied, packed as a 32-bit value suitable for ImDrawList
+ IMGUI_API const ImVec4& GetStyleColorVec4(ImGuiCol idx); // retrieve style color as stored in ImGuiStyle structure. use to feed back into PushStyleColor(), otherwise use GetColorU32() to get style color with style alpha baked in.
+
// Cursor / Layout
// - By "cursor" we mean the current output position.
// - The typical widget behavior is to output themselves at the current cursor position, then move the cursor one line down.
- // - You can call SameLine() between widgets to undo the last carriage return and output at the right of the preceeding widget.
+ // - You can call SameLine() between widgets to undo the last carriage return and output at the right of the preceding widget.
+ // - Attention! We currently have inconsistencies between window-local and absolute positions we will aim to fix with future API:
+ // Window-local coordinates: SameLine(), GetCursorPos(), SetCursorPos(), GetCursorStartPos(), GetContentRegionMax(), GetWindowContentRegion*(), PushTextWrapPos()
+ // Absolute coordinate: GetCursorScreenPos(), SetCursorScreenPos(), all ImDrawList:: functions.
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 offset_from_start_x=0.0f, float spacing=-1.0f); // call between widgets or groups to layout them horizontally. X position given in window coordinates.
IMGUI_API void NewLine(); // undo a SameLine() or force a new line when in an horizontal-layout context.
IMGUI_API void Spacing(); // add vertical spacing.
IMGUI_API void Dummy(const ImVec2& size); // add a dummy item of given size. unlike InvisibleButton(), Dummy() won't take the mouse click or be navigable into.
- 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 Indent(float indent_w = 0.0f); // move content position toward the right, by indent_w, or style.IndentSpacing if indent_w <= 0
+ IMGUI_API void Unindent(float indent_w = 0.0f); // move content position back to the left, by indent_w, or style.IndentSpacing if indent_w <= 0
IMGUI_API void BeginGroup(); // lock horizontal starting position
IMGUI_API void EndGroup(); // unlock horizontal starting position + capture the whole group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
IMGUI_API ImVec2 GetCursorPos(); // cursor position in window coordinates (relative to window position)
@@ -373,8 +414,8 @@ namespace ImGui
IMGUI_API void SetCursorPosX(float local_x); // GetWindowPos() + GetCursorPos() == GetCursorScreenPos() etc.)
IMGUI_API void SetCursorPosY(float local_y); //
IMGUI_API ImVec2 GetCursorStartPos(); // initial cursor position in window coordinates
- IMGUI_API ImVec2 GetCursorScreenPos(); // cursor position in absolute screen coordinates (0..io.DisplaySize) or natural OS coordinates when using multiple viewport. Useful to work with ImDrawList API.
- IMGUI_API void SetCursorScreenPos(const ImVec2& pos); // cursor position in absolute screen coordinates (0..io.DisplaySize) or natural OS coordinates when using multiple viewport.
+ 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 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)
@@ -415,18 +456,19 @@ namespace ImGui
// Widgets: Main
// - Most widgets return true when the value has been changed or when pressed/selected
// - You may also use one of the many IsItemXXX functions (e.g. IsItemActive, IsItemHovered, etc.) to query widget state.
- IMGUI_API bool Button(const char* label, const ImVec2& size = ImVec2(0,0)); // button
+ 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, frequently useful to build custom behaviors using the public api (along with IsItemActive, IsItemHovered, etc.)
+ IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size, ImGuiButtonFlags flags = 0); // flexible button behavior without the visuals, frequently useful to build custom behaviors using the public api (along with IsItemActive, IsItemHovered, etc.)
IMGUI_API bool ArrowButton(const char* str_id, ImGuiDir dir); // square button with an arrow shape
- 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 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);
+ IMGUI_API bool CheckboxFlags(const char* label, int* flags, int flags_value);
IMGUI_API bool CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value);
IMGUI_API bool RadioButton(const char* label, bool active); // use with e.g. if (RadioButton("one", my_value==1)) { my_value = 1; }
IMGUI_API bool RadioButton(const char* label, int* v, int v_button); // shortcut to handle the above pattern when value is an integer
- 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
+ IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-FLT_MIN, 0), const char* overlay = NULL);
+ IMGUI_API void Bullet(); // draw a small circle + keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses
// Widgets: Combo Box
// - The BeginCombo()/EndCombo() api allows you to manage your contents and selection state however you want it, by creating e.g. Selectable() items.
@@ -437,49 +479,56 @@ namespace ImGui
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
+ // Widgets: Drag Sliders
// - CTRL+Click on any drag box to turn them into an input box. Manually input values aren't clamped and 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
// - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc.
+ // - Format string may also be set to NULL or use the default format ("%f" or "%d").
// - 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).
// - Use v_min < v_max to clamp edits to given limits. Note that CTRL+Click manual input can override those limits.
- // - Use v_min > v_max to lock edits.
- 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* 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* 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* format = "%.3f", float power = 1.0f);
- IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", float power = 1.0f);
- IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", const char* format_max = NULL, float power = 1.0f);
- IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d"); // If v_min >= v_max we have no bound
- IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d");
- IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d");
- IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d");
- IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", const char* format_max = NULL);
- IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f);
- IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f);
+ // - Use v_max = FLT_MAX / INT_MAX etc to avoid clamping to a maximum, same with v_min = -FLT_MAX / INT_MIN to avoid clamping to a minimum.
+ // - We use the same sets of flags for DragXXX() and SliderXXX() functions as the features are the same and it makes it easier to swap them.
+ // - Legacy: Pre-1.78 there are DragXXX() function signatures that takes a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument.
+ // If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361
+ 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* format = "%.3f", ImGuiSliderFlags flags = 0); // 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* format = "%.3f", ImGuiSliderFlags flags = 0);
+ 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* format = "%.3f", ImGuiSliderFlags flags = 0);
+ IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0);
+ IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", const char* format_max = NULL, ImGuiSliderFlags flags = 0);
+ IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); // If v_min >= v_max we have no bound
+ IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0);
+ IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0);
+ IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0);
+ IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", const char* format_max = NULL, ImGuiSliderFlags flags = 0);
+ IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiSliderFlags flags = 0);
+ IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiSliderFlags flags = 0);
- // Widgets: Sliders
+ // Widgets: Regular Sliders
// - CTRL+Click on any slider to turn them into an input box. Manually input values aren't clamped and can go off-bounds.
// - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc.
- IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format = "%.3f", float power = 1.0f); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. Use power!=1.0 for power curve sliders
- IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format = "%.3f", float power = 1.0f);
- IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format = "%.3f", float power = 1.0f);
- IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format = "%.3f", float power = 1.0f);
- IMGUI_API bool SliderAngle(const char* label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f, const char* format = "%.0f deg");
- IMGUI_API bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* format = "%d");
- IMGUI_API bool SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format = "%d");
- IMGUI_API bool SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format = "%d");
- IMGUI_API bool SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format = "%d");
- IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, float power = 1.0f);
- IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format = NULL, float power = 1.0f);
- IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format = "%.3f", float power = 1.0f);
- IMGUI_API bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format = "%d");
- IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, float power = 1.0f);
+ // - Format string may also be set to NULL or use the default format ("%f" or "%d").
+ // - Legacy: Pre-1.78 there are SliderXXX() function signatures that takes a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument.
+ // If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361
+ IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display.
+ IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0);
+ IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0);
+ IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0);
+ IMGUI_API bool SliderAngle(const char* label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f, const char* format = "%.0f deg", ImGuiSliderFlags flags = 0);
+ IMGUI_API bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0);
+ IMGUI_API bool SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0);
+ IMGUI_API bool SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0);
+ IMGUI_API bool SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0);
+ IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0);
+ IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0);
+ IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0);
+ IMGUI_API bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0);
+ IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0);
// Widgets: Input with Keyboard
- // - If you want to use InputText() with a dynamic string type such as std::string or your own, see misc/cpp/imgui_stdlib.h
+ // - If you want to use InputText() with std::string or any custom dynamic string type, see misc/cpp/imgui_stdlib.h and comments in imgui_demo.cpp.
// - Most of the ImGuiInputTextFlags flags are only useful for InputText() and not for InputFloatX, InputIntX, InputDouble etc.
IMGUI_API bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);
- IMGUI_API bool InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size = ImVec2(0,0), ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);
+ IMGUI_API bool InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);
IMGUI_API bool InputTextWithHint(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);
IMGUI_API bool InputFloat(const char* label, float* v, float step = 0.0f, float step_fast = 0.0f, const char* format = "%.3f", ImGuiInputTextFlags flags = 0);
IMGUI_API bool InputFloat2(const char* label, float v[2], const char* format = "%.3f", ImGuiInputTextFlags flags = 0);
@@ -493,14 +542,14 @@ namespace ImGui
IMGUI_API bool InputScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_step = NULL, const void* p_step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags flags = 0);
IMGUI_API bool InputScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_step = NULL, const void* p_step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags flags = 0);
- // Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little colored preview square that can be left-clicked to open a picker, and right-clicked to open an option menu.)
+ // Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little color square that can be left-clicked to open a picker, and right-clicked to open an option menu.)
// - Note that in C++ 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 the address of a first float element out of a contiguous structure, e.g. &myvector.x
IMGUI_API bool ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags = 0);
IMGUI_API bool ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0);
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 bool ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0)); // display a color 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.
// Widgets: Trees
@@ -520,20 +569,20 @@ namespace ImGui
IMGUI_API void TreePop(); // ~ Unindent()+PopId()
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 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
+ IMGUI_API bool CollapsingHeader(const char* label, bool* p_visible, ImGuiTreeNodeFlags flags = 0); // when 'p_visible != NULL': if '*p_visible==true' display an additional small close button on upper right of the header which will set the bool to false when clicked, if '*p_visible==false' don't display the header.
IMGUI_API void SetNextItemOpen(bool is_open, ImGuiCond cond = 0); // set next TreeNode/CollapsingHeader open state.
// Widgets: Selectables
// - A selectable highlights when hovered, and can display another color when selected.
// - Neighbors selectable extend their highlight bounds in order to leave no gap between them. This is so a series of selected Selectable appear contiguous.
- 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 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.
// Widgets: List Boxes
// - FIXME: To be consistent with all the newer API, ListBoxHeader/ListBoxFooter should in reality be called BeginListBox/EndListBox. Will rename them.
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. if the function return true, you can output elements then 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. if the function return true, you can output elements then 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. only call ListBoxFooter() if ListBoxHeader() returned true!
@@ -552,7 +601,8 @@ namespace ImGui
// Widgets: Menus
// - Use BeginMenuBar() on a window ImGuiWindowFlags_MenuBar to append to its menu bar.
- // - Use BeginMainMenuBar() to create a menu bar at the top of the screen.
+ // - Use BeginMainMenuBar() to create a menu bar at the top of the screen and append to it.
+ // - Use BeginMenu() to create a menu. You can call BeginMenu() multiple time with the same identifier to append more items to it.
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 BeginMainMenuBar(); // create and append to a full screen menu-bar.
@@ -563,35 +613,109 @@ namespace ImGui
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
// Tooltips
- // - Tooltip are windows following the mouse which do not take focus away.
+ // - Tooltip are windows following the mouse. They do not take focus away.
IMGUI_API void BeginTooltip(); // begin/append a tooltip window. to create full-featured tooltip (with any kind of items).
IMGUI_API void EndTooltip();
IMGUI_API void SetTooltip(const char* fmt, ...) IM_FMTARGS(1); // set a text-only tooltip, typically use with ImGui::IsItemHovered(). override any previous call to SetTooltip().
IMGUI_API void SetTooltipV(const char* fmt, va_list args) IM_FMTLIST(1);
// Popups, Modals
- // The properties of popups windows are:
- // - They block normal mouse hovering detection outside them. (*)
- // - Unless modal, they can be closed by clicking anywhere outside them, or by pressing ESCAPE.
- // - Their visibility state (~bool) is held internally by imgui instead of being held by the programmer as we are used to with regular Begin() calls.
- // User can manipulate the visibility state by calling OpenPopup().
- // (*) You can use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup) to bypass it and detect hovering even when normally blocked by a popup.
- // Those three properties are connected. The library needs to hold their visibility state because it can close popups at any time.
- 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 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 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 (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors). return true when just opened.
- IMGUI_API bool IsPopupOpen(const char* str_id); // return true if the popup is open at the current begin-ed level of the popup stack.
- IMGUI_API void CloseCurrentPopup(); // close the popup we have begin-ed into. clicking on a MenuItem or Selectable automatically close the current popup.
+ // - They block normal mouse hovering detection (and therefore most mouse interactions) behind them.
+ // - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE.
+ // - Their visibility state (~bool) is held internally instead of being held by the programmer as we are used to with regular Begin*() calls.
+ // - The 3 properties above are related: we need to retain popup visibility state in the library because popups may be closed as any time.
+ // - You can bypass the hovering restriction by using ImGuiHoveredFlags_AllowWhenBlockedByPopup when calling IsItemHovered() or IsWindowHovered().
+ // - IMPORTANT: Popup identifiers are relative to the current ID stack, so OpenPopup and BeginPopup generally needs to be at the same level of the stack.
+ // This is sometimes leading to confusing mistakes. May rework this in the future.
+ // Popups: begin/end functions
+ // - BeginPopup(): query popup state, if open start appending into the window. Call EndPopup() afterwards. ImGuiWindowFlags are forwarded to the window.
+ // - BeginPopupModal(): block every interactions behind the window, cannot be closed by user, add a dimming background, has a title bar.
+ 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.
+ IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // return true if the modal is open, and you can start outputting to it.
+ IMGUI_API void EndPopup(); // only call EndPopup() if BeginPopupXXX() returns true!
+ // Popups: open/close functions
+ // - OpenPopup(): set popup state to open. ImGuiPopupFlags are available for opening options.
+ // - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE.
+ // - CloseCurrentPopup(): use inside the BeginPopup()/EndPopup() scope to close manually.
+ // - CloseCurrentPopup() is called by default by Selectable()/MenuItem() when activated (FIXME: need some options).
+ // - Use ImGuiPopupFlags_NoOpenOverExistingPopup to avoid opening a popup if there's already one at the same level. This is equivalent to e.g. testing for !IsAnyPopupOpen() prior to OpenPopup().
+ IMGUI_API void OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags = 0); // call to mark popup as open (don't call every frame!).
+ IMGUI_API void OpenPopupOnItemClick(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // helper to open popup when clicked on last item. return true when just opened. (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors)
+ IMGUI_API void CloseCurrentPopup(); // manually close the popup we have begin-ed into.
+ // Popups: open+begin combined functions helpers
+ // - Helpers to do OpenPopup+BeginPopup where the Open action is triggered by e.g. hovering an item and right-clicking.
+ // - They are convenient to easily create context menus, hence the name.
+ // - IMPORTANT: Notice that BeginPopupContextXXX takes ImGuiPopupFlags just like OpenPopup() and unlike BeginPopup(). For full consistency, we may add ImGuiWindowFlags to the BeginPopupContextXXX functions in the future.
+ // - IMPORTANT: we exceptionally default their flags to 1 (== ImGuiPopupFlags_MouseButtonRight) for backward compatibility with older API taking 'int mouse_button = 1' parameter, so if you add other flags remember to re-add the ImGuiPopupFlags_MouseButtonRight.
+ IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // open+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, ImGuiPopupFlags popup_flags = 1);// open+begin popup when clicked on current window.
+ IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // open+begin popup when clicked in void (where there are no windows).
+ // Popups: test function
+ // - IsPopupOpen(): return true if the popup is open at the current BeginPopup() level of the popup stack.
+ // - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId: return true if any popup is open at the current BeginPopup() level of the popup stack.
+ // - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId + ImGuiPopupFlags_AnyPopupLevel: return true if any popup is open.
+ IMGUI_API bool IsPopupOpen(const char* str_id, ImGuiPopupFlags flags = 0); // return true if the popup is open.
- // Columns
+ // Tables
+ // [BETA API] API may evolve slightly! If you use this, please update to the next version when it comes out!
+ // - Full-featured replacement for old Columns API.
+ // - See Demo->Tables for demo code.
+ // - See top of imgui_tables.cpp for general commentary.
+ // - See ImGuiTableFlags_ and ImGuiTableColumnFlags_ enums for a description of available flags.
+ // The typical call flow is:
+ // - 1. Call BeginTable().
+ // - 2. Optionally call TableSetupColumn() to submit column name/flags/defaults.
+ // - 3. Optionally call TableSetupScrollFreeze() to request scroll freezing of columns/rows.
+ // - 4. Optionally call TableHeadersRow() to submit a header row. Names are pulled from TableSetupColumn() data.
+ // - 5. Populate contents:
+ // - In most situations you can use TableNextRow() + TableSetColumnIndex(N) to start appending into a column.
+ // - If you are using tables as a sort of grid, where every columns is holding the same type of contents,
+ // you may prefer using TableNextColumn() instead of TableNextRow() + TableSetColumnIndex().
+ // TableNextColumn() will automatically wrap-around into the next row if needed.
+ // - IMPORTANT: Comparatively to the old Columns() API, we need to call TableNextColumn() for the first column!
+ // - Summary of possible call flow:
+ // --------------------------------------------------------------------------------------------------------
+ // TableNextRow() -> TableSetColumnIndex(0) -> Text("Hello 0") -> TableSetColumnIndex(1) -> Text("Hello 1") // OK
+ // TableNextRow() -> TableNextColumn() -> Text("Hello 0") -> TableNextColumn() -> Text("Hello 1") // OK
+ // TableNextColumn() -> Text("Hello 0") -> TableNextColumn() -> Text("Hello 1") // OK: TableNextColumn() automatically gets to next row!
+ // TableNextRow() -> Text("Hello 0") // Not OK! Missing TableSetColumnIndex() or TableNextColumn()! Text will not appear!
+ // --------------------------------------------------------------------------------------------------------
+ // - 5. Call EndTable()
+ IMGUI_API bool BeginTable(const char* str_id, int column, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0.0f, 0.0f), float inner_width = 0.0f);
+ IMGUI_API void EndTable(); // only call EndTable() if BeginTable() returns true!
+ IMGUI_API void TableNextRow(ImGuiTableRowFlags row_flags = 0, float min_row_height = 0.0f); // append into the first cell of a new row.
+ IMGUI_API bool TableNextColumn(); // append into the next column (or first column of next row if currently in last column). Return true when column is visible.
+ IMGUI_API bool TableSetColumnIndex(int column_n); // append into the specified column. Return true when column is visible.
+ // Tables: Headers & Columns declaration
+ // - Use TableSetupColumn() to specify label, resizing policy, default width/weight, id, various other flags etc.
+ // - Use TableHeadersRow() to create a header row and automatically submit a TableHeader() for each column.
+ // Headers are required to perform: reordering, sorting, and opening the context menu.
+ // The context menu can also be made available in columns body using ImGuiTableFlags_ContextMenuInBody.
+ // - You may manually submit headers using TableNextRow() + TableHeader() calls, but this is only useful in
+ // some advanced use cases (e.g. adding custom widgets in header row).
+ // - Use TableSetupScrollFreeze() to lock columns/rows so they stay visible when scrolled.
+ IMGUI_API void TableSetupColumn(const char* label, ImGuiTableColumnFlags flags = 0, float init_width_or_weight = 0.0f, ImU32 user_id = 0);
+ IMGUI_API void TableSetupScrollFreeze(int cols, int rows); // lock columns/rows so they stay visible when scrolled.
+ IMGUI_API void TableHeadersRow(); // submit all headers cells based on data provided to TableSetupColumn() + submit context menu
+ IMGUI_API void TableHeader(const char* label); // submit one header cell manually (rarely used)
+ // Tables: Sorting
+ // - Call TableGetSortSpecs() to retrieve latest sort specs for the table. NULL when not sorting.
+ // - When 'SpecsDirty == true' you should sort your data. It will be true when sorting specs have changed
+ // since last call, or the first time. Make sure to set 'SpecsDirty = false' after sorting, else you may
+ // wastefully sort your data every frame!
+ // - Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable().
+ IMGUI_API ImGuiTableSortSpecs* TableGetSortSpecs(); // get latest sort specs for the table (NULL if not sorting).
+ // Tables: Miscellaneous functions
+ // - Functions args 'int column_n' treat the default value of -1 as the same as passing the current column index.
+ IMGUI_API int TableGetColumnCount(); // return number of columns (value passed to BeginTable)
+ IMGUI_API int TableGetColumnIndex(); // return current column index.
+ IMGUI_API int TableGetRowIndex(); // return current row index.
+ IMGUI_API const char* TableGetColumnName(int column_n = -1); // return "" if column didn't have a name declared by TableSetupColumn(). Pass -1 to use current column.
+ IMGUI_API ImGuiTableColumnFlags TableGetColumnFlags(int column_n = -1); // return column flags so you can query their Enabled/Visible/Sorted/Hovered status flags. Pass -1 to use current column.
+ IMGUI_API void TableSetBgColor(ImGuiTableBgTarget target, ImU32 color, int column_n = -1); // change the color of a cell, row, or column. See ImGuiTableBgTarget_ flags for details.
+
+ // Legacy Columns API (2020: prefer using Tables!)
// - You can also use SameLine(pos_x) to mimic simplified columns.
- // - The columns API is work-in-progress and rather lacking (columns are arguably the worst part of dear imgui at the moment!)
- // - By end of the 2019 we will expose a new 'Table' api which will replace columns.
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
@@ -602,26 +726,13 @@ namespace ImGui
IMGUI_API int GetColumnsCount();
// Tab Bars, Tabs
- // Note: Tabs are automatically created by the docking system. Use this to create tab bars/tabs yourself without docking being involved.
IMGUI_API bool BeginTabBar(const char* str_id, ImGuiTabBarFlags flags = 0); // create and append into a TabBar
IMGUI_API void EndTabBar(); // only call EndTabBar() if BeginTabBar() returns true!
- IMGUI_API bool BeginTabItem(const char* label, bool* p_open = NULL, ImGuiTabItemFlags flags = 0);// create a Tab. Returns true if the Tab is selected.
+ IMGUI_API bool BeginTabItem(const char* label, bool* p_open = NULL, ImGuiTabItemFlags flags = 0); // create a Tab. Returns true if the Tab is selected.
IMGUI_API void EndTabItem(); // only call EndTabItem() if BeginTabItem() returns true!
+ IMGUI_API bool TabItemButton(const char* label, ImGuiTabItemFlags flags = 0); // create a Tab behaving like a button. return true when clicked. cannot be selected in the tab bar.
IMGUI_API void SetTabItemClosed(const char* tab_or_docked_window_label); // notify TabBar or Docking system of a closed tab/window ahead (useful to reduce visual flicker on reorderable tab bars). For tab-bar: call after BeginTabBar() and before Tab submissions. Otherwise call with a window name.
- // Docking
- // [BETA API] Enable with io.ConfigFlags |= ImGuiConfigFlags_DockingEnable.
- // Note: you DO NOT need to call DockSpace() to use most Docking facilities!
- // - To dock windows: if io.ConfigDockingWithShift == false (default) drag window from their title bar.
- // - To dock windows: if io.ConfigDockingWithShift == true: hold SHIFT anywhere while moving windows.
- // - Use DockSpace() to create an explicit dock node _within_ an existing window. See Docking demo for details.
- IMGUI_API void DockSpace(ImGuiID id, const ImVec2& size = ImVec2(0, 0), ImGuiDockNodeFlags flags = 0, const ImGuiWindowClass* window_class = NULL);
- IMGUI_API ImGuiID DockSpaceOverViewport(ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, const ImGuiWindowClass* window_class = NULL);
- IMGUI_API void SetNextWindowDockID(ImGuiID dock_id, ImGuiCond cond = 0); // set next window dock id (FIXME-DOCK)
- IMGUI_API void SetNextWindowClass(const ImGuiWindowClass* window_class); // set next window class (rare/advanced uses: provide hints to the platform back-end via altered viewport flags and parent/child info)
- IMGUI_API ImGuiID GetWindowDockID();
- IMGUI_API bool IsWindowDocked(); // is current window docked into another window?
-
// Logging/Capture
// - All text output from the interface can be captured into tty/file/clipboard. By default, tree nodes are automatically opened during logging.
IMGUI_API void LogToTTY(int auto_open_depth = -1); // start logging to tty (stdout)
@@ -632,7 +743,7 @@ namespace ImGui
IMGUI_API void LogText(const char* fmt, ...) IM_FMTARGS(1); // pass text data straight to log (without being displayed)
// Drag and Drop
- // [BETA API] API may evolve!
+ // - If you stop calling BeginDragDropSource() the payload is preserved however it won't have a preview tooltip (we currently display a fallback "..." tooltip as replacement)
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 sz, 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!
@@ -642,6 +753,7 @@ namespace ImGui
IMGUI_API const ImGuiPayload* GetDragDropPayload(); // peek directly into the current payload from anywhere. may return NULL. use ImGuiPayload::IsDataType() to test for the payload type.
// Clipping
+ // - Mouse hovering is affected by ImGui::PushClipRect() calls, unlike direct calls to ImDrawList::PushClipRect() which are render only.
IMGUI_API void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect);
IMGUI_API void PopClipRect();
@@ -656,12 +768,13 @@ namespace ImGui
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. This will continuously return true while holding mouse button on an item. 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) == IsMouseClicked(mouse_button) && IsItemHovered()
+ IMGUI_API bool IsItemClicked(ImGuiMouseButton mouse_button = 0); // is the last item clicked? (e.g. button/node just clicked on) == IsMouseClicked(mouse_button) && IsItemHovered()
IMGUI_API bool IsItemVisible(); // is the last item visible? (items may be out of sight because of clipping/scrolling)
IMGUI_API bool IsItemEdited(); // did the last item modify its underlying value this frame? or was pressed? This is generally the same as the "bool" return value of many widgets.
IMGUI_API bool IsItemActivated(); // was the last item just made active (item was previously inactive).
IMGUI_API bool IsItemDeactivated(); // was the last item just made inactive (item was previously active). Useful for Undo/Redo patterns with widgets that requires continuous editing.
IMGUI_API bool IsItemDeactivatedAfterEdit(); // was the last item just made inactive and made a value change when it was active? (e.g. Slider/Drag moved). Useful for Undo/Redo patterns with widgets that requires continuous editing. Note that you may get false positives (some widgets such as Combo()/ListBox()/Selectable() will return true even when clicking an already selected item).
+ IMGUI_API bool IsItemToggledOpen(); // was the last item open state toggled? set by TreeNode().
IMGUI_API bool IsAnyItemHovered(); // is any item hovered?
IMGUI_API bool IsAnyItemActive(); // is any item active?
IMGUI_API bool IsAnyItemFocused(); // is any item focused?
@@ -675,49 +788,57 @@ namespace ImGui
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 double GetTime(); // get global imgui time. incremented by io.DeltaTime every frame.
IMGUI_API int GetFrameCount(); // get global imgui frame count. incremented by 1 every frame.
- IMGUI_API ImDrawList* GetBackgroundDrawList(); // get background draw list for the viewport associated to the current window. this draw list will be the first rendering one. Useful to quickly draw shapes/text behind dear imgui contents.
- IMGUI_API ImDrawList* GetForegroundDrawList(); // get foreground draw list for the viewport associated to the current window. this draw list will be the last rendered one. Useful to quickly draw shapes/text over dear imgui contents.
- IMGUI_API ImDrawList* GetBackgroundDrawList(ImGuiViewport* viewport); // get background draw list for the given viewport. this draw list will be the first rendering one. Useful to quickly draw shapes/text behind dear imgui contents.
- IMGUI_API ImDrawList* GetForegroundDrawList(ImGuiViewport* viewport); // get foreground draw list for the given viewport. this draw list will be the last rendered one. Useful to quickly draw shapes/text over dear imgui contents.
+ IMGUI_API ImDrawList* GetBackgroundDrawList(); // this draw list will be the first rendering one. Useful to quickly draw shapes/text behind dear imgui contents.
+ IMGUI_API ImDrawList* GetForegroundDrawList(); // this draw list will be the last rendered one. Useful to quickly draw shapes/text over dear imgui contents.
IMGUI_API ImDrawListSharedData* GetDrawListSharedData(); // you may use this when creating your own ImDrawList instances.
IMGUI_API const char* GetStyleColorName(ImGuiCol idx); // get a string corresponding to the enum value (for display, saving, etc.).
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 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)
+ // Text Utilities
+ IMGUI_API ImVec2 CalcTextSize(const char* text, const char* text_end = NULL, bool hide_text_after_double_hash = false, float wrap_width = -1.0f);
+
// Color Utilities
IMGUI_API ImVec4 ColorConvertU32ToFloat4(ImU32 in);
IMGUI_API ImU32 ColorConvertFloat4ToU32(const ImVec4& in);
IMGUI_API void ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v);
IMGUI_API void ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b);
- // Inputs Utilities
+ // Inputs Utilities: Keyboard
+ // - For 'int user_key_index' you can use your own indices/enums according to how your backend/engine stored them in io.KeysDown[].
+ // - We don't know the meaning of those value. You can use GetKeyIndex() to map a ImGuiKey_ value into the user index.
IMGUI_API int GetKeyIndex(ImGuiKey imgui_key); // map ImGuiKey_* values into user's key index. == io.KeyMap[key]
- IMGUI_API bool IsKeyDown(int user_key_index); // is key being held. == io.KeysDown[user_key_index]. note that imgui doesn't know the semantic of each entry of io.KeysDown[]. Use your own indices/enums according to how your backend/engine stored them into io.KeysDown[]!
- IMGUI_API bool IsKeyPressed(int user_key_index, bool repeat = true); // was key pressed (went from !Down to Down). if repeat=true, uses io.KeyRepeatDelay / KeyRepeatRate
- IMGUI_API bool IsKeyReleased(int user_key_index); // was key released (went from Down to !Down)..
+ IMGUI_API bool IsKeyDown(int user_key_index); // is key being held. == io.KeysDown[user_key_index].
+ IMGUI_API bool IsKeyPressed(int user_key_index, bool repeat = true); // was key pressed (went from !Down to Down)? if repeat=true, uses io.KeyRepeatDelay / KeyRepeatRate
+ 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 (0=left, 1=right, 2=middle)
- 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) (0=left, 1=right, 2=middle)
- 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)
- IMGUI_API bool IsMouseDragging(int button = 0, float lock_threshold = -1.0f); // is mouse dragging. if lock_threshold < -1.0f uses io.MouseDraggingThreshold
- 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, but disregarding of other consideration of focus/window ordering/popup-block.
- IMGUI_API bool IsMousePosValid(const ImVec2* mouse_pos = NULL); // by convention we use (-FLT_MAX,-FLT_MAX) to denote that there is no mouse
- 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 position at the time of opening popup we have BeginPopup() into
- IMGUI_API ImVec2 GetMouseDragDelta(int button = 0, float lock_threshold = -1.0f); // return the delta from the initial clicking position while the mouse button is pressed or was just released. This is locked and return 0.0f until the mouse moves past a distance threshold at least once. 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 want_capture_keyboard_value = true); // attention: misleading name! 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. This is equivalent to setting "io.WantCaptureKeyboard = want_capture_keyboard_value"; after the next NewFrame() call.
+
+ // Inputs Utilities: Mouse
+ // - To refer to a mouse button, you may use named enums in your code e.g. ImGuiMouseButton_Left, ImGuiMouseButton_Right.
+ // - You can also use regular integer: it is forever guaranteed that 0=Left, 1=Right, 2=Middle.
+ // - Dragging operations are only reported after mouse has moved a certain distance away from the initial clicking position (see 'lock_threshold' and 'io.MouseDraggingThreshold')
+ IMGUI_API bool IsMouseDown(ImGuiMouseButton button); // is mouse button held?
+ IMGUI_API bool IsMouseClicked(ImGuiMouseButton button, bool repeat = false); // did mouse button clicked? (went from !Down to Down)
+ IMGUI_API bool IsMouseReleased(ImGuiMouseButton button); // did mouse button released? (went from Down to !Down)
+ IMGUI_API bool IsMouseDoubleClicked(ImGuiMouseButton button); // did mouse button double-clicked? (note that a double-click will also report IsMouseClicked() == true)
+ 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, but disregarding of other consideration of focus/window ordering/popup-block.
+ IMGUI_API bool IsMousePosValid(const ImVec2* mouse_pos = NULL); // by convention we use (-FLT_MAX,-FLT_MAX) to denote that there is no mouse available
+ IMGUI_API bool IsAnyMouseDown(); // is any mouse button held?
+ IMGUI_API ImVec2 GetMousePos(); // shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls
+ IMGUI_API ImVec2 GetMousePosOnOpeningCurrentPopup(); // retrieve mouse position at the time of opening popup we have BeginPopup() into (helper to avoid user backing that value themselves)
+ IMGUI_API bool IsMouseDragging(ImGuiMouseButton button, float lock_threshold = -1.0f); // is mouse dragging? (if lock_threshold < -1.0f, uses io.MouseDraggingThreshold)
+ IMGUI_API ImVec2 GetMouseDragDelta(ImGuiMouseButton button = 0, float lock_threshold = -1.0f); // return the delta from the initial clicking position while the mouse button is pressed or was just released. This is locked and return 0.0f until the mouse moves past a distance threshold at least once (if lock_threshold < -1.0f, uses io.MouseDraggingThreshold)
+ IMGUI_API void ResetMouseDragDelta(ImGuiMouseButton 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 cursor_type); // set desired cursor type
IMGUI_API void CaptureMouseFromApp(bool want_capture_mouse_value = true); // attention: misleading name! manually override io.WantCaptureMouse flag next frame (said flag is entirely left for your application to handle). This is equivalent to setting "io.WantCaptureMouse = want_capture_mouse_value;" after the next NewFrame() call.
- // Clipboard Utilities (also see the LogToClipboard() function to capture or output text data to the clipboard)
+ // Clipboard Utilities
+ // - Also see the LogToClipboard() function to capture GUI into clipboard, or easily output text data to the clipboard.
IMGUI_API const char* GetClipboardText();
IMGUI_API void SetClipboardText(const char* text);
@@ -729,6 +850,9 @@ namespace ImGui
IMGUI_API void SaveIniSettingsToDisk(const char* ini_filename); // this is automatically called (if io.IniFilename is not empty) a few seconds after any modification that should be reflected in the .ini file (and also by DestroyContext).
IMGUI_API const char* SaveIniSettingsToMemory(size_t* out_ini_size = NULL); // return a zero-terminated string with the .ini data which you can save by your own mean. call when io.WantSaveIniSettings is set, then save data by your own mean and clear io.WantSaveIniSettings.
+ // Debug Utilities
+ IMGUI_API bool DebugCheckVersionAndDataLayout(const char* version_str, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_drawvert, size_t sz_drawidx); // This is called by IMGUI_CHECKVERSION() macro.
+
// Memory Allocators
// - 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 because we use global storage for those.
@@ -736,20 +860,10 @@ namespace ImGui
IMGUI_API void* MemAlloc(size_t size);
IMGUI_API void MemFree(void* ptr);
- // (Optional) Platform/OS interface for multi-viewport support
- // Note: You may use GetWindowViewport() to get the current viewport of the current window.
- IMGUI_API ImGuiPlatformIO& GetPlatformIO(); // platform/renderer functions, for back-end to setup + viewports list.
- IMGUI_API ImGuiViewport* GetMainViewport(); // main viewport. same as GetPlatformIO().MainViewport == GetPlatformIO().Viewports[0].
- IMGUI_API void UpdatePlatformWindows(); // call in main loop. will call CreateWindow/ResizeWindow/etc. platform functions for each secondary viewport, and DestroyWindow for each inactive viewport.
- IMGUI_API void RenderPlatformWindowsDefault(void* platform_arg = NULL, void* renderer_arg = NULL); // call in main loop. will call RenderWindow/SwapBuffers platform functions for each secondary viewport which doesn't have the ImGuiViewportFlags_Minimized flag set. May be reimplemented by user for custom rendering needs.
- IMGUI_API void DestroyPlatformWindows(); // call DestroyWindow platform functions for all viewports. call from back-end Shutdown() if you need to close platform windows before imgui shutdown. otherwise will be called by DestroyContext().
- IMGUI_API ImGuiViewport* FindViewportByID(ImGuiID id); // this is a helper for back-ends.
- IMGUI_API ImGuiViewport* FindViewportByPlatformHandle(void* platform_handle); // this is a helper for back-ends. the type platform_handle is decided by the back-end (e.g. HWND, MyWindow*, GLFWwindow* etc.)
-
} // namespace ImGui
//-----------------------------------------------------------------------------
-// Flags & Enumerations
+// [SECTION] Flags & Enumerations
//-----------------------------------------------------------------------------
// Flags for ImGui::Begin()
@@ -761,7 +875,7 @@ enum ImGuiWindowFlags_
ImGuiWindowFlags_NoMove = 1 << 2, // Disable user moving the window
ImGuiWindowFlags_NoScrollbar = 1 << 3, // Disable scrollbars (window can still scroll with mouse or programmatically)
ImGuiWindowFlags_NoScrollWithMouse = 1 << 4, // Disable user vertically scrolling with mouse wheel. On child window, mouse wheel will be forwarded to the parent unless NoScrollbar is also set.
- ImGuiWindowFlags_NoCollapse = 1 << 5, // Disable user collapsing window by double-clicking on it. Also referred to as "window menu button" within a docking node.
+ ImGuiWindowFlags_NoCollapse = 1 << 5, // Disable user collapsing window by double-clicking on it
ImGuiWindowFlags_AlwaysAutoResize = 1 << 6, // Resize every window to its content every frame
ImGuiWindowFlags_NoBackground = 1 << 7, // Disable drawing background color (WindowBg, etc.) and outside border. Similar as using SetNextWindowBgAlpha(0.0f).
ImGuiWindowFlags_NoSavedSettings = 1 << 8, // Never load/save settings in .ini file
@@ -776,8 +890,6 @@ enum ImGuiWindowFlags_
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_UnsavedDocument = 1 << 20, // Append '*' to title without affecting the ID, as a convenience to avoid using the ### operator. When used in a tab/docking context, tab is selected on closure and closure is deferred by one frame to allow code to cancel the closure (with a confirmation popup, etc.) without flicker.
- ImGuiWindowFlags_NoDocking = 1 << 21, // Disable docking of this window
-
ImGuiWindowFlags_NoNav = ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus,
ImGuiWindowFlags_NoDecoration = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse,
ImGuiWindowFlags_NoInputs = ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus,
@@ -788,12 +900,10 @@ enum ImGuiWindowFlags_
ImGuiWindowFlags_Tooltip = 1 << 25, // Don't use! For internal use by BeginTooltip()
ImGuiWindowFlags_Popup = 1 << 26, // Don't use! For internal use by BeginPopup()
ImGuiWindowFlags_Modal = 1 << 27, // Don't use! For internal use by BeginPopupModal()
- ImGuiWindowFlags_ChildMenu = 1 << 28, // Don't use! For internal use by BeginMenu()
- ImGuiWindowFlags_DockNodeHost = 1 << 29 // Don't use! For internal use by Begin()/NewFrame()
+ ImGuiWindowFlags_ChildMenu = 1 << 28 // Don't use! For internal use by BeginMenu()
// [Obsolete]
- //ImGuiWindowFlags_ShowBorders = 1 << 7, // --> Set style.FrameBorderSize=1.0f / style.WindowBorderSize=1.0f to enable borders around windows and items
- //ImGuiWindowFlags_ResizeFromAnySide = 1 << 17, // --> Set io.ConfigWindowsResizeFromEdges and make sure mouse cursors are supported by back-end (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors)
+ //ImGuiWindowFlags_ResizeFromAnySide = 1 << 17, // --> Set io.ConfigWindowsResizeFromEdges=true and make sure mouse cursors are supported by backend (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors)
};
// Flags for ImGui::InputText()
@@ -819,6 +929,7 @@ enum ImGuiInputTextFlags_
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)
ImGuiInputTextFlags_CallbackResize = 1 << 18, // Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. Notify when the string wants to be resized (for string types which hold a cache of their Size). You will be provided a new BufSize in the callback and NEED to honor it. (see misc/cpp/imgui_stdlib.h for an example of using this)
+ ImGuiInputTextFlags_CallbackEdit = 1 << 19, // Callback on any edit (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the underlying buffer while focus is active)
// [Internal]
ImGuiInputTextFlags_Multiline = 1 << 20, // For internal use by InputTextMultiline()
ImGuiInputTextFlags_NoMarkEdited = 1 << 21 // For internal use by functions using InputText() before reformatting data
@@ -829,7 +940,7 @@ enum ImGuiTreeNodeFlags_
{
ImGuiTreeNodeFlags_None = 0,
ImGuiTreeNodeFlags_Selected = 1 << 0, // Draw as selected
- ImGuiTreeNodeFlags_Framed = 1 << 1, // Full colored frame (e.g. for CollapsingHeader)
+ ImGuiTreeNodeFlags_Framed = 1 << 1, // Draw frame with background (e.g. for CollapsingHeader)
ImGuiTreeNodeFlags_AllowItemOverlap = 1 << 2, // Hit testing to allow subsequent widgets to overlap this one
ImGuiTreeNodeFlags_NoTreePushOnOpen = 1 << 3, // Don't do a TreePush() when open (e.g. for CollapsingHeader) = no extra indent nor pushing on ID stack
ImGuiTreeNodeFlags_NoAutoOpenOnLog = 1 << 4, // Don't automatically and temporarily open node when Logging is active (by default logging will automatically open tree nodes)
@@ -844,11 +955,29 @@ enum ImGuiTreeNodeFlags_
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_NoScrollOnOpen = 1 << 14, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible
ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_NoAutoOpenOnLog
+};
- // Obsolete names (will be removed)
-#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
- , ImGuiTreeNodeFlags_AllowOverlapMode = ImGuiTreeNodeFlags_AllowItemOverlap // [renamed in 1.53]
-#endif
+// Flags for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() functions.
+// - To be backward compatible with older API which took an 'int mouse_button = 1' argument, we need to treat
+// small flags values as a mouse button index, so we encode the mouse button in the first few bits of the flags.
+// It is therefore guaranteed to be legal to pass a mouse button index in ImGuiPopupFlags.
+// - For the same reason, we exceptionally default the ImGuiPopupFlags argument of BeginPopupContextXXX functions to 1 instead of 0.
+// IMPORTANT: because the default parameter is 1 (==ImGuiPopupFlags_MouseButtonRight), if you rely on the default parameter
+// and want to another another flag, you need to pass in the ImGuiPopupFlags_MouseButtonRight flag.
+// - Multiple buttons currently cannot be combined/or-ed in those functions (we could allow it later).
+enum ImGuiPopupFlags_
+{
+ ImGuiPopupFlags_None = 0,
+ ImGuiPopupFlags_MouseButtonLeft = 0, // For BeginPopupContext*(): open on Left Mouse release. Guaranteed to always be == 0 (same as ImGuiMouseButton_Left)
+ ImGuiPopupFlags_MouseButtonRight = 1, // For BeginPopupContext*(): open on Right Mouse release. Guaranteed to always be == 1 (same as ImGuiMouseButton_Right)
+ ImGuiPopupFlags_MouseButtonMiddle = 2, // For BeginPopupContext*(): open on Middle Mouse release. Guaranteed to always be == 2 (same as ImGuiMouseButton_Middle)
+ ImGuiPopupFlags_MouseButtonMask_ = 0x1F,
+ ImGuiPopupFlags_MouseButtonDefault_ = 1,
+ ImGuiPopupFlags_NoOpenOverExistingPopup = 1 << 5, // For OpenPopup*(), BeginPopupContext*(): don't open if there's already a popup at the same level of the popup stack
+ ImGuiPopupFlags_NoOpenOverItems = 1 << 6, // For BeginPopupContextWindow(): don't return true when hovering items, only when hovering empty space
+ ImGuiPopupFlags_AnyPopupId = 1 << 7, // For IsPopupOpen(): ignore the ImGuiID parameter and test for any popup.
+ ImGuiPopupFlags_AnyPopupLevel = 1 << 8, // For IsPopupOpen(): search/test at any level of the popup stack (default test in the current level)
+ ImGuiPopupFlags_AnyPopup = ImGuiPopupFlags_AnyPopupId | ImGuiPopupFlags_AnyPopupLevel
};
// Flags for ImGui::Selectable()
@@ -899,7 +1028,154 @@ enum ImGuiTabItemFlags_
ImGuiTabItemFlags_UnsavedDocument = 1 << 0, // Append '*' to title without affecting the ID, as a convenience to avoid using the ### operator. Also: tab is selected on closure and closure is deferred by one frame to allow code to undo it without flicker.
ImGuiTabItemFlags_SetSelected = 1 << 1, // Trigger flag to programmatically make the tab selected when calling BeginTabItem()
ImGuiTabItemFlags_NoCloseWithMiddleMouseButton = 1 << 2, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You can still repro this behavior on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false.
- ImGuiTabItemFlags_NoPushId = 1 << 3 // Don't call PushID(tab->ID)/PopID() on BeginTabItem()/EndTabItem()
+ ImGuiTabItemFlags_NoPushId = 1 << 3, // Don't call PushID(tab->ID)/PopID() on BeginTabItem()/EndTabItem()
+ ImGuiTabItemFlags_NoTooltip = 1 << 4, // Disable tooltip for the given tab
+ ImGuiTabItemFlags_NoReorder = 1 << 5, // Disable reordering this tab or having another tab cross over this tab
+ ImGuiTabItemFlags_Leading = 1 << 6, // Enforce the tab position to the left of the tab bar (after the tab list popup button)
+ ImGuiTabItemFlags_Trailing = 1 << 7 // Enforce the tab position to the right of the tab bar (before the scrolling buttons)
+};
+
+// Flags for ImGui::BeginTable()
+// [BETA API] API may evolve slightly! If you use this, please update to the next version when it comes out!
+// - Important! Sizing policies have complex and subtle side effects, more so than you would expect.
+// Read comments/demos carefully + experiment with live demos to get acquainted with them.
+// - The DEFAULT sizing policies are:
+// - Default to ImGuiTableFlags_SizingFixedFit if ScrollX is on, or if host window has ImGuiWindowFlags_AlwaysAutoResize.
+// - Default to ImGuiTableFlags_SizingStretchSame if ScrollX is off.
+// - When ScrollX is off:
+// - Table defaults to ImGuiTableFlags_SizingStretchSame -> all Columns defaults to ImGuiTableColumnFlags_WidthStretch with same weight.
+// - Columns sizing policy allowed: Stretch (default), Fixed/Auto.
+// - Fixed Columns will generally obtain their requested width (unless the table cannot fit them all).
+// - Stretch Columns will share the remaining width.
+// - Mixed Fixed/Stretch columns is possible but has various side-effects on resizing behaviors.
+// The typical use of mixing sizing policies is: any number of LEADING Fixed columns, followed by one or two TRAILING Stretch columns.
+// (this is because the visible order of columns have subtle but necessary effects on how they react to manual resizing).
+// - When ScrollX is on:
+// - Table defaults to ImGuiTableFlags_SizingFixedFit -> all Columns defaults to ImGuiTableColumnFlags_WidthFixed
+// - Columns sizing policy allowed: Fixed/Auto mostly.
+// - Fixed Columns can be enlarged as needed. Table will show an horizontal scrollbar if needed.
+// - When using auto-resizing (non-resizable) fixed columns, querying the content width to use item right-alignment e.g. SetNextItemWidth(-FLT_MIN) doesn't make sense, would create a feedback loop.
+// - Using Stretch columns OFTEN DOES NOT MAKE SENSE if ScrollX is on, UNLESS you have specified a value for 'inner_width' in BeginTable().
+// If you specify a value for 'inner_width' then effectively the scrolling space is known and Stretch or mixed Fixed/Stretch columns become meaningful again.
+// - Read on documentation at the top of imgui_tables.cpp for details.
+enum ImGuiTableFlags_
+{
+ // Features
+ ImGuiTableFlags_None = 0,
+ ImGuiTableFlags_Resizable = 1 << 0, // Enable resizing columns.
+ ImGuiTableFlags_Reorderable = 1 << 1, // Enable reordering columns in header row (need calling TableSetupColumn() + TableHeadersRow() to display headers)
+ ImGuiTableFlags_Hideable = 1 << 2, // Enable hiding/disabling columns in context menu.
+ ImGuiTableFlags_Sortable = 1 << 3, // Enable sorting. Call TableGetSortSpecs() to obtain sort specs. Also see ImGuiTableFlags_SortMulti and ImGuiTableFlags_SortTristate.
+ ImGuiTableFlags_NoSavedSettings = 1 << 4, // Disable persisting columns order, width and sort settings in the .ini file.
+ ImGuiTableFlags_ContextMenuInBody = 1 << 5, // Right-click on columns body/contents will display table context menu. By default it is available in TableHeadersRow().
+ // Decorations
+ ImGuiTableFlags_RowBg = 1 << 6, // Set each RowBg color with ImGuiCol_TableRowBg or ImGuiCol_TableRowBgAlt (equivalent of calling TableSetBgColor with ImGuiTableBgFlags_RowBg0 on each row manually)
+ ImGuiTableFlags_BordersInnerH = 1 << 7, // Draw horizontal borders between rows.
+ ImGuiTableFlags_BordersOuterH = 1 << 8, // Draw horizontal borders at the top and bottom.
+ ImGuiTableFlags_BordersInnerV = 1 << 9, // Draw vertical borders between columns.
+ ImGuiTableFlags_BordersOuterV = 1 << 10, // Draw vertical borders on the left and right sides.
+ ImGuiTableFlags_BordersH = ImGuiTableFlags_BordersInnerH | ImGuiTableFlags_BordersOuterH, // Draw horizontal borders.
+ ImGuiTableFlags_BordersV = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersOuterV, // Draw vertical borders.
+ ImGuiTableFlags_BordersInner = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersInnerH, // Draw inner borders.
+ ImGuiTableFlags_BordersOuter = ImGuiTableFlags_BordersOuterV | ImGuiTableFlags_BordersOuterH, // Draw outer borders.
+ ImGuiTableFlags_Borders = ImGuiTableFlags_BordersInner | ImGuiTableFlags_BordersOuter, // Draw all borders.
+ ImGuiTableFlags_NoBordersInBody = 1 << 11, // [ALPHA] Disable vertical borders in columns Body (borders will always appears in Headers). -> May move to style
+ ImGuiTableFlags_NoBordersInBodyUntilResize = 1 << 12, // [ALPHA] Disable vertical borders in columns Body until hovered for resize (borders will always appears in Headers). -> May move to style
+ // Sizing Policy (read above for defaults)
+ ImGuiTableFlags_SizingFixedFit = 1 << 13, // Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching contents width.
+ ImGuiTableFlags_SizingFixedSame = 2 << 13, // Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching the maximum contents width of all columns. Implicitly enable ImGuiTableFlags_NoKeepColumnsVisible.
+ ImGuiTableFlags_SizingStretchProp = 3 << 13, // Columns default to _WidthStretch with default weights proportional to each columns contents widths.
+ ImGuiTableFlags_SizingStretchSame = 4 << 13, // Columns default to _WidthStretch with default weights all equal, unless overriden by TableSetupColumn().
+ // Sizing Extra Options
+ ImGuiTableFlags_NoHostExtendX = 1 << 16, // Make outer width auto-fit to columns, overriding outer_size.x value. Only available when ScrollX/ScrollY are disabled and Stretch columns are not used.
+ ImGuiTableFlags_NoHostExtendY = 1 << 17, // Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible.
+ ImGuiTableFlags_NoKeepColumnsVisible = 1 << 18, // Disable keeping column always minimally visible when ScrollX is off and table gets too small. Not recommended if columns are resizable.
+ ImGuiTableFlags_PreciseWidths = 1 << 19, // Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth.
+ // Clipping
+ ImGuiTableFlags_NoClip = 1 << 20, // Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with TableSetupScrollFreeze().
+ // Padding
+ ImGuiTableFlags_PadOuterX = 1 << 21, // Default if BordersOuterV is on. Enable outer-most padding. Generally desirable if you have headers.
+ ImGuiTableFlags_NoPadOuterX = 1 << 22, // Default if BordersOuterV is off. Disable outer-most padding.
+ ImGuiTableFlags_NoPadInnerX = 1 << 23, // Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off).
+ // Scrolling
+ ImGuiTableFlags_ScrollX = 1 << 24, // Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Changes default sizing policy. Because this create a child window, ScrollY is currently generally recommended when using ScrollX.
+ ImGuiTableFlags_ScrollY = 1 << 25, // Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size.
+ // Sorting
+ ImGuiTableFlags_SortMulti = 1 << 26, // Hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1).
+ ImGuiTableFlags_SortTristate = 1 << 27, // Allow no sorting, disable default sorting. TableGetSortSpecs() may return specs where (SpecsCount == 0).
+
+ // [Internal] Combinations and masks
+ ImGuiTableFlags_SizingMask_ = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_SizingFixedSame | ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_SizingStretchSame
+
+ // Obsolete names (will be removed soon)
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ //, ImGuiTableFlags_ColumnsWidthFixed = ImGuiTableFlags_SizingFixedFit, ImGuiTableFlags_ColumnsWidthStretch = ImGuiTableFlags_SizingStretchSame // WIP Tables 2020/12
+ //, ImGuiTableFlags_SizingPolicyFixed = ImGuiTableFlags_SizingFixedFit, ImGuiTableFlags_SizingPolicyStretch = ImGuiTableFlags_SizingStretchSame // WIP Tables 2021/01
+#endif
+};
+
+// Flags for ImGui::TableSetupColumn()
+enum ImGuiTableColumnFlags_
+{
+ // Input configuration flags
+ ImGuiTableColumnFlags_None = 0,
+ ImGuiTableColumnFlags_DefaultHide = 1 << 0, // Default as a hidden/disabled column.
+ ImGuiTableColumnFlags_DefaultSort = 1 << 1, // Default as a sorting column.
+ ImGuiTableColumnFlags_WidthStretch = 1 << 2, // Column will stretch. Preferable with horizontal scrolling disabled (default if table sizing policy is _SizingStretchSame or _SizingStretchProp).
+ ImGuiTableColumnFlags_WidthFixed = 1 << 3, // Column will not stretch. Preferable with horizontal scrolling enabled (default if table sizing policy is _SizingFixedFit and table is resizable).
+ ImGuiTableColumnFlags_NoResize = 1 << 4, // Disable manual resizing.
+ ImGuiTableColumnFlags_NoReorder = 1 << 5, // Disable manual reordering this column, this will also prevent other columns from crossing over this column.
+ ImGuiTableColumnFlags_NoHide = 1 << 6, // Disable ability to hide/disable this column.
+ ImGuiTableColumnFlags_NoClip = 1 << 7, // Disable clipping for this column (all NoClip columns will render in a same draw command).
+ ImGuiTableColumnFlags_NoSort = 1 << 8, // Disable ability to sort on this field (even if ImGuiTableFlags_Sortable is set on the table).
+ ImGuiTableColumnFlags_NoSortAscending = 1 << 9, // Disable ability to sort in the ascending direction.
+ ImGuiTableColumnFlags_NoSortDescending = 1 << 10, // Disable ability to sort in the descending direction.
+ ImGuiTableColumnFlags_NoHeaderWidth = 1 << 11, // Disable header text width contribution to automatic column width.
+ ImGuiTableColumnFlags_PreferSortAscending = 1 << 12, // Make the initial sort direction Ascending when first sorting on this column (default).
+ ImGuiTableColumnFlags_PreferSortDescending = 1 << 13, // Make the initial sort direction Descending when first sorting on this column.
+ ImGuiTableColumnFlags_IndentEnable = 1 << 14, // Use current Indent value when entering cell (default for column 0).
+ ImGuiTableColumnFlags_IndentDisable = 1 << 15, // Ignore current Indent value when entering cell (default for columns > 0). Indentation changes _within_ the cell will still be honored.
+
+ // Output status flags, read-only via TableGetColumnFlags()
+ ImGuiTableColumnFlags_IsEnabled = 1 << 20, // Status: is enabled == not hidden by user/api (referred to as "Hide" in _DefaultHide and _NoHide) flags.
+ ImGuiTableColumnFlags_IsVisible = 1 << 21, // Status: is visible == is enabled AND not clipped by scrolling.
+ ImGuiTableColumnFlags_IsSorted = 1 << 22, // Status: is currently part of the sort specs
+ ImGuiTableColumnFlags_IsHovered = 1 << 23, // Status: is hovered by mouse
+
+ // [Internal] Combinations and masks
+ ImGuiTableColumnFlags_WidthMask_ = ImGuiTableColumnFlags_WidthStretch | ImGuiTableColumnFlags_WidthFixed,
+ ImGuiTableColumnFlags_IndentMask_ = ImGuiTableColumnFlags_IndentEnable | ImGuiTableColumnFlags_IndentDisable,
+ ImGuiTableColumnFlags_StatusMask_ = ImGuiTableColumnFlags_IsEnabled | ImGuiTableColumnFlags_IsVisible | ImGuiTableColumnFlags_IsSorted | ImGuiTableColumnFlags_IsHovered,
+ ImGuiTableColumnFlags_NoDirectResize_ = 1 << 30 // [Internal] Disable user resizing this column directly (it may however we resized indirectly from its left edge)
+
+ // Obsolete names (will be removed soon)
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ //ImGuiTableColumnFlags_WidthAuto = ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_NoResize, // Column will not stretch and keep resizing based on submitted contents.
+#endif
+};
+
+// Flags for ImGui::TableNextRow()
+enum ImGuiTableRowFlags_
+{
+ ImGuiTableRowFlags_None = 0,
+ ImGuiTableRowFlags_Headers = 1 << 0 // Identify header row (set default background color + width of its contents accounted different for auto column width)
+};
+
+// Enum for ImGui::TableSetBgColor()
+// Background colors are rendering in 3 layers:
+// - Layer 0: draw with RowBg0 color if set, otherwise draw with ColumnBg0 if set.
+// - Layer 1: draw with RowBg1 color if set, otherwise draw with ColumnBg1 if set.
+// - Layer 2: draw with CellBg color if set.
+// The purpose of the two row/columns layers is to let you decide if a background color changes should override or blend with the existing color.
+// When using ImGuiTableFlags_RowBg on the table, each row has the RowBg0 color automatically set for odd/even rows.
+// If you set the color of RowBg0 target, your color will override the existing RowBg0 color.
+// If you set the color of RowBg1 or ColumnBg1 target, your color will blend over the RowBg0 color.
+enum ImGuiTableBgTarget_
+{
+ ImGuiTableBgTarget_None = 0,
+ ImGuiTableBgTarget_RowBg0 = 1, // Set row background color 0 (generally used for background, automatically set when ImGuiTableFlags_RowBg is used)
+ ImGuiTableBgTarget_RowBg1 = 2, // Set row background color 1 (generally used for selection marking)
+ ImGuiTableBgTarget_CellBg = 3 // Set cell background color (top-most color)
};
// Flags for ImGui::IsWindowFocused()
@@ -908,12 +1184,12 @@ enum ImGuiFocusedFlags_
ImGuiFocusedFlags_None = 0,
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. Important: If you are trying to tell how to dispatch your low-level inputs, do NOT use this. Use ImGui::GetIO().WantCaptureMouse instead.
+ ImGuiFocusedFlags_AnyWindow = 1 << 2, // IsWindowFocused(): Return true if any window is focused. Important: If you are trying to tell how to dispatch your low-level inputs, do NOT use this. Use 'io.WantCaptureMouse' instead! Please read the FAQ!
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!
+// Note: if you are trying to check whether your mouse should be dispatched to Dear ImGui or to your app, you should use 'io.WantCaptureMouse' instead! Please read the FAQ!
// Note: windows with the ImGuiWindowFlags_NoInputs flag are ignored by IsWindowHovered() calls.
enum ImGuiHoveredFlags_
{
@@ -930,21 +1206,6 @@ enum ImGuiHoveredFlags_
ImGuiHoveredFlags_RootAndChildWindows = ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows
};
-// Flags for ImGui::DockSpace(), shared/inherited by child nodes.
-// (Some flags can be applied to individual nodes directly)
-// FIXME-DOCK: Also see ImGuiDockNodeFlagsPrivate_ which may involve using the WIP and internal DockBuilder api.
-enum ImGuiDockNodeFlags_
-{
- ImGuiDockNodeFlags_None = 0,
- ImGuiDockNodeFlags_KeepAliveOnly = 1 << 0, // Shared // Don't display the dockspace node but keep it alive. Windows docked into this dockspace node won't be undocked.
- //ImGuiDockNodeFlags_NoCentralNode = 1 << 1, // Shared // Disable Central Node (the node which can stay empty)
- ImGuiDockNodeFlags_NoDockingInCentralNode = 1 << 2, // Shared // Disable docking inside the Central Node, which will be always kept empty.
- ImGuiDockNodeFlags_PassthruCentralNode = 1 << 3, // Shared // Enable passthru dockspace: 1) DockSpace() will render a ImGuiCol_WindowBg background covering everything excepted the Central Node when empty. Meaning the host window should probably use SetNextWindowBgAlpha(0.0f) prior to Begin() when using this. 2) When Central Node is empty: let inputs pass-through + won't display a DockingEmptyBg background. See demo for details.
- ImGuiDockNodeFlags_NoSplit = 1 << 4, // Shared/Local // Disable splitting the node into smaller nodes. Useful e.g. when embedding dockspaces into a main root one (the root one may have splitting disabled to reduce confusion). Note: when turned off, existing splits will be preserved.
- ImGuiDockNodeFlags_NoResize = 1 << 5, // Shared/Local // Disable resizing node using the splitter/separators. Useful with programatically setup dockspaces.
- ImGuiDockNodeFlags_AutoHideTabBar = 1 << 6 // Shared/Local // Tab bar will automatically hide when there is a single window in the dock node.
-};
-
// Flags for ImGui::BeginDragDropSource(), ImGui::AcceptDragDropPayload()
enum ImGuiDragDropFlags_
{
@@ -994,6 +1255,14 @@ enum ImGuiDir_
ImGuiDir_COUNT
};
+// A sorting direction
+enum ImGuiSortDirection_
+{
+ ImGuiSortDirection_None = 0,
+ ImGuiSortDirection_Ascending = 1, // Ascending = 0->9, A->Z etc.
+ ImGuiSortDirection_Descending = 2 // Descending = 9->0, Z->A etc.
+};
+
// User fill ImGuiIO.KeyMap[] array with indices into the ImGuiIO.KeysDown[512] array
enum ImGuiKey_
{
@@ -1022,10 +1291,20 @@ enum ImGuiKey_
ImGuiKey_COUNT
};
-// Gamepad/Keyboard directional navigation
+// To test io.KeyMods (which is a combination of individual fields io.KeyCtrl, io.KeyShift, io.KeyAlt set by user/backend)
+enum ImGuiKeyModFlags_
+{
+ ImGuiKeyModFlags_None = 0,
+ ImGuiKeyModFlags_Ctrl = 1 << 0,
+ ImGuiKeyModFlags_Shift = 1 << 1,
+ ImGuiKeyModFlags_Alt = 1 << 2,
+ ImGuiKeyModFlags_Super = 1 << 3
+};
+
+// Gamepad/Keyboard navigation
// Keyboard: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable. NewFrame() will automatically fill io.NavInputs[] based on your io.KeysDown[] + 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 http://goo.gl/9LgVZW.
+// Gamepad: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable. Backend: 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 http://dearimgui.org/controls_sheets.
enum ImGuiNavInput_
{
// Gamepad Mapping
@@ -1062,39 +1341,25 @@ enum ImGuiConfigFlags_
{
ImGuiConfigFlags_None = 0,
ImGuiConfigFlags_NavEnableKeyboard = 1 << 0, // Master keyboard navigation enable flag. NewFrame() will automatically fill io.NavInputs[] based on io.KeysDown[].
- 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_NavEnableGamepad = 1 << 1, // Master gamepad navigation enable flag. This is mostly to instruct your imgui backend to fill io.NavInputs[]. Backend 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 backend, 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 when io.NavActive is set.
- ImGuiConfigFlags_NoMouse = 1 << 4, // Instruct imgui to clear mouse position/buttons in NewFrame(). This allows ignoring the mouse information set by the back-end.
- ImGuiConfigFlags_NoMouseCursorChange = 1 << 5, // Instruct back-end to not alter mouse cursor shape and visibility. Use if the back-end cursor changes are interfering with yours and you don't want to use SetMouseCursor() to change mouse cursor. You may want to honor requests from imgui by reading GetMouseCursor() yourself instead.
+ ImGuiConfigFlags_NoMouse = 1 << 4, // Instruct imgui to clear mouse position/buttons in NewFrame(). This allows ignoring the mouse information set by the backend.
+ ImGuiConfigFlags_NoMouseCursorChange = 1 << 5, // Instruct backend to not alter mouse cursor shape and visibility. Use if the backend cursor changes are interfering with yours and you don't want to use SetMouseCursor() to change mouse cursor. You may want to honor requests from imgui by reading GetMouseCursor() yourself instead.
- // [BETA] Docking
- ImGuiConfigFlags_DockingEnable = 1 << 6, // Docking enable flags.
-
- // [BETA] Viewports
- // When using viewports it is recommended that your default value for ImGuiCol_WindowBg is opaque (Alpha=1.0) so transition to a viewport won't be noticeable.
- ImGuiConfigFlags_ViewportsEnable = 1 << 10, // Viewport enable flags (require both ImGuiConfigFlags_PlatformHasViewports + ImGuiConfigFlags_RendererHasViewports set by the respective back-ends)
- ImGuiConfigFlags_DpiEnableScaleViewports= 1 << 14, // [BETA: Don't use] FIXME-DPI: Reposition and resize imgui windows when the DpiScale of a viewport changed (mostly useful for the main viewport hosting other window). Note that resizing the main window itself is up to your application.
- ImGuiConfigFlags_DpiEnableScaleFonts = 1 << 15, // [BETA: Don't use] FIXME-DPI: Request bitmap-scaled fonts to match DpiScale. This is a very low-quality workaround. The correct way to handle DPI is _currently_ to replace the atlas and/or fonts in the Platform_OnChangedViewport callback, but this is all early work in progress.
-
- // 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 Dear ImGui)
+ // User storage (to allow your backend/engine to communicate to code that may be shared between multiple projects. Those flags are not used by core Dear 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.
+// Backend capabilities flags stored in io.BackendFlags. Set by imgui_impl_xxx or custom backend.
enum ImGuiBackendFlags_
{
ImGuiBackendFlags_None = 0,
- ImGuiBackendFlags_HasGamepad = 1 << 0, // Back-end Platform supports gamepad and currently has one connected.
- ImGuiBackendFlags_HasMouseCursors = 1 << 1, // Back-end Platform supports honoring GetMouseCursor() value to change the OS cursor shape.
- ImGuiBackendFlags_HasSetMousePos = 1 << 2, // Back-end Platform supports io.WantSetMousePos requests to reposition the OS mouse position (only used if ImGuiConfigFlags_NavEnableSetMousePos is set).
- ImGuiBackendFlags_RendererHasVtxOffset = 1 << 3, // Back-end Renderer supports ImDrawCmd::VtxOffset. This enables output of large meshes (64K+ vertices) while still using 16-bits indices.
-
- // [BETA] Viewports
- ImGuiBackendFlags_PlatformHasViewports = 1 << 10, // Back-end Platform supports multiple viewports.
- ImGuiBackendFlags_HasMouseHoveredViewport=1 << 11, // Back-end Platform supports setting io.MouseHoveredViewport to the viewport directly under the mouse _IGNORING_ viewports with the ImGuiViewportFlags_NoInputs flag and _REGARDLESS_ of whether another viewport is focused and may be capturing the mouse. This information is _NOT EASY_ to provide correctly with most high-level engines! Don't set this without studying how the examples/ back-end handle it!
- ImGuiBackendFlags_RendererHasViewports = 1 << 12 // Back-end Renderer supports multiple viewports.
+ ImGuiBackendFlags_HasGamepad = 1 << 0, // Backend Platform supports gamepad and currently has one connected.
+ ImGuiBackendFlags_HasMouseCursors = 1 << 1, // Backend Platform supports honoring GetMouseCursor() value to change the OS cursor shape.
+ ImGuiBackendFlags_HasSetMousePos = 1 << 2, // Backend Platform supports io.WantSetMousePos requests to reposition the OS mouse position (only used if ImGuiConfigFlags_NavEnableSetMousePos is set).
+ ImGuiBackendFlags_RendererHasVtxOffset = 1 << 3 // Backend Renderer supports ImDrawCmd::VtxOffset. This enables output of large meshes (64K+ vertices) while still using 16-bit indices.
};
// Enumeration for PushStyleColor() / PopStyleColor()
@@ -1138,12 +1403,15 @@ enum ImGuiCol_
ImGuiCol_TabActive,
ImGuiCol_TabUnfocused,
ImGuiCol_TabUnfocusedActive,
- ImGuiCol_DockingPreview,
- ImGuiCol_DockingEmptyBg, // Background color for empty node (e.g. CentralNode with no window docked into it)
ImGuiCol_PlotLines,
ImGuiCol_PlotLinesHovered,
ImGuiCol_PlotHistogram,
ImGuiCol_PlotHistogramHovered,
+ ImGuiCol_TableHeaderBg, // Table header background
+ ImGuiCol_TableBorderStrong, // Table outer and header borders (prefer using Alpha=1.0 here)
+ ImGuiCol_TableBorderLight, // Table inner borders (prefer using Alpha=1.0 here)
+ ImGuiCol_TableRowBg, // Table row background (even rows)
+ ImGuiCol_TableRowBgAlt, // Table row background (odd rows)
ImGuiCol_TextSelectedBg,
ImGuiCol_DragDropTarget,
ImGuiCol_NavHighlight, // Gamepad/keyboard: current highlighted item
@@ -1151,19 +1419,15 @@ enum ImGuiCol_
ImGuiCol_NavWindowingDimBg, // Darken/colorize entire screen behind the CTRL+TAB window list, when active
ImGuiCol_ModalWindowDimBg, // Darken/colorize entire screen behind a modal window, when one is active
ImGuiCol_COUNT
-
- // Obsolete names (will be removed)
-#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
- , ImGuiCol_ModalWindowDarkening = ImGuiCol_ModalWindowDimBg // [renamed in 1.63]
- , ImGuiCol_ChildWindowBg = ImGuiCol_ChildBg // [renamed in 1.53]
- //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
};
// Enumeration for PushStyleVar() / PopStyleVar() to temporarily modify the ImGuiStyle structure.
-// NB: the enum only refers to fields of ImGuiStyle which makes sense to be pushed/popped inside UI code. During initialization, feel free to just poke into ImGuiStyle directly.
-// NB: if changing this enum, you need to update the associated internal table GStyleVarInfo[] accordingly. This is where we link enum values to members offset/type.
+// - The enum only refers to fields of ImGuiStyle which makes sense to be pushed/popped inside UI code.
+// During initialization or between frames, feel free to just poke into ImGuiStyle directly.
+// - Tip: Use your programming IDE navigation facilities on the names in the _second column_ below to find the actual members and their description.
+// In Visual Studio IDE: CTRL+comma ("Edit.NavigateTo") can follow symbols in comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot.
+// With Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols in comments.
+// - When changing this enum, you need to update the associated internal table GStyleVarInfo[] accordingly. This is where we link enum values to members offset/type.
enum ImGuiStyleVar_
{
// Enum name --------------------- // Member in ImGuiStyle structure (see ImGuiStyle for descriptions)
@@ -1183,6 +1447,7 @@ enum ImGuiStyleVar_
ImGuiStyleVar_ItemSpacing, // ImVec2 ItemSpacing
ImGuiStyleVar_ItemInnerSpacing, // ImVec2 ItemInnerSpacing
ImGuiStyleVar_IndentSpacing, // float IndentSpacing
+ ImGuiStyleVar_CellPadding, // ImVec2 CellPadding
ImGuiStyleVar_ScrollbarSize, // float ScrollbarSize
ImGuiStyleVar_ScrollbarRounding, // float ScrollbarRounding
ImGuiStyleVar_GrabMinSize, // float GrabMinSize
@@ -1191,12 +1456,19 @@ enum ImGuiStyleVar_
ImGuiStyleVar_ButtonTextAlign, // ImVec2 ButtonTextAlign
ImGuiStyleVar_SelectableTextAlign, // ImVec2 SelectableTextAlign
ImGuiStyleVar_COUNT
+};
- // Obsolete names (will be removed)
-#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
- , ImGuiStyleVar_Count_ = ImGuiStyleVar_COUNT // [renamed in 1.60]
- , ImGuiStyleVar_ChildWindowRounding = ImGuiStyleVar_ChildRounding // [renamed in 1.53]
-#endif
+// Flags for InvisibleButton() [extended in imgui_internal.h]
+enum ImGuiButtonFlags_
+{
+ ImGuiButtonFlags_None = 0,
+ ImGuiButtonFlags_MouseButtonLeft = 1 << 0, // React on left mouse button (default)
+ ImGuiButtonFlags_MouseButtonRight = 1 << 1, // React on right mouse button
+ ImGuiButtonFlags_MouseButtonMiddle = 1 << 2, // React on center mouse button
+
+ // [Internal]
+ ImGuiButtonFlags_MouseButtonMask_ = ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonRight | ImGuiButtonFlags_MouseButtonMiddle,
+ ImGuiButtonFlags_MouseButtonDefault_ = ImGuiButtonFlags_MouseButtonLeft
};
// Flags for ColorEdit3() / ColorEdit4() / ColorPicker3() / ColorPicker4() / ColorButton()
@@ -1204,14 +1476,15 @@ enum ImGuiColorEditFlags_
{
ImGuiColorEditFlags_None = 0,
ImGuiColorEditFlags_NoAlpha = 1 << 1, // // ColorEdit, ColorPicker, ColorButton: ignore Alpha component (will only read 3 components from the input pointer).
- ImGuiColorEditFlags_NoPicker = 1 << 2, // // ColorEdit: disable picker when clicking on colored square.
+ ImGuiColorEditFlags_NoPicker = 1 << 2, // // ColorEdit: disable picker when clicking on color square.
ImGuiColorEditFlags_NoOptions = 1 << 3, // // ColorEdit: disable toggling options menu when right-clicking on inputs/small preview.
- ImGuiColorEditFlags_NoSmallPreview = 1 << 4, // // ColorEdit, ColorPicker: disable colored square preview next to the inputs. (e.g. to show only the inputs)
- ImGuiColorEditFlags_NoInputs = 1 << 5, // // ColorEdit, ColorPicker: disable inputs sliders/text widgets (e.g. to show only the small preview colored square).
+ ImGuiColorEditFlags_NoSmallPreview = 1 << 4, // // ColorEdit, ColorPicker: disable color square preview next to the inputs. (e.g. to show only the inputs)
+ ImGuiColorEditFlags_NoInputs = 1 << 5, // // ColorEdit, ColorPicker: disable inputs sliders/text widgets (e.g. to show only the small preview color square).
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.
+ ImGuiColorEditFlags_NoSidePreview = 1 << 8, // // ColorPicker: disable bigger color preview on right side of the picker, use small color square preview instead.
ImGuiColorEditFlags_NoDragDrop = 1 << 9, // // ColorEdit: disable drag and drop target. ColorButton: disable drag and drop source.
+ ImGuiColorEditFlags_NoBorder = 1 << 10, // // ColorButton: disable border (which is enforced by default)
// User Options (right-click on widget to change some of them).
ImGuiColorEditFlags_AlphaBar = 1 << 16, // // ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker.
@@ -1230,13 +1503,13 @@ enum ImGuiColorEditFlags_
// Defaults Options. You can set application defaults using SetColorEditOptions(). The intent is that you probably don't want to
// override them in most of your calls. Let the user choose via the option menu and/or call SetColorEditOptions() once during startup.
- ImGuiColorEditFlags__OptionsDefault = ImGuiColorEditFlags_Uint8|ImGuiColorEditFlags_DisplayRGB|ImGuiColorEditFlags_InputRGB|ImGuiColorEditFlags_PickerHueBar,
+ ImGuiColorEditFlags__OptionsDefault = ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_PickerHueBar,
// [Internal] Masks
- ImGuiColorEditFlags__DisplayMask = ImGuiColorEditFlags_DisplayRGB|ImGuiColorEditFlags_DisplayHSV|ImGuiColorEditFlags_DisplayHex,
- ImGuiColorEditFlags__DataTypeMask = ImGuiColorEditFlags_Uint8|ImGuiColorEditFlags_Float,
- ImGuiColorEditFlags__PickerMask = ImGuiColorEditFlags_PickerHueWheel|ImGuiColorEditFlags_PickerHueBar,
- ImGuiColorEditFlags__InputMask = ImGuiColorEditFlags_InputRGB|ImGuiColorEditFlags_InputHSV
+ ImGuiColorEditFlags__DisplayMask = ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_DisplayHex,
+ ImGuiColorEditFlags__DataTypeMask = ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_Float,
+ ImGuiColorEditFlags__PickerMask = ImGuiColorEditFlags_PickerHueWheel | ImGuiColorEditFlags_PickerHueBar,
+ ImGuiColorEditFlags__InputMask = ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_InputHSV
// Obsolete names (will be removed)
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
@@ -1244,8 +1517,35 @@ enum ImGuiColorEditFlags_
#endif
};
+// Flags for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc.
+// We use the same sets of flags for DragXXX() and SliderXXX() functions as the features are the same and it makes it easier to swap them.
+enum ImGuiSliderFlags_
+{
+ ImGuiSliderFlags_None = 0,
+ ImGuiSliderFlags_AlwaysClamp = 1 << 4, // Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds.
+ ImGuiSliderFlags_Logarithmic = 1 << 5, // Make the widget logarithmic (linear otherwise). Consider using ImGuiSliderFlags_NoRoundToFormat with this if using a format-string with small amount of digits.
+ ImGuiSliderFlags_NoRoundToFormat = 1 << 6, // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits)
+ ImGuiSliderFlags_NoInput = 1 << 7, // Disable CTRL+Click or Enter key allowing to input text directly into the widget
+ ImGuiSliderFlags_InvalidMask_ = 0x7000000F // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed.
+
+ // Obsolete names (will be removed)
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ , ImGuiSliderFlags_ClampOnInput = ImGuiSliderFlags_AlwaysClamp // [renamed in 1.79]
+#endif
+};
+
+// Identify a mouse button.
+// Those values are guaranteed to be stable and we frequently use 0/1 directly. Named enums provided for convenience.
+enum ImGuiMouseButton_
+{
+ ImGuiMouseButton_Left = 0,
+ ImGuiMouseButton_Right = 1,
+ ImGuiMouseButton_Middle = 2,
+ ImGuiMouseButton_COUNT = 5
+};
+
// 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
+// User code may request backend to display given cursor by calling SetMouseCursor(), which is why we have some cursors that are marked unused here
enum ImGuiMouseCursor_
{
ImGuiMouseCursor_None = -1,
@@ -1257,48 +1557,50 @@ enum ImGuiMouseCursor_
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_Hand, // (Unused by Dear ImGui functions. Use for e.g. hyperlinks)
+ ImGuiMouseCursor_NotAllowed, // When hovering something with disallowed interaction. Usually a crossed circle.
ImGuiMouseCursor_COUNT
-
- // Obsolete names (will be removed)
-#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
- , ImGuiMouseCursor_Count_ = ImGuiMouseCursor_COUNT // [renamed in 1.60]
-#endif
};
-// Enumateration for ImGui::SetWindow***(), SetNextWindow***(), SetNextItem***() functions
+// Enumeration for ImGui::SetWindow***(), SetNextWindow***(), SetNextItem***() functions
// Represent a condition.
// 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_None = 0, // No condition (always set the variable), same as _Always
+ ImGuiCond_Always = 1 << 0, // No condition (always set the variable)
+ ImGuiCond_Once = 1 << 1, // Set the variable once per runtime session (only the first call will succeed)
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)
};
//-----------------------------------------------------------------------------
-// Helpers: Memory allocations macros
-// IM_MALLOC(), IM_FREE(), IM_NEW(), IM_PLACEMENT_NEW(), IM_DELETE()
-// 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 which on some platforms complains when user has disabled exceptions.
+// [SECTION] Helpers: Memory allocations macros, ImVector<>
//-----------------------------------------------------------------------------
-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 symmetrical new()
+//-----------------------------------------------------------------------------
+// IM_MALLOC(), IM_FREE(), IM_NEW(), IM_PLACEMENT_NEW(), IM_DELETE()
+// We call C++ constructor on own allocated memory via the placement "new(ptr) Type()" syntax.
+// Defining a custom placement new() with a custom parameter allows us to bypass including which on some platforms complains when user has disabled exceptions.
+//-----------------------------------------------------------------------------
+
+struct ImNewWrapper {};
+inline void* operator new(size_t, ImNewWrapper, void* ptr) { return ptr; }
+inline void operator delete(void*, ImNewWrapper, void*) {} // This is only required so we can use the symmetrical new()
#define IM_ALLOC(_SIZE) ImGui::MemAlloc(_SIZE)
#define IM_FREE(_PTR) ImGui::MemFree(_PTR)
-#define IM_PLACEMENT_NEW(_PTR) new(ImNewDummy(), _PTR)
-#define IM_NEW(_TYPE) new(ImNewDummy(), ImGui::MemAlloc(sizeof(_TYPE))) _TYPE
+#define IM_PLACEMENT_NEW(_PTR) new(ImNewWrapper(), _PTR)
+#define IM_NEW(_TYPE) new(ImNewWrapper(), ImGui::MemAlloc(sizeof(_TYPE))) _TYPE
template void IM_DELETE(T* p) { if (p) { p->~T(); ImGui::MemFree(p); } }
//-----------------------------------------------------------------------------
-// Helper: ImVector<>
+// ImVector<>
// Lightweight std::vector<>-like class to avoid dragging dependencies (also, some implementations of STL with debug enabled are absurdly slow, we bypass it so our code runs fast in debug).
-// You generally do NOT need to care or use this ever. But we need to make it available in imgui.h because some of our data structures are relying on it.
-// Important: clear() frees memory, resize(0) keep the allocated buffer. We use resize(0) a lot to intentionally recycle allocated buffers across frames and amortize our costs.
-// Important: our implementation does NOT call C++ constructors/destructors, we treat everything as raw data! This is intentional but be extra mindful of that,
-// do NOT use this class as a std::vector replacement in your own code! Many of the structures used by dear imgui can be safely initialized by a zero-memset.
+//-----------------------------------------------------------------------------
+// - You generally do NOT need to care or use this ever. But we need to make it available in imgui.h because some of our public structures are relying on it.
+// - We use std-like naming convention here, which is a little unusual for this codebase.
+// - Important: clear() frees memory, resize(0) keep the allocated buffer. We use resize(0) a lot to intentionally recycle allocated buffers across frames and amortize our costs.
+// - Important: our implementation does NOT call C++ constructors/destructors, we treat everything as raw data! This is intentional but be extra mindful of that,
+// Do NOT use this class as a std::vector replacement in your own code! Many of the structures used by dear imgui can be safely initialized by a zero-memset.
//-----------------------------------------------------------------------------
template
@@ -1322,9 +1624,10 @@ struct ImVector
inline bool empty() const { return Size == 0; }
inline int size() const { return Size; }
inline int size_in_bytes() const { return Size * (int)sizeof(T); }
+ inline int max_size() const { return 0x7FFFFFFF / (int)sizeof(T); }
inline int capacity() const { return Capacity; }
- inline T& operator[](int i) { IM_ASSERT(i < Size); return Data[i]; }
- inline const T& operator[](int i) const { IM_ASSERT(i < Size); return Data[i]; }
+ inline T& operator[](int i) { IM_ASSERT(i >= 0 && i < Size); return Data[i]; }
+ inline const T& operator[](int i) const { IM_ASSERT(i >= 0 && i < Size); return Data[i]; }
inline void clear() { if (Data) { Size = Capacity = 0; IM_FREE(Data); Data = NULL; } }
inline T* begin() { return Data; }
@@ -1337,19 +1640,20 @@ struct ImVector
inline const T& back() const { IM_ASSERT(Size > 0); return Data[Size - 1]; }
inline void swap(ImVector& rhs) { int rhs_size = rhs.Size; rhs.Size = Size; Size = rhs_size; int rhs_cap = rhs.Capacity; rhs.Capacity = Capacity; Capacity = rhs_cap; T* rhs_data = rhs.Data; rhs.Data = Data; Data = rhs_data; }
- inline int _grow_capacity(int sz) const { int new_capacity = Capacity ? (Capacity + Capacity/2) : 8; return new_capacity > sz ? new_capacity : sz; }
+ 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 T& 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 shrink(int new_size) { IM_ASSERT(new_size <= Size); Size = new_size; } // Resize a vector to a smaller size, guaranteed not to cause a reallocation
inline void reserve(int new_capacity) { if (new_capacity <= Capacity) return; T* new_data = (T*)IM_ALLOC((size_t)new_capacity * sizeof(T)); if (Data) { memcpy(new_data, Data, (size_t)Size * sizeof(T)); IM_FREE(Data); } Data = new_data; Capacity = new_capacity; }
// NB: It is illegal to call push_back/push_front/insert with a reference pointing inside the ImVector data itself! e.g. v.push_back(v[10]) is forbidden.
inline void push_back(const T& 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 T& v) { if (Size == 0) push_back(v); else insert(Data, v); }
- inline T* erase(const T* 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(T)); Size--; return Data + off; }
- inline T* erase(const T* it, const T* it_last){ IM_ASSERT(it >= Data && it < Data+Size && it_last > it && it_last <= Data+Size); const ptrdiff_t count = it_last - it; const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + count, ((size_t)Size - (size_t)off - count) * sizeof(T)); Size -= (int)count; return Data + off; }
- inline T* erase_unsorted(const T* it) { IM_ASSERT(it >= Data && it < Data+Size); const ptrdiff_t off = it - Data; if (it < Data+Size-1) memcpy(Data + off, Data + Size - 1, sizeof(T)); Size--; return Data + off; }
- inline T* insert(const T* it, const T& 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(T)); memcpy(&Data[off], &v, sizeof(v)); Size++; return Data + off; }
+ inline T* erase(const T* 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(T)); Size--; return Data + off; }
+ inline T* erase(const T* it, const T* it_last){ IM_ASSERT(it >= Data && it < Data + Size && it_last > it && it_last <= Data + Size); const ptrdiff_t count = it_last - it; const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + count, ((size_t)Size - (size_t)off - count) * sizeof(T)); Size -= (int)count; return Data + off; }
+ inline T* erase_unsorted(const T* it) { IM_ASSERT(it >= Data && it < Data + Size); const ptrdiff_t off = it - Data; if (it < Data + Size - 1) memcpy(Data + off, Data + Size - 1, sizeof(T)); Size--; return Data + off; }
+ inline T* insert(const T* it, const T& 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(T)); memcpy(&Data[off], &v, sizeof(v)); Size++; return Data + off; }
inline bool contains(const T& v) const { const T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data++ == v) return true; return false; }
inline T* find(const T& v) { T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data == v) break; else ++data; return data; }
inline const T* find(const T& v) const { const T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data == v) break; else ++data; return data; }
@@ -1359,7 +1663,8 @@ struct ImVector
};
//-----------------------------------------------------------------------------
-// ImGuiStyle
+// [SECTION] ImGuiStyle
+//-----------------------------------------------------------------------------
// 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.
@@ -1369,7 +1674,7 @@ struct ImGuiStyle
{
float Alpha; // Global alpha applies to everything in Dear ImGui.
ImVec2 WindowPadding; // Padding within a window.
- float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows.
+ float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
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.
@@ -1383,6 +1688,7 @@ struct ImGuiStyle
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 CellPadding; // Padding within a table cell
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. Preferably > (FramePadding.x + 1).
@@ -1390,17 +1696,21 @@ struct ImGuiStyle
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.
+ float LogSliderDeadzone; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
float TabRounding; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
float TabBorderSize; // Thickness of border around tabs.
+ float TabMinWidthForCloseButton; // Minimum width for close button to appears on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
ImGuiDir ColorButtonPosition; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f, 0.5f) (centered).
- ImVec2 SelectableTextAlign; // Alignment of selectable text when selectable is larger than text. Defaults to (0.0f, 0.0f) (top-left aligned).
+ ImVec2 SelectableTextAlign; // Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
ImVec2 DisplayWindowPadding; // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
ImVec2 DisplaySafeAreaPadding; // If you cannot see the edges of your screen (e.g. on a TV) increase the safe area padding. Apply to popups/tooltips as well regular windows. NB: Prefer configuring your TV sets correctly!
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.)
+ bool AntiAliasedLines; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList).
+ bool AntiAliasedLinesUseTex; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering. Latched at the beginning of the frame (copied to ImDrawList).
+ bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList).
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.
+ float CircleSegmentMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
ImVec4 Colors[ImGuiCol_COUNT];
IMGUI_API ImGuiStyle();
@@ -1408,7 +1718,8 @@ struct ImGuiStyle
};
//-----------------------------------------------------------------------------
-// ImGuiIO
+// [SECTION] ImGuiIO
+//-----------------------------------------------------------------------------
// Communicate most settings and inputs/outputs to Dear ImGui using this structure.
// Access via ImGui::GetIO(). Read 'Programmer guide' section in .cpp file for general usage.
//-----------------------------------------------------------------------------
@@ -1420,8 +1731,8 @@ struct ImGuiIO
//------------------------------------------------------------------
ImGuiConfigFlags ConfigFlags; // = 0 // See ImGuiConfigFlags_ enum. Set by user/application. Gamepad/keyboard navigation options, etc.
- ImGuiBackendFlags BackendFlags; // = 0 // See ImGuiBackendFlags_ enum. Set by back-end (imgui_impl_xxx files or custom back-end) to communicate features supported by the back-end.
- ImVec2 DisplaySize; // // Main display size, in pixels. This is for the default viewport. Use BeginViewport() for other viewports.
+ ImGuiBackendFlags BackendFlags; // = 0 // See ImGuiBackendFlags_ enum. Set by backend (imgui_impl_xxx files or custom backend) to communicate features supported by the backend.
+ ImVec2 DisplaySize; // // Main display size, in pixels.
float DeltaTime; // = 1.0f/60.0f // Time elapsed since last frame, in seconds.
float IniSavingRate; // = 5.0f // Minimum time between saving positions/sizes to .ini file, in seconds.
const char* IniFilename; // = "imgui.ini" // Path to .ini file. Set NULL to disable automatic .ini loading/saving, if e.g. you want to manually load/save from memory.
@@ -1440,37 +1751,26 @@ struct ImGuiIO
ImFont* FontDefault; // = NULL // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0].
ImVec2 DisplayFramebufferScale; // = (1, 1) // For retina display or other situations where window coordinates are different from framebuffer coordinates. This generally ends up in ImDrawData::FramebufferScale.
- // Docking options (when ImGuiConfigFlags_DockingEnable is set)
- bool ConfigDockingNoSplit; // = false // Simplified docking mode: disable window splitting, so docking is limited to merging multiple windows together into tab-bars.
- bool ConfigDockingWithShift; // = false // Enable docking with holding Shift key (reduce visual noise, allows dropping in wider space)
- bool ConfigDockingAlwaysTabBar; // = false // [BETA] [FIXME: This currently creates regression with auto-sizing and general overhead] Make every single floating window display within a docking node.
- bool ConfigDockingTransparentPayload;// = false // [BETA] Make window or viewport transparent when docking and only display docking boxes on the target viewport. Useful if rendering of multiple viewport cannot be synced. Best used with ConfigViewportsNoAutoMerge.
-
- // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
- bool ConfigViewportsNoAutoMerge; // = false; // Set to make all floating imgui windows always create their own viewport. Otherwise, they are merged into the main host viewports when overlapping it. May also set ImGuiViewportFlags_NoAutoMerge on individual viewport.
- bool ConfigViewportsNoTaskBarIcon; // = false // Disable default OS task bar icon flag for secondary viewports. When a viewport doesn't want a task bar icon, ImGuiViewportFlags_NoTaskBarIcon will be set on it.
- bool ConfigViewportsNoDecoration; // = true // [BETA] Disable default OS window decoration flag for secondary viewports. When a viewport doesn't want window decorations, ImGuiViewportFlags_NoDecoration will be set on it. Enabling decoration can create subsequent issues at OS levels (e.g. minimum window size).
- bool ConfigViewportsNoDefaultParent; // = false // Disable default OS parenting to main viewport for secondary viewports. By default, viewports are marked with ParentViewportId = , expecting the platform back-end to setup a parent/child relationship between the OS windows (some back-end may ignore this). Set to true if you want the default to be 0, then all viewports will be top-level OS windows.
-
// Miscellaneous options
- bool MouseDrawCursor; // = false // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by back-end implementations.
- bool ConfigMacOSXBehaviors; // = defined(__APPLE__) // OS X style: Text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl (was called io.OptMacOSXBehaviors prior to 1.63)
- bool ConfigInputTextCursorBlink; // = true // Set to false to disable blinking cursor, for users who consider it distracting. (was called: io.OptCursorBlink prior to 1.63)
+ bool MouseDrawCursor; // = false // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by backend implementations.
+ bool ConfigMacOSXBehaviors; // = defined(__APPLE__) // OS X style: Text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl.
+ bool ConfigInputTextCursorBlink; // = true // Enable blinking cursor (optional as some users consider it to be distracting).
+ bool ConfigDragClickToInputText; // = false // [BETA] Enable turning DragXXX widgets into text input with a simple mouse click-release (without moving). Not desirable on devices without a keyboard.
bool ConfigWindowsResizeFromEdges; // = true // Enable resizing of windows from their edges and from the lower-left corner. This requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback. (This used to be a per-window ImGuiWindowFlags_ResizeFromAnySide flag)
- bool ConfigWindowsMoveFromTitleBarOnly; // = false // [BETA] Set to true to only allow moving windows when clicked+dragged from the title bar. Windows without a title bar are not affected.
- float ConfigWindowsMemoryCompactTimer;// = 60.0f // [BETA] Compact window memory usage when unused. Set to -1.0f to disable.
+ bool ConfigWindowsMoveFromTitleBarOnly; // = false // Enable allowing to move windows only when clicking on their title bar. Does not apply to windows without a title bar.
+ float ConfigMemoryCompactTimer; // = 60.0f // Timer (in seconds) to free transient windows/tables memory buffers when unused. Set to -1.0f to disable.
//------------------------------------------------------------------
// Platform Functions
- // (the imgui_impl_xxxx back-end files are setting those up for you)
+ // (the imgui_impl_xxxx backend files are setting those up for you)
//------------------------------------------------------------------
- // Optional: Platform/Renderer back-end name (informational only! will be displayed in About Window) + User data for back-end/wrappers to store their own stuff.
+ // Optional: Platform/Renderer backend name (informational only! will be displayed in About Window) + User data for backend/wrappers to store their own stuff.
const char* BackendPlatformName; // = NULL
const char* BackendRendererName; // = NULL
- void* BackendPlatformUserData; // = NULL
- void* BackendRendererUserData; // = NULL
- void* BackendLanguageUserData; // = NULL
+ void* BackendPlatformUserData; // = NULL // User data for platform backend
+ void* BackendRendererUserData; // = NULL // User data for renderer backend
+ void* BackendLanguageUserData; // = NULL // User data for non C++ programming language backend
// 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)
@@ -1478,24 +1778,19 @@ struct ImGuiIO
void (*SetClipboardTextFn)(void* user_data, const char* text);
void* ClipboardUserData;
-#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
- // [OBSOLETE since 1.60+] 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);
-#else
- // This is only here to keep ImGuiIO the same size/layout, so that IMGUI_DISABLE_OBSOLETE_FUNCTIONS can exceptionally be used outside of imconfig.h.
- void* RenderDrawListsFnUnused;
-#endif
+ // Optional: Notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese IME on Windows)
+ // (default to use native imm32 api on Windows)
+ void (*ImeSetInputScreenPosFn)(int x, int y);
+ void* ImeWindowHandle; // = NULL // (Windows) Set this to your HWND to get automatic IME cursor positioning.
//------------------------------------------------------------------
// 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: 0=left, 1=right, 2=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.
+ 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: 0=left, 1=right, 2=middle + extras (ImGuiMouseButton_COUNT == 5). Dear ImGui mostly uses left and right buttons. 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 Vertical: 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.
- ImGuiID MouseHoveredViewport; // (Optional) When using multiple viewports: viewport the OS mouse cursor is hovering _IGNORING_ viewports with the ImGuiViewportFlags_NoInputs flag, and _REGARDLESS_ of whether another viewport is focused. Set io.BackendFlags |= ImGuiBackendFlags_HasMouseHoveredViewport if you can provide this info. If you don't imgui will infer the value using the rectangles and last focused time of the viewports it knows about (ignoring other OS windows).
+ float MouseWheelH; // Mouse wheel Horizontal. Most users don't have a mouse with an horizontal wheel, may not be filled by all backends.
bool KeyCtrl; // Keyboard modifier pressed: Control
bool KeyShift; // Keyboard modifier pressed: Shift
bool KeyAlt; // Keyboard modifier pressed: Alt
@@ -1505,21 +1800,24 @@ struct ImGuiIO
// Functions
IMGUI_API void AddInputCharacter(unsigned int c); // Queue new character input
+ IMGUI_API void AddInputCharacterUTF16(ImWchar16 c); // Queue new character input from an UTF-16 character, it can be a surrogate
IMGUI_API void AddInputCharactersUTF8(const char* str); // Queue new characters input from an UTF-8 string
IMGUI_API void ClearInputCharacters(); // Clear the text input buffer manually
//------------------------------------------------------------------
- // Output - Retrieve after calling NewFrame()
+ // Output - Updated by NewFrame() or EndFrame()/Render()
+ // (when reading from the io.WantCaptureMouse, io.WantCaptureKeyboard flags to dispatch your inputs, it is
+ // generally easier and more correct to use their state BEFORE calling NewFrame(). See FAQ for details!)
//------------------------------------------------------------------
- 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 WantSetMousePos; // MousePos has been altered, back-end should reposition mouse on next frame. Set only when ImGuiConfigFlags_NavEnableSetMousePos flag is enabled.
- bool WantSaveIniSettings; // When manual .ini load/save is active (io.IniFilename == NULL), this will be set to notify your application that you can call SaveIniSettingsToMemory() and save yourself. IMPORTANT: You need to clear io.WantSaveIniSettings yourself.
- 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
+ bool WantCaptureMouse; // Set when Dear ImGui will use mouse inputs, in this case do not dispatch them to your main game/application (either way, 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; // Set when Dear ImGui will use keyboard inputs, in this case do not dispatch them to your main game/application (either way, 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 set, you may display an on-screen keyboard. This is set by Dear ImGui when it wants textual keyboard input to happen (e.g. when a InputText widget is active).
+ bool WantSetMousePos; // MousePos has been altered, backend should reposition mouse on next frame. Rarely used! Set only when ImGuiConfigFlags_NavEnableSetMousePos flag is enabled.
+ bool WantSaveIniSettings; // When manual .ini load/save is active (io.IniFilename == NULL), this will be set to notify your application that you can call SaveIniSettingsToMemory() and save yourself. Important: clear io.WantSaveIniSettings yourself after saving!
+ bool NavActive; // Keyboard/Gamepad navigation is currently allowed (will handle ImGuiKey_NavXXX events) = a window is focused and it doesn't use the ImGuiWindowFlags_NoNavInputs flag.
+ bool NavVisible; // Keyboard/Gamepad navigation is visible and allowed (will handle ImGuiKey_NavXXX events).
+ float Framerate; // Application framerate estimate, in frame per second. Solely for convenience. Rolling average estimation based on io.DeltaTime over 120 frames.
int MetricsRenderVertices; // Vertices output during last call to Render()
int MetricsRenderIndices; // Indices output during last call to Render() = number of triangles * 3
int MetricsRenderWindows; // Number of visible windows
@@ -1528,9 +1826,10 @@ struct ImGuiIO
ImVec2 MouseDelta; // Mouse delta. Note that this is zero if either current or previous position are invalid (-FLT_MAX,-FLT_MAX), so a disappearing/reappearing mouse won't have a huge delta.
//------------------------------------------------------------------
- // [Internal] ImGui will maintain those fields. Forward compatibility not guaranteed!
+ // [Internal] Dear ImGui will maintain those fields. Forward compatibility not guaranteed!
//------------------------------------------------------------------
+ ImGuiKeyModFlags KeyMods; // Key mods flags (same as io.KeyCtrl/KeyShift/KeyAlt/KeySuper but merged into flags), updated by NewFrame()
ImVec2 MousePosPrev; // Previous mouse position (note that MouseDelta is not necessary == MousePos-MousePosPrev, in case either position is invalid)
ImVec2 MouseClickedPos[5]; // Position at time of clicking
double MouseClickedTime[5]; // Time of last click (used to figure out double-click)
@@ -1547,21 +1846,24 @@ struct ImGuiIO
float KeysDownDurationPrev[512]; // Previous duration the key has been down
float NavInputsDownDuration[ImGuiNavInput_COUNT];
float NavInputsDownDurationPrev[ImGuiNavInput_COUNT];
- ImVector InputQueueCharacters; // Queue of _characters_ input (obtained by platform back-end). Fill using AddInputCharacter() helper.
+ float PenPressure; // Touch/Pen pressure (0.0f to 1.0f, should be >0.0f only when MouseDown[0] == true). Helper storage currently unused by Dear ImGui.
+ ImWchar16 InputQueueSurrogate; // For AddInputCharacterUTF16
+ ImVector InputQueueCharacters; // Queue of _characters_ input (obtained by platform backend). Fill using AddInputCharacter() helper.
IMGUI_API ImGuiIO();
};
//-----------------------------------------------------------------------------
-// Misc data structures
+// [SECTION] Misc data structures
//-----------------------------------------------------------------------------
// Shared state of InputText(), passed as an argument to your callback when a ImGuiInputTextFlags_Callback* flag is used.
// The callback function should return 0 by default.
// Callbacks (follow a flag name and see comments in ImGuiInputTextFlags_ declarations for more details)
+// - ImGuiInputTextFlags_CallbackEdit: Callback on buffer edit (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the underlying buffer while focus is active)
+// - ImGuiInputTextFlags_CallbackAlways: Callback on each iteration
// - ImGuiInputTextFlags_CallbackCompletion: Callback on pressing TAB
// - ImGuiInputTextFlags_CallbackHistory: Callback on pressing Up/Down arrows
-// - ImGuiInputTextFlags_CallbackAlways: Callback on each iteration
// - ImGuiInputTextFlags_CallbackCharFilter: Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard.
// - ImGuiInputTextFlags_CallbackResize: Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow.
struct ImGuiInputTextCallbackData
@@ -1588,7 +1890,9 @@ struct ImGuiInputTextCallbackData
IMGUI_API ImGuiInputTextCallbackData();
IMGUI_API void DeleteChars(int pos, int bytes_count);
IMGUI_API void InsertChars(int pos, const char* text, const char* text_end = NULL);
- bool HasSelection() const { return SelectionStart != SelectionEnd; }
+ void SelectAll() { SelectionStart = 0; SelectionEnd = BufTextLen; }
+ void ClearSelection() { SelectionStart = SelectionEnd = BufTextLen; }
+ bool HasSelection() const { return SelectionStart != SelectionEnd; }
};
// Resizing callback data to apply custom constraint. As enabled by SetNextWindowSizeConstraints(). Callback is called during the next Begin().
@@ -1601,20 +1905,6 @@ struct ImGuiSizeCallbackData
ImVec2 DesiredSize; // Read-write. Desired size, based on user's mouse position. Write to this field to restrain resizing.
};
-// [BETA] Rarely used / very advanced uses only. Use with SetNextWindowClass() and DockSpace() functions.
-// Provide hints to the platform back-end via altered viewport flags (enable/disable OS decoration, OS task bar icons, etc.) and OS level parent/child relationships.
-struct ImGuiWindowClass
-{
- ImGuiID ClassId; // User data. 0 = Default class (unclassed)
- ImGuiID ParentViewportId; // Hint for the platform back-end. If non-zero, the platform back-end can create a parent<>child relationship between the platform windows. Not conforming back-ends are free to e.g. parent every viewport to the main viewport or not.
- ImGuiViewportFlags ViewportFlagsOverrideSet; // Viewport flags to set when a window of this class owns a viewport. This allows you to enforce OS decoration or task bar icon, override the defaults on a per-window basis.
- ImGuiViewportFlags ViewportFlagsOverrideClear; // Viewport flags to clear when a window of this class owns a viewport. This allows you to enforce OS decoration or task bar icon, override the defaults on a per-window basis.
- bool DockingAlwaysTabBar; // Set to true to enforce windows of this class always having their own tab (equivalent of setting the global io.ConfigDockingAlwaysTabBar)
- bool DockingAllowUnclassed; // Set to true to allow windows of this class to be docked/merged with an unclassed window.
-
- ImGuiWindowClass() { ClassId = 0; ParentViewportId = 0; ViewportFlagsOverrideSet = ViewportFlagsOverrideClear = 0x00; DockingAlwaysTabBar = false; DockingAllowUnclassed = true; }
-};
-
// Data payload for Drag and Drop operations: AcceptDragDropPayload(), GetDragDropPayload()
struct ImGuiPayload
{
@@ -1626,7 +1916,7 @@ struct ImGuiPayload
ImGuiID SourceId; // Source item id
ImGuiID SourceParentId; // Source parent id (if available)
int DataFrameCount; // Data timestamp
- char DataType[32+1]; // Data type tag (short user-supplied string, 32 characters max)
+ 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.
@@ -1637,15 +1927,59 @@ struct ImGuiPayload
bool IsDelivery() const { return Delivery; }
};
+// Sorting specification for one column of a table (sizeof == 12 bytes)
+struct ImGuiTableColumnSortSpecs
+{
+ ImGuiID ColumnUserID; // User id of the column (if specified by a TableSetupColumn() call)
+ ImS16 ColumnIndex; // Index of the column
+ ImS16 SortOrder; // Index within parent ImGuiTableSortSpecs (always stored in order starting from 0, tables sorted on a single criteria will always have a 0 here)
+ ImGuiSortDirection SortDirection : 8; // ImGuiSortDirection_Ascending or ImGuiSortDirection_Descending (you can use this or SortSign, whichever is more convenient for your sort function)
+
+ ImGuiTableColumnSortSpecs() { memset(this, 0, sizeof(*this)); }
+};
+
+// Sorting specifications for a table (often handling sort specs for a single column, occasionally more)
+// Obtained by calling TableGetSortSpecs().
+// When 'SpecsDirty == true' you can sort your data. It will be true with sorting specs have changed since last call, or the first time.
+// Make sure to set 'SpecsDirty = false' after sorting, else you may wastefully sort your data every frame!
+struct ImGuiTableSortSpecs
+{
+ const ImGuiTableColumnSortSpecs* Specs; // Pointer to sort spec array.
+ int SpecsCount; // Sort spec count. Most often 1. May be > 1 when ImGuiTableFlags_SortMulti is enabled. May be == 0 when ImGuiTableFlags_SortTristate is enabled.
+ bool SpecsDirty; // Set to true when specs have changed since last time! Use this to sort again, then clear the flag.
+
+ ImGuiTableSortSpecs() { memset(this, 0, sizeof(*this)); }
+};
+
//-----------------------------------------------------------------------------
-// Obsolete functions (Will be removed! Read 'API BREAKING CHANGES' section in imgui.cpp for details)
+// [SECTION] Obsolete functions
+// (Will be removed! Read 'API BREAKING CHANGES' section in imgui.cpp for details)
// Please keep your copy of dear imgui up to date! Occasionally set '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in imconfig.h to stay ahead.
//-----------------------------------------------------------------------------
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
namespace ImGui
{
- // OBSOLETED in 1.72 (from July 2019)
+ // OBSOLETED in 1.79 (from August 2020)
+ static inline void OpenPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mb = 1) { OpenPopupOnItemClick(str_id, mb); } // Bool return value removed. Use IsWindowAppearing() in BeginPopup() instead. Renamed in 1.77, renamed back in 1.79. Sorry!
+ // OBSOLETED in 1.78 (from June 2020)
+ // Old drag/sliders functions that took a 'float power = 1.0' argument instead of flags.
+ // For shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
+ IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power);
+ IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power);
+ static inline bool DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, power); }
+ static inline bool DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, power); }
+ static inline bool DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, power); }
+ static inline bool DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, power); }
+ IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power);
+ IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format, float power);
+ static inline bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power) { return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, power); }
+ static inline bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power) { return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, power); }
+ static inline bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power) { return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, power); }
+ static inline bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power) { return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, power); }
+ // OBSOLETED in 1.77 (from June 2020)
+ static inline bool BeginPopupContextWindow(const char* str_id, ImGuiMouseButton mb, bool over_items) { return BeginPopupContextWindow(str_id, mb | (over_items ? 0 : ImGuiPopupFlags_NoOpenOverItems)); }
+ // OBSOLETED in 1.72 (from April 2019)
static inline void TreeAdvanceToLabelPos() { SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()); }
// OBSOLETED in 1.71 (from June 2019)
static inline void SetNextTreeNodeOpen(bool open, ImGuiCond cond = 0) { SetNextItemOpen(open, cond); }
@@ -1655,32 +1989,21 @@ namespace ImGui
static inline ImDrawList* GetOverlayDrawList() { return GetForegroundDrawList(); }
// OBSOLETED in 1.66 (from Sep 2018)
static inline void SetScrollHere(float center_ratio=0.5f){ SetScrollHereY(center_ratio); }
- // OBSOLETED in 1.63 (between Aug 2018 and Sept 2018)
- static inline bool IsItemDeactivatedAfterChange() { return IsItemDeactivatedAfterEdit(); }
- // OBSOLETED in 1.61 (between Apr 2018 and Aug 2018)
- IMGUI_API bool InputFloat(const char* label, float* v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags flags = 0); // Use the 'const char* format' version instead of 'decimal_precision'!
- IMGUI_API bool InputFloat2(const char* label, float v[2], int decimal_precision, ImGuiInputTextFlags flags = 0);
- IMGUI_API bool InputFloat3(const char* label, float v[3], int decimal_precision, ImGuiInputTextFlags flags = 0);
- IMGUI_API bool InputFloat4(const char* label, float v[4], int decimal_precision, ImGuiInputTextFlags flags = 0);
- // OBSOLETED in 1.60 (between Dec 2017 and Apr 2018)
- 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) { IM_UNUSED(on_edge); IM_UNUSED(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(); }
}
-typedef ImGuiInputTextCallback ImGuiTextEditCallback; // OBSOLETED in 1.63 (from Aug 2018): made the names consistent
-typedef ImGuiInputTextCallbackData ImGuiTextEditCallbackData;
#endif
//-----------------------------------------------------------------------------
-// Helpers
+// [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, ImColor)
//-----------------------------------------------------------------------------
+// Helper: Unicode defines
+#define IM_UNICODE_CODEPOINT_INVALID 0xFFFD // Invalid Unicode code point (standard value).
+#ifdef IMGUI_USE_WCHAR32
+#define IM_UNICODE_CODEPOINT_MAX 0x10FFFF // Maximum Unicode code point supported by this build.
+#else
+#define IM_UNICODE_CODEPOINT_MAX 0xFFFF // Maximum Unicode code point supported by this build.
+#endif
+
// 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
@@ -1724,11 +2047,11 @@ struct ImGuiTextBuffer
IMGUI_API static char EmptyString[1];
ImGuiTextBuffer() { }
- inline char operator[](int i) { IM_ASSERT(Buf.Data != NULL); return Buf.Data[i]; }
+ inline char operator[](int i) const { IM_ASSERT(Buf.Data != NULL); return Buf.Data[i]; }
const char* begin() const { return Buf.Data ? &Buf.front() : EmptyString; }
const char* end() const { return Buf.Data ? &Buf.back() : EmptyString; } // Buf is zero-terminated, so end() will point on the zero-terminator
int size() const { return Buf.Size ? Buf.Size - 1 : 0; }
- bool empty() { return Buf.Size <= 1; }
+ bool empty() const { return Buf.Size <= 1; }
void clear() { Buf.clear(); }
void reserve(int capacity) { Buf.reserve(capacity); }
const char* c_str() const { return Buf.Data ? Buf.Data : EmptyString; }
@@ -1789,36 +2112,49 @@ struct ImGuiStorage
};
// Helper: Manually clip large list of items.
-// If you are submitting lots of evenly spaced items and you have a random access to the list, you can perform coarse clipping based on visibility to save yourself from processing those items at all.
+// If you are submitting lots of evenly spaced items and you have a random access to the list, you can perform coarse
+// clipping based on visibility to save yourself from processing those items at all.
// The clipper calculates the range of visible items and advance the cursor to compensate for the non-visible items we have skipped.
-// ImGui already clip items based on their bounds but it needs to measure text size to do so. Coarse clipping before submission makes this cost and your own data fetching/submission cost null.
+// (Dear ImGui already clip items based on their bounds but it needs to measure text size to do so, whereas manual coarse clipping before submission makes this cost and your own data fetching/submission cost almost null)
// Usage:
-// ImGuiListClipper clipper(1000); // we have 1000 elements, evenly spaced.
-// while (clipper.Step())
-// for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
-// ImGui::Text("line number %d", i);
-// - Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height (step skipped if we passed a known height as second arg to constructor).
-// - Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element.
-// - (Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user call Step(). Does nothing and switch to Step 3.)
-// - Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop.
+// ImGuiListClipper clipper;
+// clipper.Begin(1000); // We have 1000 elements, evenly spaced.
+// while (clipper.Step())
+// for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
+// ImGui::Text("line number %d", i);
+// Generally what happens is:
+// - Clipper lets you process the first element (DisplayStart = 0, DisplayEnd = 1) regardless of it being visible or not.
+// - User code submit one element.
+// - Clipper can measure the height of the first element
+// - Clipper calculate the actual range of elements to display based on the current clipping rectangle, position the cursor before the first visible element.
+// - User code submit visible elements.
struct ImGuiListClipper
{
- float StartPosY;
+ int DisplayStart;
+ int DisplayEnd;
+
+ // [Internal]
+ int ItemsCount;
+ int StepNo;
+ int ItemsFrozen;
float ItemsHeight;
- int ItemsCount, StepNo, DisplayStart, DisplayEnd;
+ float StartPosY;
- // items_count: Use -1 to ignore (you can call Begin later). Use INT_MAX if you don't know how many items you have (in which case the cursor won't be advanced in the final step).
+ IMGUI_API ImGuiListClipper();
+ IMGUI_API ~ImGuiListClipper();
+
+ // items_count: Use INT_MAX if you don't know how many items you have (in which case the cursor won't be advanced in the final step)
// items_height: Use -1.0f to be calculated automatically on first step. Otherwise pass in the distance between your items, typically GetTextLineHeightWithSpacing() or GetFrameHeightWithSpacing().
- // If you don't specify an items_height, you NEED to call Step(). If you specify items_height you may call the old Begin()/End() api directly, but prefer calling Step().
- ImGuiListClipper(int items_count = -1, float items_height = -1.0f) { Begin(items_count, items_height); } // NB: Begin() initialize every fields (as we allow user to call Begin/End multiple times on a same instance if they want).
- ~ImGuiListClipper() { IM_ASSERT(ItemsCount == -1); } // Assert if user forgot to call End() or Step() until false.
-
- IMGUI_API bool Step(); // Call until it returns false. The DisplayStart/DisplayEnd fields will be set and you can process/draw those items.
IMGUI_API void Begin(int items_count, float items_height = -1.0f); // Automatically called by constructor if you passed 'items_count' or by Step() in Step 1.
IMGUI_API void End(); // Automatically called on the last call of Step() that returns false.
+ IMGUI_API bool Step(); // Call until it returns false. The DisplayStart/DisplayEnd fields will be set and you can process/draw those items.
+
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ inline ImGuiListClipper(int items_count, float items_height = -1.0f) { memset(this, 0, sizeof(*this)); ItemsCount = -1; Begin(items_count, items_height); } // [removed in 1.79]
+#endif
};
-// Helpers macros to generate 32-bits encoded colors
+// Helpers macros to generate 32-bit encoded colors
#ifdef IMGUI_USE_BGRA_PACKED_COLOR
#define IM_COL32_R_SHIFT 16
#define IM_COL32_G_SHIFT 8
@@ -1846,8 +2182,8 @@ struct ImColor
ImVec4 Value;
ImColor() { Value.x = Value.y = Value.z = Value.w = 0.0f; }
- ImColor(int r, int g, int b, int a = 255) { float sc = 1.0f/255.0f; Value.x = (float)r * sc; Value.y = (float)g * sc; Value.z = (float)b * sc; Value.w = (float)a * sc; }
- ImColor(ImU32 rgba) { float sc = 1.0f/255.0f; Value.x = (float)((rgba>>IM_COL32_R_SHIFT)&0xFF) * sc; Value.y = (float)((rgba>>IM_COL32_G_SHIFT)&0xFF) * sc; Value.z = (float)((rgba>>IM_COL32_B_SHIFT)&0xFF) * sc; Value.w = (float)((rgba>>IM_COL32_A_SHIFT)&0xFF) * sc; }
+ ImColor(int r, int g, int b, int a = 255) { float sc = 1.0f / 255.0f; Value.x = (float)r * sc; Value.y = (float)g * sc; Value.z = (float)b * sc; Value.w = (float)a * sc; }
+ ImColor(ImU32 rgba) { float sc = 1.0f / 255.0f; Value.x = (float)((rgba >> IM_COL32_R_SHIFT) & 0xFF) * sc; Value.y = (float)((rgba >> IM_COL32_G_SHIFT) & 0xFF) * sc; Value.z = (float)((rgba >> IM_COL32_B_SHIFT) & 0xFF) * sc; Value.w = (float)((rgba >> IM_COL32_A_SHIFT) & 0xFF) * sc; }
ImColor(float r, float g, float b, float a = 1.0f) { Value.x = r; Value.y = g; Value.z = b; Value.w = a; }
ImColor(const ImVec4& col) { Value = col; }
inline operator ImU32() const { return ImGui::ColorConvertFloat4ToU32(Value); }
@@ -1855,50 +2191,57 @@ struct ImColor
// FIXME-OBSOLETE: May need to obsolete/cleanup those helpers.
inline void SetHSV(float h, float s, float v, float a = 1.0f){ ImGui::ColorConvertHSVtoRGB(h, s, v, Value.x, Value.y, Value.z); Value.w = a; }
- static ImColor HSV(float h, float s, float v, float a = 1.0f) { float r,g,b; ImGui::ColorConvertHSVtoRGB(h, s, v, r, g, b); return ImColor(r,g,b,a); }
+ static ImColor HSV(float h, float s, float v, float a = 1.0f) { float r, g, b; ImGui::ColorConvertHSVtoRGB(h, s, v, r, g, b); return ImColor(r, g, b, a); }
};
//-----------------------------------------------------------------------------
-// Draw List API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawListFlags, ImDrawList, ImDrawData)
+// [SECTION] Drawing API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawListFlags, ImDrawList, ImDrawData)
// Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList.
//-----------------------------------------------------------------------------
-// Draw callbacks for advanced uses.
+// The maximum line width to bake anti-aliased textures for. Build atlas with ImFontAtlasFlags_NoBakedLines to disable baking.
+#ifndef IM_DRAWLIST_TEX_LINES_WIDTH_MAX
+#define IM_DRAWLIST_TEX_LINES_WIDTH_MAX (63)
+#endif
+
+// ImDrawCallback: Draw callbacks for advanced uses [configurable type: override in imconfig.h]
// NB: You most likely do NOT need to use draw callbacks just to create your own widget or customized UI rendering,
// you can poke into the draw list for that! Draw callback may be useful for example to:
// A) Change your GPU render state,
// B) render a complex 3D scene inside a UI element without an intermediate texture/render target, etc.
// The expected behavior from your rendering function is 'if (cmd.UserCallback != NULL) { cmd.UserCallback(parent_list, cmd); } else { RenderTriangles() }'
-// If you want to override the signature of ImDrawCallback, you can simply use e.g. '#define ImDrawCallback MyDrawCallback' (in imconfig.h) + update rendering back-end accordingly.
+// If you want to override the signature of ImDrawCallback, you can simply use e.g. '#define ImDrawCallback MyDrawCallback' (in imconfig.h) + update rendering backend accordingly.
#ifndef ImDrawCallback
typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* cmd);
#endif
-// Special Draw callback value to request renderer back-end to reset the graphics/render state.
-// The renderer back-end needs to handle this special value, otherwise it will crash trying to call a function at this address.
+// Special Draw callback value to request renderer backend to reset the graphics/render state.
+// The renderer backend needs to handle this special value, otherwise it will crash trying to call a function at this address.
// This is useful for example if you submitted callbacks which you know have altered the render state and you want it to be restored.
// It is not done by default because they are many perfectly useful way of altering render state for imgui contents (e.g. changing shader/blending settings before an Image call).
#define ImDrawCallback_ResetRenderState (ImDrawCallback)(-1)
// Typically, 1 command = 1 GPU draw call (unless command is a callback)
-// Pre 1.71 back-ends will typically ignore the VtxOffset/IdxOffset fields. When 'io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset'
-// is enabled, those fields allow us to render meshes larger than 64K vertices while keeping 16-bits indices.
+// - VtxOffset/IdxOffset: When 'io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset' is enabled,
+// those fields allow us to render meshes larger than 64K vertices while keeping 16-bit indices.
+// Pre-1.71 backends will typically ignore the VtxOffset/IdxOffset fields.
+// - The ClipRect/TextureId/VtxOffset fields must be contiguous as we memcmp() them together (this is asserted for).
struct ImDrawCmd
{
- unsigned int ElemCount; // Number of indices (multiple of 3) to be rendered as triangles. Vertices are stored in the callee ImDrawList's vtx_buffer[] array, indices in idx_buffer[].
- ImVec4 ClipRect; // Clipping rectangle (x1, y1, x2, y2). Subtract ImDrawData->DisplayPos to get clipping rectangle in "viewport" coordinates
- ImTextureID TextureId; // User-provided texture ID. Set by user in ImfontAtlas::SetTexID() for fonts or passed to Image*() functions. Ignore if never using images or multiple fonts atlas.
- unsigned int VtxOffset; // Start offset in vertex buffer. Pre-1.71 or without ImGuiBackendFlags_RendererHasVtxOffset: always 0. With ImGuiBackendFlags_RendererHasVtxOffset: may be >0 to support meshes larger than 64K vertices with 16-bits indices.
- unsigned int IdxOffset; // Start offset in index buffer. Always equal to sum of ElemCount drawn so far.
- ImDrawCallback UserCallback; // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally.
- void* UserCallbackData; // The draw callback code can access this.
+ ImVec4 ClipRect; // 4*4 // Clipping rectangle (x1, y1, x2, y2). Subtract ImDrawData->DisplayPos to get clipping rectangle in "viewport" coordinates
+ ImTextureID TextureId; // 4-8 // User-provided texture ID. Set by user in ImfontAtlas::SetTexID() for fonts or passed to Image*() functions. Ignore if never using images or multiple fonts atlas.
+ unsigned int VtxOffset; // 4 // Start offset in vertex buffer. ImGuiBackendFlags_RendererHasVtxOffset: always 0, otherwise may be >0 to support meshes larger than 64K vertices with 16-bit indices.
+ unsigned int IdxOffset; // 4 // Start offset in index buffer. Always equal to sum of ElemCount drawn so far.
+ unsigned int ElemCount; // 4 // Number of indices (multiple of 3) to be rendered as triangles. Vertices are stored in the callee ImDrawList's vtx_buffer[] array, indices in idx_buffer[].
+ ImDrawCallback UserCallback; // 4-8 // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally.
+ void* UserCallbackData; // 4-8 // The draw callback code can access this.
- ImDrawCmd() { ElemCount = 0; TextureId = (ImTextureID)NULL; VtxOffset = IdxOffset = 0; UserCallback = NULL; UserCallbackData = NULL; }
+ ImDrawCmd() { memset(this, 0, sizeof(*this)); } // Also ensure our padding fields are zeroed
};
-// Vertex index
-// (to allow large meshes with 16-bits indices: set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' and handle ImDrawCmd::VtxOffset in the renderer back-end)
-// (to use 32-bits indices: override with '#define ImDrawIdx unsigned int' in imconfig.h)
+// Vertex index, default to 16-bit
+// To allow large meshes with 16-bit indices: set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' and handle ImDrawCmd::VtxOffset in the renderer backend (recommended).
+// To use 32-bit indices: override with '#define ImDrawIdx unsigned int' in imconfig.h.
#ifndef ImDrawIdx
typedef unsigned short ImDrawIdx;
#endif
@@ -1919,22 +2262,31 @@ struct ImDrawVert
IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT;
#endif
-// For use by ImDrawListSplitter.
+// [Internal] For use by ImDrawList
+struct ImDrawCmdHeader
+{
+ ImVec4 ClipRect;
+ ImTextureID TextureId;
+ unsigned int VtxOffset;
+};
+
+// [Internal] For use by ImDrawListSplitter
struct ImDrawChannel
{
ImVector _CmdBuffer;
ImVector _IdxBuffer;
};
+
// Split/Merge functions are used to split the draw list into different layers which can be drawn into out of order.
-// This is used by the Columns api, so items of each column can be batched together in a same draw call.
+// This is used by the Columns/Tables API, so items of each column can be batched together in a same draw call.
struct ImDrawListSplitter
{
int _Current; // Current channel number (0)
int _Count; // Number of active channels (1+)
ImVector _Channels; // Draw channels (not resized down so _Count might be < Channels.Size)
- inline ImDrawListSplitter() { Clear(); }
+ inline ImDrawListSplitter() { memset(this, 0, sizeof(*this)); }
inline ~ImDrawListSplitter() { ClearFreeMemory(); }
inline void Clear() { _Current = 0; _Count = 1; } // Do not clear Channels[] so our allocations are reused next frame
IMGUI_API void ClearFreeMemory();
@@ -1957,12 +2309,15 @@ enum ImDrawCornerFlags_
ImDrawCornerFlags_All = 0xF // In your function calls you may use ~0 (= all bits sets) instead of ImDrawCornerFlags_All, as a convenience
};
+// Flags for ImDrawList. Those are set automatically by ImGui:: functions from ImGuiIO settings, and generally not manipulated directly.
+// It is however possible to temporarily alter flags between calls to ImDrawList:: functions.
enum ImDrawListFlags_
{
- ImDrawListFlags_None = 0,
- ImDrawListFlags_AntiAliasedLines = 1 << 0, // Lines are anti-aliased (*2 the number of triangles for 1.0f wide line, otherwise *3 the number of triangles)
- ImDrawListFlags_AntiAliasedFill = 1 << 1, // Filled shapes have anti-aliased edges (*2 the number of vertices)
- ImDrawListFlags_AllowVtxOffset = 1 << 2 // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled.
+ ImDrawListFlags_None = 0,
+ ImDrawListFlags_AntiAliasedLines = 1 << 0, // Enable anti-aliased lines/borders (*2 the number of triangles for 1.0f wide line or lines thin enough to be drawn using textures, otherwise *3 the number of triangles)
+ ImDrawListFlags_AntiAliasedLinesUseTex = 1 << 1, // Enable anti-aliased lines/borders using textures when possible. Require backend to render with bilinear filtering.
+ ImDrawListFlags_AntiAliasedFill = 1 << 2, // Enable anti-aliased edge around filled shapes (rounded rectangles, circles).
+ ImDrawListFlags_AllowVtxOffset = 1 << 3 // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled.
};
// Draw command list
@@ -1971,7 +2326,7 @@ enum ImDrawListFlags_
// Each dear imgui window contains its own ImDrawList. You can use ImGui::GetWindowDrawList() to
// access the current window draw list and draw custom primitives.
// You can interleave normal ImGui:: calls and adding primitives to the current draw list.
-// All positions are generally in pixel coordinates (generally top-left at 0,0, bottom-right at io.DisplaySize, unless multiple viewports are used), but you are totally free to apply whatever transformation matrix to want to the data (if you apply such transformation you'll want to apply it to ClipRect as well)
+// All positions are generally in pixel coordinates (top-left at (0,0), bottom-right at io.DisplaySize), but you are totally free to apply whatever transformation matrix to want to the data (if you apply such transformation you'll want to apply it to ClipRect as well)
// Important: Primitives are always added to the list and not culled (culling is done at higher-level by ImGui:: functions), if you use this API a lot consider coarse culling your drawn objects.
struct ImDrawList
{
@@ -1982,20 +2337,22 @@ struct ImDrawList
ImDrawListFlags Flags; // Flags, you may poke into these to adjust anti-aliasing settings per-primitive.
// [Internal, used while building lists]
+ unsigned int _VtxCurrentIdx; // [Internal] generally == VtxBuffer.Size unless we are past 64K vertices, in which case this gets reset to 0.
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 _VtxCurrentOffset; // [Internal] Always 0 unless 'Flags & ImDrawListFlags_AllowVtxOffset'.
- unsigned int _VtxCurrentIdx; // [Internal] Generally == VtxBuffer.Size unless we are past 64K vertices, in which case this gets reset to 0.
ImDrawVert* _VtxWritePtr; // [Internal] point within VtxBuffer.Data after each add command (to avoid using the ImVector<> operators too much)
ImDrawIdx* _IdxWritePtr; // [Internal] point within IdxBuffer.Data after each add command (to avoid using the ImVector<> operators too much)
ImVector _ClipRectStack; // [Internal]
ImVector _TextureIdStack; // [Internal]
ImVector _Path; // [Internal] current path building
- ImDrawListSplitter _Splitter; // [Internal] for channels api
+ ImDrawCmdHeader _CmdHeader; // [Internal] template of active commands. Fields should match those of CmdBuffer.back().
+ ImDrawListSplitter _Splitter; // [Internal] for channels api (note: prefer using your own persistent instance of ImDrawListSplitter!)
+ float _FringeScale; // [Internal] anti-alias fringe is scaled by this value, this helps to keep things sharp while zooming at vertex buffer content
// 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(); }
+ ImDrawList(const ImDrawListSharedData* shared_data) { memset(this, 0, sizeof(*this)); _Data = shared_data; }
+
+ ~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();
@@ -2006,21 +2363,28 @@ struct ImDrawList
// Primitives
// - For rectangular primitives, "p_min" and "p_max" represent the upper-left and lower-right corners.
+ // - For circle primitives, use "num_segments == 0" to automatically calculate tessellation (preferred).
+ // In older versions (until Dear ImGui 1.77) the AddCircle functions defaulted to num_segments == 12.
+ // In future versions we will use textures to provide cheaper and higher-quality circles.
+ // Use AddNgon() and AddNgonFilled() functions if you need to guaranteed a specific number of sides.
IMGUI_API void AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness = 1.0f);
- IMGUI_API void AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding = 0.0f, ImDrawCornerFlags rounding_corners = ImDrawCornerFlags_All, float thickness = 1.0f); // a: upper-left, b: lower-right (== upper-left + size), rounding_corners_flags: 4-bits corresponding to which corner to round
+ IMGUI_API void AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding = 0.0f, ImDrawCornerFlags rounding_corners = ImDrawCornerFlags_All, float thickness = 1.0f); // a: upper-left, b: lower-right (== upper-left + size), rounding_corners_flags: 4 bits corresponding to which corner to round
IMGUI_API void AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding = 0.0f, ImDrawCornerFlags rounding_corners = ImDrawCornerFlags_All); // a: upper-left, b: lower-right (== upper-left + size)
IMGUI_API void AddRectFilledMultiColor(const ImVec2& p_min, const ImVec2& p_max, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left);
IMGUI_API void AddQuad(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness = 1.0f);
IMGUI_API void AddQuadFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col);
IMGUI_API void AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness = 1.0f);
IMGUI_API void AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col);
- IMGUI_API void AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments = 12, float thickness = 1.0f);
- IMGUI_API void AddCircleFilled(const ImVec2& center, float radius, ImU32 col, int num_segments = 12);
+ IMGUI_API void AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments = 0, float thickness = 1.0f);
+ IMGUI_API void AddCircleFilled(const ImVec2& center, float radius, ImU32 col, int num_segments = 0);
+ IMGUI_API void AddNgon(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness = 1.0f);
+ IMGUI_API void AddNgonFilled(const ImVec2& center, float radius, ImU32 col, int num_segments);
IMGUI_API void AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL);
IMGUI_API void AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL, float wrap_width = 0.0f, const ImVec4* cpu_fine_clip_rect = NULL);
IMGUI_API void AddPolyline(const ImVec2* points, int num_points, ImU32 col, bool closed, float thickness);
IMGUI_API void AddConvexPolyFilled(const ImVec2* points, int num_points, ImU32 col); // Note: Anti-aliased filling requires points to be in clockwise order.
- IMGUI_API void AddBezierCurve(const ImVec2& pos0, const ImVec2& cp0, const ImVec2& cp1, const ImVec2& pos1, ImU32 col, float thickness, int num_segments = 0);
+ IMGUI_API void AddBezierCubic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments = 0); // Cubic Bezier (4 control points)
+ IMGUI_API void AddBezierQuadratic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness, int num_segments = 0); // Quadratic Bezier (3 control points)
// Image primitives
// - Read FAQ to understand what ImTextureID is.
@@ -2033,12 +2397,13 @@ struct ImDrawList
// Stateful path API, add points then finish with PathFillConvex() or PathStroke()
inline void PathClear() { _Path.Size = 0; }
inline void PathLineTo(const ImVec2& pos) { _Path.push_back(pos); }
- inline void PathLineToMergeDuplicate(const ImVec2& pos) { if (_Path.Size == 0 || memcmp(&_Path.Data[_Path.Size-1], &pos, 8) != 0) _Path.push_back(pos); }
+ inline void PathLineToMergeDuplicate(const ImVec2& pos) { if (_Path.Size == 0 || memcmp(&_Path.Data[_Path.Size - 1], &pos, 8) != 0) _Path.push_back(pos); }
inline void PathFillConvex(ImU32 col) { AddConvexPolyFilled(_Path.Data, _Path.Size, col); _Path.Size = 0; } // Note: Anti-aliased filling requires points to be in clockwise order.
inline void PathStroke(ImU32 col, bool closed, float thickness = 1.0f) { AddPolyline(_Path.Data, _Path.Size, col, closed, thickness); _Path.Size = 0; }
IMGUI_API void PathArcTo(const ImVec2& center, float radius, float a_min, float a_max, int num_segments = 10);
- IMGUI_API void PathArcToFast(const ImVec2& center, float radius, int a_min_of_12, int a_max_of_12); // Use precomputed angles for a 12 steps circle
- IMGUI_API void PathBezierCurveTo(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, int num_segments = 0);
+ IMGUI_API void PathArcToFast(const ImVec2& center, float radius, int a_min_of_12, int a_max_of_12); // Use precomputed angles for a 12 steps circle
+ IMGUI_API void PathBezierCubicCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments = 0); // Cubic Bezier (4 control points)
+ IMGUI_API void PathBezierQuadraticCurveTo(const ImVec2& p2, const ImVec2& p3, int num_segments = 0); // Quadratic Bezier (3 control points)
IMGUI_API void PathRect(const ImVec2& rect_min, const ImVec2& rect_max, float rounding = 0.0f, ImDrawCornerFlags rounding_corners = ImDrawCornerFlags_All);
// Advanced
@@ -2047,25 +2412,39 @@ struct ImDrawList
IMGUI_API ImDrawList* CloneOutput() const; // Create a clone of the CmdBuffer/IdxBuffer/VtxBuffer.
// Advanced: Channels
- // - Use to split render into layers. By switching channels to can render out-of-order (e.g. submit foreground primitives before background primitives)
- // - Use to minimize draw calls (e.g. if going back-and-forth between multiple non-overlapping clipping rectangles, prefer to append into separate channels then merge at the end)
+ // - Use to split render into layers. By switching channels to can render out-of-order (e.g. submit FG primitives before BG primitives)
+ // - Use to minimize draw calls (e.g. if going back-and-forth between multiple clipping rectangles, prefer to append into separate channels then merge at the end)
+ // - FIXME-OBSOLETE: This API shouldn't have been in ImDrawList in the first place!
+ // Prefer using your own persistent instance of ImDrawListSplitter as you can stack them.
+ // Using the ImDrawList::ChannelsXXXX you cannot stack a split over another.
inline void ChannelsSplit(int count) { _Splitter.Split(this, count); }
inline void ChannelsMerge() { _Splitter.Merge(this); }
inline void ChannelsSetCurrent(int n) { _Splitter.SetCurrentChannel(this, n); }
- // Internal helpers
- // NB: all primitives needs to be reserved via PrimReserve() beforehand!
- IMGUI_API void Clear();
- IMGUI_API void ClearFreeMemory();
+ // Advanced: Primitives allocations
+ // - We render triangles (three vertices)
+ // - All primitives needs to be reserved via PrimReserve() beforehand.
IMGUI_API void PrimReserve(int idx_count, int vtx_count);
+ IMGUI_API void PrimUnreserve(int idx_count, int vtx_count);
IMGUI_API void PrimRect(const ImVec2& a, const ImVec2& b, ImU32 col); // Axis aligned rectangle (composed of two triangles)
IMGUI_API void PrimRectUV(const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col);
IMGUI_API void PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col);
- inline void PrimWriteVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col){ _VtxWritePtr->pos = pos; _VtxWritePtr->uv = uv; _VtxWritePtr->col = col; _VtxWritePtr++; _VtxCurrentIdx++; }
- inline void PrimWriteIdx(ImDrawIdx idx) { *_IdxWritePtr = idx; _IdxWritePtr++; }
- inline void PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { PrimWriteIdx((ImDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); }
- IMGUI_API void UpdateClipRect();
- IMGUI_API void UpdateTextureID();
+ inline void PrimWriteVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { _VtxWritePtr->pos = pos; _VtxWritePtr->uv = uv; _VtxWritePtr->col = col; _VtxWritePtr++; _VtxCurrentIdx++; }
+ inline void PrimWriteIdx(ImDrawIdx idx) { *_IdxWritePtr = idx; _IdxWritePtr++; }
+ inline void PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { PrimWriteIdx((ImDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); } // Write vertex with unique index
+
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ inline void AddBezierCurve(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments = 0) { AddBezierCubic(p1, p2, p3, p4, col, thickness, num_segments); }
+ inline void PathBezierCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments = 0) { PathBezierCubicCurveTo(p2, p3, p4, num_segments); }
+#endif
+
+ // [Internal helpers]
+ IMGUI_API void _ResetForNewFrame();
+ IMGUI_API void _ClearFreeMemory();
+ IMGUI_API void _PopUnusedDrawCmd();
+ IMGUI_API void _OnChangedClipRect();
+ IMGUI_API void _OnChangedTextureID();
+ IMGUI_API void _OnChangedVtxOffset();
};
// All draw data to render a Dear ImGui frame
@@ -2081,18 +2460,17 @@ struct ImDrawData
ImVec2 DisplayPos; // Upper-left position of the viewport to render (== upper-left of the orthogonal projection matrix to use)
ImVec2 DisplaySize; // Size of the viewport to render (== io.DisplaySize for the main viewport) (DisplayPos + DisplaySize == lower-right of the orthogonal projection matrix to use)
ImVec2 FramebufferScale; // Amount of pixels for each unit of DisplaySize. Based on io.DisplayFramebufferScale. Generally (1,1) on normal display, (2,2) on OSX with Retina display.
- ImGuiViewport* OwnerViewport; // Viewport carrying the ImDrawData instance, might be of use to the renderer (generally not).
// Functions
ImDrawData() { Valid = false; Clear(); }
~ImDrawData() { Clear(); }
- void Clear() { Valid = false; CmdLists = NULL; CmdListsCount = TotalVtxCount = TotalIdxCount = 0; DisplayPos = DisplaySize = FramebufferScale = ImVec2(0.f, 0.f); OwnerViewport = NULL; } // The ImDrawList are owned by ImGuiContext!
+ void Clear() { Valid = false; CmdLists = NULL; CmdListsCount = TotalVtxCount = TotalIdxCount = 0; DisplayPos = DisplaySize = FramebufferScale = ImVec2(0.f, 0.f); } // 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& fb_scale); // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than Dear ImGui expects, or if there is a difference between your window resolution and framebuffer resolution.
};
//-----------------------------------------------------------------------------
-// Font API (ImFontConfig, ImFontGlyph, ImFontAtlasFlags, ImFontAtlas, ImFontGlyphRangesBuilder, ImFont)
+// [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontAtlasFlags, ImFontAtlas, ImFontGlyphRangesBuilder, ImFont)
//-----------------------------------------------------------------------------
struct ImFontConfig
@@ -2111,7 +2489,7 @@ struct ImFontConfig
float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font
float GlyphMaxAdvanceX; // FLT_MAX // Maximum AdvanceX for glyphs
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.
+ unsigned int FontBuilderFlags; // 0 // Settings for custom font builder. THIS IS BUILDER IMPLEMENTATION DEPENDENT. Leave as zero if unsure.
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.
ImWchar EllipsisChar; // -1 // Explicitly specify unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used.
@@ -2122,9 +2500,12 @@ struct ImFontConfig
IMGUI_API ImFontConfig();
};
+// Hold rendering data for one glyph.
+// (Note: some language parsers may fail to convert the 31+1 bitfield members, in this case maybe drop store a single u32 or we can rework this)
struct ImFontGlyph
{
- ImWchar Codepoint; // 0x0000..0xFFFF
+ unsigned int Codepoint : 31; // 0x0000..0xFFFF
+ unsigned int Visible : 1; // Flag to allow early out when rendering
float AdvanceX; // Distance to next character (= data from font + ImFontConfig::GlyphExtraSpacing.x baked in)
float X0, Y0, X1, Y1; // Glyph corners
float U0, V0, U1, V1; // Texture coordinates
@@ -2136,11 +2517,11 @@ struct ImFontGlyphRangesBuilder
{
ImVector UsedChars; // Store 1-bit per Unicode code point (0=unused, 1=used)
- ImFontGlyphRangesBuilder() { Clear(); }
- inline void Clear() { int size_in_bytes = 0x10000 / 8; UsedChars.resize(size_in_bytes / (int)sizeof(ImU32)); memset(UsedChars.Data, 0, (size_t)size_in_bytes); }
- inline bool GetBit(int n) const { int off = (n >> 5); ImU32 mask = 1u << (n & 31); return (UsedChars[off] & mask) != 0; } // Get bit n in the array
- inline void SetBit(int n) { int off = (n >> 5); ImU32 mask = 1u << (n & 31); UsedChars[off] |= mask; } // Set bit n in the array
- inline void AddChar(ImWchar c) { SetBit(c); } // Add character
+ ImFontGlyphRangesBuilder() { Clear(); }
+ inline void Clear() { int size_in_bytes = (IM_UNICODE_CODEPOINT_MAX + 1) / 8; UsedChars.resize(size_in_bytes / (int)sizeof(ImU32)); memset(UsedChars.Data, 0, (size_t)size_in_bytes); }
+ inline bool GetBit(size_t n) const { int off = (int)(n >> 5); ImU32 mask = 1u << (n & 31); return (UsedChars[off] & mask) != 0; } // Get bit n in the array
+ inline void SetBit(size_t n) { int off = (int)(n >> 5); ImU32 mask = 1u << (n & 31); UsedChars[off] |= mask; } // Set bit n in the array
+ inline void AddChar(ImWchar c) { SetBit(c); } // Add character
IMGUI_API void AddText(const char* text, const char* text_end = NULL); // Add string (each character of the UTF-8 string are added)
IMGUI_API void AddRanges(const ImWchar* ranges); // Add ranges, e.g. builder.AddRanges(ImFontAtlas::GetGlyphRangesDefault()) to force add all of ASCII/Latin+Ext
IMGUI_API void BuildRanges(ImVector* out_ranges); // Output new ranges
@@ -2149,21 +2530,23 @@ struct ImFontGlyphRangesBuilder
// See ImFontAtlas::AddCustomRectXXX functions.
struct ImFontAtlasCustomRect
{
- unsigned int ID; // Input // User ID. Use <0x10000 to map into a font glyph, >=0x10000 for other/internal/custom texture data.
unsigned short Width, Height; // Input // Desired rectangle dimension
unsigned short X, Y; // Output // Packed position in Atlas
- float GlyphAdvanceX; // Input // For custom font glyphs only (ID<0x10000): glyph xadvance
- ImVec2 GlyphOffset; // Input // For custom font glyphs only (ID<0x10000): glyph display offset
- ImFont* Font; // Input // For custom font glyphs only (ID<0x10000): target font
- ImFontAtlasCustomRect() { ID = 0xFFFFFFFF; Width = Height = 0; X = Y = 0xFFFF; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0,0); Font = NULL; }
+ unsigned int GlyphID; // Input // For custom font glyphs only (ID < 0x110000)
+ float GlyphAdvanceX; // Input // For custom font glyphs only: glyph xadvance
+ ImVec2 GlyphOffset; // Input // For custom font glyphs only: glyph display offset
+ ImFont* Font; // Input // For custom font glyphs only: target font
+ ImFontAtlasCustomRect() { Width = Height = 0; X = Y = 0xFFFF; GlyphID = 0; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0, 0); Font = NULL; }
bool IsPacked() const { return X != 0xFFFF; }
};
+// Flags for ImFontAtlas build
enum ImFontAtlasFlags_
{
ImFontAtlasFlags_None = 0,
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
+ ImFontAtlasFlags_NoMouseCursors = 1 << 1, // Don't build software mouse cursors into the atlas (save a little texture memory)
+ ImFontAtlasFlags_NoBakedLines = 1 << 2 // Don't build thick line textures into the atlas (save a little texture memory). The AntiAliasedLinesUseTex features uses them, otherwise they will be rendered using polygons (more expensive for CPU/GPU).
};
// Load and rasterize multiple TTF/OTF fonts into a same texture. The font atlas will build a single texture holding:
@@ -2206,7 +2589,7 @@ struct ImFontAtlas
IMGUI_API bool Build(); // Build pixels data. This is called automatically for you by the GetTexData*** functions.
IMGUI_API void GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 1 byte per-pixel
IMGUI_API void GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 4 bytes-per-pixel
- bool IsBuilt() { return Fonts.Size > 0 && (TexPixelsAlpha8 != NULL || TexPixelsRGBA32 != NULL); }
+ bool IsBuilt() const { return Fonts.Size > 0 && (TexPixelsAlpha8 != NULL || TexPixelsRGBA32 != NULL); }
void SetTexID(ImTextureID id) { TexID = id; }
//-------------------------------------------
@@ -2218,7 +2601,7 @@ struct ImFontAtlas
// NB: Consider using ImFontGlyphRangesBuilder to build glyph ranges from textual data.
IMGUI_API const ImWchar* GetGlyphRangesDefault(); // Basic Latin, Extended Latin
IMGUI_API const ImWchar* GetGlyphRangesKorean(); // Default + Korean characters
- IMGUI_API const ImWchar* GetGlyphRangesJapanese(); // Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs
+ IMGUI_API const ImWchar* GetGlyphRangesJapanese(); // Default + Hiragana, Katakana, Half-Width, Selection of 2999 Ideographs
IMGUI_API const ImWchar* GetGlyphRangesChineseFull(); // Default + Half-Width + Japanese Hiragana/Katakana + full set of about 21000 CJK Unified Ideographs
IMGUI_API const ImWchar* GetGlyphRangesChineseSimplifiedCommon();// Default + Half-Width + Japanese Hiragana/Katakana + set of 2500 CJK Unified Ideographs for common simplified Chinese
IMGUI_API const ImWchar* GetGlyphRangesCyrillic(); // Default + about 400 Cyrillic characters
@@ -2233,13 +2616,14 @@ struct ImFontAtlas
// After calling Build(), you can query the rectangle position and render your pixels.
// You can also request your rectangles to be mapped as font glyph (given a font + Unicode point),
// so you can render e.g. custom colorful icons and use them as regular glyphs.
- // Read misc/fonts/README.txt for more details about using colorful icons.
- 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.
- const ImFontAtlasCustomRect*GetCustomRectByIndex(int index) const { if (index < 0) return NULL; return &CustomRects[index]; }
+ // Read docs/FONTS.md for more details about using colorful icons.
+ // Note: this API may be redesigned later in order to support multi-monitor varying DPI settings.
+ IMGUI_API int AddCustomRectRegular(int width, int height);
+ IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0));
+ ImFontAtlasCustomRect* GetCustomRectByIndex(int index) { IM_ASSERT(index >= 0); return &CustomRects[index]; }
// [Internal]
- IMGUI_API void CalcCustomRectUV(const ImFontAtlasCustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max);
+ IMGUI_API void CalcCustomRectUV(const ImFontAtlasCustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const;
IMGUI_API bool GetMouseCursorTexData(ImGuiMouseCursor cursor, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]);
//-------------------------------------------
@@ -2262,8 +2646,16 @@ struct ImFontAtlas
ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel
ImVector 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 CustomRects; // Rectangles for packing custom texture data into the atlas.
- ImVector ConfigData; // Internal data
- int CustomRectIds[1]; // Identifiers of custom texture rectangle used by ImFontAtlas/ImDrawList
+ ImVector ConfigData; // Configuration data
+ ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines
+
+ // [Internal] Font builder
+ const ImFontBuilderIO* FontBuilderIO; // Opaque interface to a font builder (default to stb_truetype, can be changed to use FreeType by defining IMGUI_ENABLE_FREETYPE).
+ unsigned int FontBuilderFlags; // Shared flags (for all fonts) for custom font builder. THIS IS BUILD IMPLEMENTATION DEPENDENT. Per-font override is also available in ImFontConfig.
+
+ // [Internal] Packing data
+ int PackIdMouseCursors; // Custom texture rectangle ID for white pixel and mouse cursors
+ int PackIdLines; // Custom texture rectangle ID for baked anti-aliased lines
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+
@@ -2280,11 +2672,10 @@ struct ImFont
float FallbackAdvanceX; // 4 // out // = FallbackGlyph->AdvanceX
float FontSize; // 4 // in // // Height of characters/line, set during loading (don't change after loading)
- // Members: Hot ~36/48 bytes (for CalcTextSize + render loop)
+ // Members: Hot ~28/40 bytes (for CalcTextSize + render loop)
ImVector IndexLookup; // 12-16 // out // // Sparse. Index glyphs by Unicode code-point.
ImVector Glyphs; // 12-16 // out // // All glyphs.
const ImFontGlyph* FallbackGlyph; // 4-8 // out // = FindGlyph(FontFallbackChar)
- ImVec2 DisplayOffset; // 8 // in // = (0,0) // Offset font rendering by xx pixels
// Members: Cold ~32/40 bytes
ImFontAtlas* ContainerAtlas; // 4-8 // out // // What we has been loaded into
@@ -2292,10 +2683,11 @@ struct ImFont
short ConfigDataCount; // 2 // in // ~ 1 // Number of ImFontConfig involved in creating this font. Bigger than 1 when merging multiple font sources into one ImFont.
ImWchar FallbackChar; // 2 // in // = '?' // Replacement character if a glyph isn't found. Only set via SetFallbackChar()
ImWchar EllipsisChar; // 2 // out // = -1 // Character used for ellipsis rendering.
+ bool DirtyLookupTables; // 1 // out //
float Scale; // 4 // in // = 1.f // Base font scale, multiplied by the per-window font scale which you can adjust with SetWindowFontScale()
float Ascent, Descent; // 4+4 // out // // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize]
int MetricsTotalSurface;// 4 // out // // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs)
- bool DirtyLookupTables; // 1 // out //
+ ImU8 Used4kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/4096/8]; // 2 bytes if ImWchar=ImWchar16, 34 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 4K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints.
// Methods
IMGUI_API ImFont();
@@ -2317,124 +2709,11 @@ struct ImFont
IMGUI_API void BuildLookupTable();
IMGUI_API void ClearOutputData();
IMGUI_API void GrowIndex(int new_size);
- IMGUI_API void AddGlyph(ImWchar c, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x);
+ IMGUI_API void AddGlyph(const ImFontConfig* src_cfg, ImWchar c, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x);
IMGUI_API void AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst = true); // Makes 'dst' character/glyph points to 'src' character/glyph. Currently needs to be called AFTER fonts have been built.
+ IMGUI_API void SetGlyphVisible(ImWchar c, bool visible);
IMGUI_API void SetFallbackChar(ImWchar c);
-};
-
-//-----------------------------------------------------------------------------
-// [BETA] Platform interface for multi-viewport support
-// - completely optional, for advanced users!
-// - this is used for back-ends aiming to support the seamless creation of multiple viewport (= multiple Platform/OS windows)
-// dear imgui manages the viewports, and the back-end create one Platform/OS windows for each secondary viewport.
-// - if you are new to dear imgui and trying to integrate it into your engine, you should probably ignore this for now.
-//-----------------------------------------------------------------------------
-
-// (Optional) This is required when enabling multi-viewport. Represent the bounds of each connected monitor/display and their DPI.
-// We use this information for multiple DPI support + clamping the position of popups and tooltips so they don't straddle multiple monitors.
-struct ImGuiPlatformMonitor
-{
- ImVec2 MainPos, MainSize; // Coordinates of the area displayed on this monitor (Min = upper left, Max = bottom right)
- ImVec2 WorkPos, WorkSize; // (Optional) Coordinates without task bars / side bars / menu bars. imgui uses this to avoid positioning popups/tooltips inside this region.
- float DpiScale; // 1.0f = 96 DPI
- ImGuiPlatformMonitor() { MainPos = MainSize = WorkPos = WorkSize = ImVec2(0,0); DpiScale = 1.0f; }
-};
-
-// (Optional) Setup required only if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) is enabled.
-// Access via ImGui::GetPlatformIO(). This is designed so we can mix and match two imgui_impl_xxxx files,
-// one for the Platform (~window handling), one for Renderer. Custom engine back-ends will often provide
-// both Platform and Renderer interfaces and so may not need to use all functions.
-// Platform functions are typically called before their Renderer counterpart,
-// apart from Destroy which are called the other way.
-// RenderPlatformWindowsDefault() is that helper that iterate secondary viewports and call, in this order:
-// Platform_RenderWindow(), Renderer_RenderWindow(), Platform_SwapBuffers(), Renderer_SwapBuffers()
-// You may skip using RenderPlatformWindowsDefault() and call your draw/swap functions yourself if you need
-// specific behavior for your multi-window rendering.
-struct ImGuiPlatformIO
-{
- //------------------------------------------------------------------
- // Input - Back-end interface/functions + Monitor List
- //------------------------------------------------------------------
-
- // (Optional) Platform functions (e.g. Win32, GLFW, SDL2)
- // Most of them are called by ImGui::UpdatePlatformWindows() and ImGui::RenderPlatformWindowsDefault().
- void (*Platform_CreateWindow)(ImGuiViewport* vp); // Create a new platform window for the given viewport
- void (*Platform_DestroyWindow)(ImGuiViewport* vp);
- void (*Platform_ShowWindow)(ImGuiViewport* vp); // Newly created windows are initially hidden so SetWindowPos/Size/Title can be called on them first
- void (*Platform_SetWindowPos)(ImGuiViewport* vp, ImVec2 pos);
- ImVec2 (*Platform_GetWindowPos)(ImGuiViewport* vp);
- void (*Platform_SetWindowSize)(ImGuiViewport* vp, ImVec2 size);
- ImVec2 (*Platform_GetWindowSize)(ImGuiViewport* vp);
- void (*Platform_SetWindowFocus)(ImGuiViewport* vp); // Move window to front and set input focus
- bool (*Platform_GetWindowFocus)(ImGuiViewport* vp);
- bool (*Platform_GetWindowMinimized)(ImGuiViewport* vp);
- void (*Platform_SetWindowTitle)(ImGuiViewport* vp, const char* title);
- void (*Platform_SetWindowAlpha)(ImGuiViewport* vp, float alpha); // (Optional) Setup window transparency
- void (*Platform_UpdateWindow)(ImGuiViewport* vp); // (Optional) Called in UpdatePlatforms(). Optional hook to allow the platform back-end from doing general book-keeping every frame.
- void (*Platform_RenderWindow)(ImGuiViewport* vp, void* render_arg); // (Optional) Setup for render
- void (*Platform_SwapBuffers)(ImGuiViewport* vp, void* render_arg); // (Optional) Call Present/SwapBuffers (platform side)
- float (*Platform_GetWindowDpiScale)(ImGuiViewport* vp); // (Optional) [BETA] (FIXME-DPI) DPI handling: Return DPI scale for this viewport. 1.0f = 96 DPI.
- void (*Platform_OnChangedViewport)(ImGuiViewport* vp); // (Optional) [BETA] (FIXME-DPI) DPI handling: Called during Begin() every time the viewport we are outputting into changes, so back-end has a chance to swap fonts to adjust style.
- void (*Platform_SetImeInputPos)(ImGuiViewport* vp, ImVec2 pos); // (Optional) Set IME (Input Method Editor, e.g. for Asian languages) input position, so text preview appears over the imgui input box.
- int (*Platform_CreateVkSurface)(ImGuiViewport* vp, ImU64 vk_inst, const void* vk_allocators, ImU64* out_vk_surface); // (Optional) For Renderer to call into Platform code
-
- // (Optional) Renderer functions (e.g. DirectX, OpenGL3, Vulkan)
- void (*Renderer_CreateWindow)(ImGuiViewport* vp); // Create swap chains, frame buffers etc.
- void (*Renderer_DestroyWindow)(ImGuiViewport* vp);
- void (*Renderer_SetWindowSize)(ImGuiViewport* vp, ImVec2 size); // Resize swap chain, frame buffers etc.
- void (*Renderer_RenderWindow)(ImGuiViewport* vp, void* render_arg); // (Optional) Clear targets, Render viewport->DrawData
- void (*Renderer_SwapBuffers)(ImGuiViewport* vp, void* render_arg); // (Optional) Call Present/SwapBuffers (renderer side)
-
- // (Optional) List of monitors (updated by: app/back-end, used by: imgui to clamp popups/tooltips within same monitor and not have them straddle monitors)
- ImVector Monitors;
-
- //------------------------------------------------------------------
- // Output - List of viewports to render into platform windows
- //------------------------------------------------------------------
-
- // List of viewports (the list is updated by calling ImGui::EndFrame or ImGui::Render)
- ImGuiViewport* MainViewport; // Guaranteed to be == Viewports[0]
- ImVector Viewports; // Main viewports, followed by all secondary viewports.
- ImGuiPlatformIO() { memset(this, 0, sizeof(*this)); } // Zero clear
-};
-
-// Flags stored in ImGuiViewport::Flags, giving indications to the platform back-ends.
-enum ImGuiViewportFlags_
-{
- ImGuiViewportFlags_None = 0,
- ImGuiViewportFlags_NoDecoration = 1 << 0, // Platform Window: Disable platform decorations: title bar, borders, etc. (generally set all windows, but if ImGuiConfigFlags_ViewportsDecoration is set we only set this on popups/tooltips)
- ImGuiViewportFlags_NoTaskBarIcon = 1 << 1, // Platform Window: Disable platform task bar icon (generally set on popups/tooltips, or all windows if ImGuiConfigFlags_ViewportsNoTaskBarIcon is set)
- ImGuiViewportFlags_NoFocusOnAppearing = 1 << 2, // Platform Window: Don't take focus when created.
- ImGuiViewportFlags_NoFocusOnClick = 1 << 3, // Platform Window: Don't take focus when clicked on.
- ImGuiViewportFlags_NoInputs = 1 << 4, // Platform Window: Make mouse pass through so we can drag this window while peaking behind it.
- ImGuiViewportFlags_NoRendererClear = 1 << 5, // Platform Window: Renderer doesn't need to clear the framebuffer ahead (because we will fill it entirely).
- ImGuiViewportFlags_TopMost = 1 << 6, // Platform Window: Display on top (for tooltips only).
- ImGuiViewportFlags_Minimized = 1 << 7, // Platform Window: Window is minimized, can skip render. When minimized we tend to avoid using the viewport pos/size for clipping window or testing if they are contained in the viewport.
- ImGuiViewportFlags_NoAutoMerge = 1 << 8, // Platform Window: Avoid merging this widow into another host window. This can only be set via ImGuiWindowClass viewport flags override (because we need to now ahead if we are going to create a viewport in the first place!).
- ImGuiViewportFlags_CanHostOtherWindows = 1 << 9 // Main viewport: can host multiple imgui windows (secondary viewports are associated to a single window).
-};
-
-// The viewports created and managed by imgui. The role of the platform back-end is to create the platform/OS windows corresponding to each viewport.
-struct ImGuiViewport
-{
- ImGuiID ID; // Unique identifier for the viewport
- ImGuiViewportFlags Flags; // See ImGuiViewportFlags_
- ImVec2 Pos; // Position of viewport both in imgui space and in OS desktop/native space
- ImVec2 Size; // Size of viewport in pixel
- float DpiScale; // 1.0f = 96 DPI = No extra scale
- ImDrawData* DrawData; // The ImDrawData corresponding to this viewport. Valid after Render() and until the next call to NewFrame().
- ImGuiID ParentViewportId; // (Advanced) 0: no parent. Instruct the platform back-end to setup a parent/child relationship between platform windows.
-
- void* RendererUserData; // void* to hold custom data structure for the renderer (e.g. swap chain, frame-buffers etc.)
- void* PlatformUserData; // void* to hold custom data structure for the OS / platform (e.g. windowing info, render context)
- void* PlatformHandle; // void* for FindViewportByPlatformHandle(). (e.g. suggested to use natural platform handle such as HWND, GLFWWindow*, SDL_Window*)
- void* PlatformHandleRaw; // void* to hold low-level, platform-native window handle (e.g. the HWND) when using an abstraction layer like GLFW or SDL (where PlatformHandle would be a SDL_Window*)
- bool PlatformRequestClose; // Platform window requested closure (e.g. window was moved by the OS / host window manager, e.g. pressing ALT-F4)
- bool PlatformRequestMove; // Platform window requested move (e.g. window was moved by the OS / host window manager, authoritative position will be OS window position)
- bool PlatformRequestResize; // Platform window requested resize (e.g. window was resized by the OS / host window manager, authoritative size will be OS window size)
-
- ImGuiViewport() { ID = 0; Flags = 0; DpiScale = 0.0f; DrawData = NULL; ParentViewportId = 0; RendererUserData = PlatformUserData = PlatformHandle = PlatformHandleRaw = NULL; PlatformRequestClose = PlatformRequestMove = PlatformRequestResize = false; }
- ~ImGuiViewport() { IM_ASSERT(PlatformUserData == NULL && RendererUserData == NULL); }
+ IMGUI_API bool IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last);
};
#if defined(__clang__)
@@ -2447,3 +2726,5 @@ struct ImGuiViewport
#ifdef IMGUI_INCLUDE_IMGUI_USER_H
#include "imgui_user.h"
#endif
+
+#endif // #ifndef IMGUI_DISABLE
diff --git a/dep/imgui/include/imgui_internal.h b/dep/imgui/include/imgui_internal.h
index 71d644696..1c961617a 100644
--- a/dep/imgui/include/imgui_internal.h
+++ b/dep/imgui/include/imgui_internal.h
@@ -1,4 +1,4 @@
-// dear imgui, v1.74 WIP
+// dear imgui, v1.81 WIP
// (internal structures/api)
// You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility!
@@ -9,29 +9,44 @@
/*
Index of this file:
-// Header mess
-// Forward declarations
-// STB libraries includes
-// Context pointer
-// Generic helpers
-// Misc data structures
-// Main imgui context
-// Tab bar, tab item
-// Internal API
+
+// [SECTION] Header mess
+// [SECTION] Forward declarations
+// [SECTION] Context pointer
+// [SECTION] STB libraries includes
+// [SECTION] Macros
+// [SECTION] Generic helpers
+// [SECTION] ImDrawList support
+// [SECTION] Widgets support: flags, enums, data structures
+// [SECTION] Columns support
+// [SECTION] Multi-select support
+// [SECTION] Docking support
+// [SECTION] Viewport support
+// [SECTION] Settings support
+// [SECTION] Metrics, Debug
+// [SECTION] Generic context hooks
+// [SECTION] ImGuiContext (main imgui context)
+// [SECTION] ImGuiWindowTempData, ImGuiWindow
+// [SECTION] Tab bar, Tab item support
+// [SECTION] Table support
+// [SECTION] ImGui internal API
+// [SECTION] ImFontAtlas internal API
+// [SECTION] Test Engine specific hooks (imgui_test_engine)
*/
#pragma once
+#ifndef IMGUI_DISABLE
//-----------------------------------------------------------------------------
-// Header mess
+// [SECTION] Header mess
//-----------------------------------------------------------------------------
#ifndef IMGUI_VERSION
#error Must include imgui.h before imgui_internal.h
#endif
-#include // FILE*
+#include // FILE*, sscanf
#include // NULL, malloc, free, qsort, atoi, atof
#include // sqrtf, fabsf, fmodf, powf, floorf, ceilf, cosf, sinf
#include // INT_MIN, INT_MAX
@@ -45,71 +60,99 @@ Index of this file:
// Clang/GCC warnings with -Weverything
#if defined(__clang__)
#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wunused-function" // for stb_textedit.h
-#pragma clang diagnostic ignored "-Wmissing-prototypes" // for stb_textedit.h
+#if __has_warning("-Wunknown-warning-option")
+#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx'
+#endif
+#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
+#pragma clang diagnostic ignored "-Wunused-function" // for stb_textedit.h
+#pragma clang diagnostic ignored "-Wmissing-prototypes" // for stb_textedit.h
#pragma clang diagnostic ignored "-Wold-style-cast"
-#if __has_warning("-Wzero-as-null-pointer-constant")
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
-#endif
-#if __has_warning("-Wdouble-promotion")
#pragma clang diagnostic ignored "-Wdouble-promotion"
-#endif
+#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
#elif defined(__GNUC__)
#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
-#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
+#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
+#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
+#endif
+
+// Legacy defines
+#ifdef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS // Renamed in 1.74
+#error Use IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
+#endif
+#ifdef IMGUI_DISABLE_MATH_FUNCTIONS // Renamed in 1.74
+#error Use IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS
+#endif
+
+// Enable stb_truetype by default unless FreeType is enabled.
+// You can compile with both by defining both IMGUI_ENABLE_FREETYPE and IMGUI_ENABLE_STB_TRUETYPE together.
+#ifndef IMGUI_ENABLE_FREETYPE
+#define IMGUI_ENABLE_STB_TRUETYPE
#endif
//-----------------------------------------------------------------------------
-// Forward declarations
+// [SECTION] Forward declarations
//-----------------------------------------------------------------------------
+struct ImBitVector; // Store 1-bit per value
struct ImRect; // An axis-aligned rectangle (2 points)
struct ImDrawDataBuilder; // Helper to build a ImDrawData instance
struct ImDrawListSharedData; // Data shared between all ImDrawList instances
struct ImGuiColorMod; // Stacked color modifier, backup of modified data so we can restore it
-struct ImGuiColumnData; // Storage data for a single column
-struct ImGuiColumns; // Storage data for a columns set
struct ImGuiContext; // Main Dear ImGui context
+struct ImGuiContextHook; // Hook for extensions like ImGuiTestEngine
struct ImGuiDataTypeInfo; // Type information associated to a ImGuiDataType enum
-struct ImGuiDockContext; // Docking system context
-struct ImGuiDockNode; // Docking system node (hold a list of Windows OR two child dock nodes)
-struct ImGuiDockNodeSettings; // Storage for a dock node in .ini file (we preserve those even if the associated dock node isn't active during the session)
struct ImGuiGroupData; // Stacked storage data for BeginGroup()/EndGroup()
struct ImGuiInputTextState; // Internal state of the currently focused/edited text input box
-struct ImGuiItemHoveredDataBackup; // Backup and restore IsItemHovered() internal data
+struct ImGuiLastItemDataBackup; // Backup and restore IsItemHovered() internal data
struct ImGuiMenuColumns; // Simple column measurement, currently used for MenuItem() only
-struct ImGuiNavMoveResult; // Result of a directional navigation move query result
+struct ImGuiNavMoveResult; // Result of a gamepad/keyboard directional navigation move query result
+struct ImGuiMetricsConfig; // Storage for ShowMetricsWindow() and DebugNodeXXX() functions
struct ImGuiNextWindowData; // Storage for SetNextWindow** functions
struct ImGuiNextItemData; // Storage for SetNextItem** functions
+struct ImGuiOldColumnData; // Storage data for a single column for legacy Columns() api
+struct ImGuiOldColumns; // Storage data for a columns set for legacy Columns() api
struct ImGuiPopupData; // Storage for current popup stack
struct ImGuiSettingsHandler; // Storage for one type registered in the .ini file
+struct ImGuiStackSizes; // Storage of stack sizes for debugging/asserting
struct ImGuiStyleMod; // Stacked style modifier, backup of modified data so we can restore it
struct ImGuiTabBar; // Storage for a tab bar
struct ImGuiTabItem; // Storage for a tab item (within a tab bar)
+struct ImGuiTable; // Storage for a table
+struct ImGuiTableColumn; // Storage for one column of a table
+struct ImGuiTableSettings; // Storage for a table .ini settings
+struct ImGuiTableColumnsSettings; // Storage for a column .ini settings
struct ImGuiWindow; // Storage for one window
struct ImGuiWindowTempData; // Temporary storage for one window (that's the data which in theory we could ditch at the end of the frame)
-struct ImGuiWindowSettings; // Storage for window settings stored in .ini file (we keep one of those even if the actual window wasn't instanced during this session)
+struct ImGuiWindowSettings; // Storage for a window .ini settings (we keep one of those even if the actual window wasn't instanced during this session)
// Use your programming IDE "Go to definition" facility on the names of the center columns to find the actual flags/enum lists.
-typedef int ImGuiDataAuthority; // -> enum ImGuiDataAuthority_ // Enum: for storing the source authority (dock node vs window) of a field
typedef int ImGuiLayoutType; // -> enum ImGuiLayoutType_ // Enum: Horizontal or vertical
-typedef int ImGuiButtonFlags; // -> enum ImGuiButtonFlags_ // Flags: for ButtonEx(), ButtonBehavior()
-typedef int ImGuiColumnsFlags; // -> enum ImGuiColumnsFlags_ // Flags: BeginColumns()
-typedef int ImGuiDragFlags; // -> enum ImGuiDragFlags_ // Flags: for DragBehavior()
typedef int ImGuiItemFlags; // -> enum ImGuiItemFlags_ // Flags: for PushItemFlag()
typedef int ImGuiItemStatusFlags; // -> enum ImGuiItemStatusFlags_ // Flags: for DC.LastItemStatusFlags
+typedef int ImGuiOldColumnFlags; // -> enum ImGuiOldColumnFlags_ // Flags: for BeginColumns()
typedef int ImGuiNavHighlightFlags; // -> enum ImGuiNavHighlightFlags_ // Flags: for RenderNavHighlight()
typedef int ImGuiNavDirSourceFlags; // -> enum ImGuiNavDirSourceFlags_ // Flags: for GetNavInputAmount2d()
typedef int ImGuiNavMoveFlags; // -> enum ImGuiNavMoveFlags_ // Flags: for navigation requests
typedef int ImGuiNextItemDataFlags; // -> enum ImGuiNextItemDataFlags_ // Flags: for SetNextItemXXX() functions
typedef int ImGuiNextWindowDataFlags; // -> enum ImGuiNextWindowDataFlags_// Flags: for SetNextWindowXXX() functions
typedef int ImGuiSeparatorFlags; // -> enum ImGuiSeparatorFlags_ // Flags: for SeparatorEx()
-typedef int ImGuiSliderFlags; // -> enum ImGuiSliderFlags_ // Flags: for SliderBehavior()
typedef int ImGuiTextFlags; // -> enum ImGuiTextFlags_ // Flags: for TextEx()
+typedef int ImGuiTooltipFlags; // -> enum ImGuiTooltipFlags_ // Flags: for BeginTooltipEx()
+
+typedef void (*ImGuiErrorLogCallback)(void* user_data, const char* fmt, ...);
+
+//-----------------------------------------------------------------------------
+// [SECTION] Context pointer
+// See implementation of this variable in imgui.cpp for comments and details.
+//-----------------------------------------------------------------------------
+
+#ifndef GImGui
+extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer
+#endif
//-------------------------------------------------------------------------
-// STB libraries includes
+// [SECTION] STB libraries includes
//-------------------------------------------------------------------------
namespace ImStb
@@ -119,7 +162,7 @@ namespace ImStb
#undef STB_TEXTEDIT_CHARTYPE
#define STB_TEXTEDIT_STRING ImGuiInputTextState
#define STB_TEXTEDIT_CHARTYPE ImWchar
-#define STB_TEXTEDIT_GETWIDTH_NEWLINE -1.0f
+#define STB_TEXTEDIT_GETWIDTH_NEWLINE (-1.0f)
#define STB_TEXTEDIT_UNDOSTATECOUNT 99
#define STB_TEXTEDIT_UNDOCHARCOUNT 999
#include "imstb_textedit.h"
@@ -127,40 +170,54 @@ namespace ImStb
} // namespace ImStb
//-----------------------------------------------------------------------------
-// Context pointer
+// [SECTION] Macros
//-----------------------------------------------------------------------------
-#ifndef GImGui
-extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer
-#endif
-
-// Internal Drag and Drop payload types. String starting with '_' are reserved for Dear ImGui.
-#define IMGUI_PAYLOAD_TYPE_WINDOW "_IMWINDOW" // Payload == ImGuiWindow*
-
-//-----------------------------------------------------------------------------
-// Generic helpers
-//-----------------------------------------------------------------------------
-
-#define IM_PI 3.14159265358979323846f
-#ifdef _WIN32
-#define IM_NEWLINE "\r\n" // Play it nice with Windows users (2018/05 news: Microsoft announced that Notepad will finally display Unix-style carriage returns!)
-#else
-#define IM_NEWLINE "\n"
-#endif
-#define IM_TABSIZE (4)
-#define IM_STATIC_ASSERT(_COND) typedef char static_assertion_##__line__[(_COND)?1:-1]
-#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
-#define IM_FLOOR(_VAL) ((float)(int)(_VAL)) // ImFloor() is not inlined in MSVC debug builds
-
// Debug Logging
#ifndef IMGUI_DEBUG_LOG
#define IMGUI_DEBUG_LOG(_FMT,...) printf("[%05d] " _FMT, GImGui->FrameCount, __VA_ARGS__)
#endif
-#define IMGUI_DEBUG_LOG_VIEWPORT(...) ((void)0) // Disable log
-#define IMGUI_DEBUG_LOG_DOCKING(...) ((void)0) // Disable log
-//#define IMGUI_DEBUG_LOG_VIEWPORT IMGUI_DEBUG_LOG // Enable log
-//#define IMGUI_DEBUG_LOG_DOCKING IMGUI_DEBUG_LOG // Enable log
+
+// Debug Logging for selected systems. Remove the '((void)0) //' to enable.
+//#define IMGUI_DEBUG_LOG_POPUP IMGUI_DEBUG_LOG // Enable log
+//#define IMGUI_DEBUG_LOG_NAV IMGUI_DEBUG_LOG // Enable log
+#define IMGUI_DEBUG_LOG_POPUP(...) ((void)0) // Disable log
+#define IMGUI_DEBUG_LOG_NAV(...) ((void)0) // Disable log
+
+// Static Asserts
+#if (__cplusplus >= 201100) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201100)
+#define IM_STATIC_ASSERT(_COND) static_assert(_COND, "")
+#else
+#define IM_STATIC_ASSERT(_COND) typedef char static_assertion_##__line__[(_COND)?1:-1]
+#endif
+
+// "Paranoid" Debug Asserts are meant to only be enabled during specific debugging/work, otherwise would slow down the code too much.
+// We currently don't have many of those so the effect is currently negligible, but onward intent to add more aggressive ones in the code.
+//#define IMGUI_DEBUG_PARANOID
+#ifdef IMGUI_DEBUG_PARANOID
+#define IM_ASSERT_PARANOID(_EXPR) IM_ASSERT(_EXPR)
+#else
+#define IM_ASSERT_PARANOID(_EXPR)
+#endif
+
+// Error handling
+// Down the line in some frameworks/languages we would like to have a way to redirect those to the programmer and recover from more faults.
+#ifndef IM_ASSERT_USER_ERROR
+#define IM_ASSERT_USER_ERROR(_EXP,_MSG) IM_ASSERT((_EXP) && _MSG) // Recoverable User Error
+#endif
+
+// Misc Macros
+#define IM_PI 3.14159265358979323846f
+#ifdef _WIN32
+#define IM_NEWLINE "\r\n" // Play it nice with Windows users (Update: since 2018-05, Notepad finally appears to support Unix-style carriage returns!)
+#else
+#define IM_NEWLINE "\n"
+#endif
+#define IM_TABSIZE (4)
+#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
+#define IM_FLOOR(_VAL) ((float)(int)(_VAL)) // ImFloor() is not inlined in MSVC debug builds
+#define IM_ROUND(_VAL) ((float)(int)((_VAL) + 0.5f)) //
// 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
@@ -169,36 +226,60 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer
#define IMGUI_CDECL
#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
-IMGUI_API int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end); // read one character. return input UTF-8 bytes count
-IMGUI_API int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_remaining = NULL); // return input UTF-8 bytes count
-IMGUI_API int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end); // return number of UTF-8 code-points (NOT bytes count)
-IMGUI_API int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end); // return number of bytes to express one char in UTF-8
-IMGUI_API int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end); // return number of bytes to express string in UTF-8
+// Debug Tools
+// Use 'Metrics->Tools->Item Picker' to break into the call-stack of a specific item.
+#ifndef IM_DEBUG_BREAK
+#if defined(__clang__)
+#define IM_DEBUG_BREAK() __builtin_debugtrap()
+#elif defined (_MSC_VER)
+#define IM_DEBUG_BREAK() __debugbreak()
+#else
+#define IM_DEBUG_BREAK() IM_ASSERT(0) // It is expected that you define IM_DEBUG_BREAK() into something that will break nicely in a debugger!
+#endif
+#endif // #ifndef IM_DEBUG_BREAK
-// Helpers: Misc
-IMGUI_API ImU32 ImHashData(const void* data, size_t data_size, ImU32 seed = 0);
-IMGUI_API ImU32 ImHashStr(const char* data, size_t data_size = 0, ImU32 seed = 0);
-IMGUI_API void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, size_t* out_file_size = NULL, int padding_bytes = 0);
-IMGUI_API FILE* ImFileOpen(const char* filename, const char* file_open_mode);
-static inline bool ImCharIsBlankA(char c) { return c == ' ' || c == '\t'; }
-static inline bool ImCharIsBlankW(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; }
-#define ImQsort qsort
+//-----------------------------------------------------------------------------
+// [SECTION] Generic helpers
+// Note that the ImXXX helpers functions are lower-level than ImGui functions.
+// ImGui functions or the ImGui context are never called/used from other ImXXX functions.
+//-----------------------------------------------------------------------------
+// - Helpers: Hashing
+// - Helpers: Sorting
+// - Helpers: Bit manipulation
+// - Helpers: String, Formatting
+// - Helpers: UTF-8 <> wchar conversions
+// - Helpers: ImVec2/ImVec4 operators
+// - Helpers: Maths
+// - Helpers: Geometry
+// - Helper: ImVec1
+// - Helper: ImVec2ih
+// - Helper: ImRect
+// - Helper: ImBitArray
+// - Helper: ImBitVector
+// - Helper: ImSpan<>, ImSpanAllocator<>
+// - Helper: ImPool<>
+// - Helper: ImChunkStream<>
+//-----------------------------------------------------------------------------
+
+// Helpers: Hashing
+IMGUI_API ImGuiID ImHashData(const void* data, size_t data_size, ImU32 seed = 0);
+IMGUI_API ImGuiID ImHashStr(const char* data, size_t data_size = 0, ImU32 seed = 0);
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
-static inline ImU32 ImHash(const void* data, int size, ImU32 seed = 0) { return size ? ImHashData(data, (size_t)size, seed) : ImHashStr((const char*)data, 0, seed); } // [moved to ImHashStr/ImHashData in 1.68]
+static inline ImGuiID ImHash(const void* data, int size, ImU32 seed = 0) { return size ? ImHashData(data, (size_t)size, seed) : ImHashStr((const char*)data, 0, seed); } // [moved to ImHashStr/ImHashData in 1.68]
#endif
-// Helpers: Geometry
-IMGUI_API ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p);
-IMGUI_API bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p);
-IMGUI_API ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p);
-IMGUI_API void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w);
-IMGUI_API ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy);
+// Helpers: Sorting
+#define ImQsort qsort
-// Helpers: String
+// Helpers: Color Blending
+IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b);
+
+// Helpers: Bit manipulation
+static inline bool ImIsPowerOfTwo(int v) { return v != 0 && (v & (v - 1)) == 0; }
+static inline bool ImIsPowerOfTwo(ImU64 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; }
+
+// Helpers: String, Formatting
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);
@@ -217,45 +298,84 @@ IMGUI_API const char* ImParseFormatFindStart(const char* format);
IMGUI_API const char* ImParseFormatFindEnd(const char* format);
IMGUI_API const char* ImParseFormatTrimDecorations(const char* format, char* buf, size_t buf_size);
IMGUI_API int ImParseFormatPrecision(const char* format, int default_value);
+static inline bool ImCharIsBlankA(char c) { return c == ' ' || c == '\t'; }
+static inline bool ImCharIsBlankW(unsigned int c) { return c == ' ' || c == '\t' || c == 0x3000; }
+
+// Helpers: UTF-8 <> wchar conversions
+IMGUI_API int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end); // return output UTF-8 bytes count
+IMGUI_API int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end); // read one character. return input UTF-8 bytes count
+IMGUI_API int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_remaining = NULL); // return input UTF-8 bytes count
+IMGUI_API int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end); // return number of UTF-8 code-points (NOT bytes count)
+IMGUI_API int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end); // return number of bytes to express one char in UTF-8
+IMGUI_API int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end); // return number of bytes to express string in UTF-8
// Helpers: ImVec2/ImVec4 operators
// We are keeping those disabled by default so they don't leak in user space, to allow user enabling implicit cast operators between ImVec2 and their own types (using IM_VEC2_CLASS_EXTRA etc.)
// We unfortunately don't have a unary- operator for ImVec2 because this would needs to be defined inside the class itself.
#ifdef IMGUI_DEFINE_MATH_OPERATORS
-static inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x*rhs, lhs.y*rhs); }
-static inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x/rhs, lhs.y/rhs); }
-static inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x+rhs.x, lhs.y+rhs.y); }
-static inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x-rhs.x, lhs.y-rhs.y); }
-static inline ImVec2 operator*(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x*rhs.x, lhs.y*rhs.y); }
-static inline ImVec2 operator/(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x/rhs.x, lhs.y/rhs.y); }
-static inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; }
-static inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; }
+static inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x * rhs, lhs.y * rhs); }
+static inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x / rhs, lhs.y / rhs); }
+static inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x + rhs.x, lhs.y + rhs.y); }
+static inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x - rhs.x, lhs.y - rhs.y); }
+static inline ImVec2 operator*(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); }
+static inline ImVec2 operator/(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x / rhs.x, lhs.y / rhs.y); }
static inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; }
static inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; }
-static inline ImVec4 operator+(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x+rhs.x, lhs.y+rhs.y, lhs.z+rhs.z, lhs.w+rhs.w); }
-static inline ImVec4 operator-(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x-rhs.x, lhs.y-rhs.y, lhs.z-rhs.z, lhs.w-rhs.w); }
-static inline ImVec4 operator*(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x*rhs.x, lhs.y*rhs.y, lhs.z*rhs.z, lhs.w*rhs.w); }
+static inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; }
+static inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; }
+static inline ImVec2& operator*=(ImVec2& lhs, const ImVec2& rhs) { lhs.x *= rhs.x; lhs.y *= rhs.y; return lhs; }
+static inline ImVec2& operator/=(ImVec2& lhs, const ImVec2& rhs) { lhs.x /= rhs.x; lhs.y /= rhs.y; return lhs; }
+static inline ImVec4 operator+(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w); }
+static inline ImVec4 operator-(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w); }
+static inline ImVec4 operator*(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z, lhs.w * rhs.w); }
#endif
+// Helpers: File System
+#ifdef IMGUI_DISABLE_FILE_FUNCTIONS
+#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
+typedef void* ImFileHandle;
+static inline ImFileHandle ImFileOpen(const char*, const char*) { return NULL; }
+static inline bool ImFileClose(ImFileHandle) { return false; }
+static inline ImU64 ImFileGetSize(ImFileHandle) { return (ImU64)-1; }
+static inline ImU64 ImFileRead(void*, ImU64, ImU64, ImFileHandle) { return 0; }
+static inline ImU64 ImFileWrite(const void*, ImU64, ImU64, ImFileHandle) { return 0; }
+#endif
+#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
+typedef FILE* ImFileHandle;
+IMGUI_API ImFileHandle ImFileOpen(const char* filename, const char* mode);
+IMGUI_API bool ImFileClose(ImFileHandle file);
+IMGUI_API ImU64 ImFileGetSize(ImFileHandle file);
+IMGUI_API ImU64 ImFileRead(void* data, ImU64 size, ImU64 count, ImFileHandle file);
+IMGUI_API ImU64 ImFileWrite(const void* data, ImU64 size, ImU64 count, ImFileHandle file);
+#else
+#define IMGUI_DISABLE_TTY_FUNCTIONS // Can't use stdout, fflush if we are not using default file functions
+#endif
+IMGUI_API void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size = NULL, int padding_bytes = 0);
+
// Helpers: Maths
// - Wrapper for standard libs functions. (Note that imgui_demo.cpp does _not_ use them to keep the code easy to copy)
-#ifndef IMGUI_DISABLE_MATH_FUNCTIONS
-static inline float ImFabs(float x) { return fabsf(x); }
-static inline float ImSqrt(float x) { return sqrtf(x); }
-static inline float ImPow(float x, float y) { return powf(x, y); }
-static inline double ImPow(double x, double y) { return pow(x, y); }
-static inline float ImFmod(float x, float y) { return fmodf(x, y); }
-static inline double ImFmod(double x, double y) { return fmod(x, y); }
-static inline float ImCos(float x) { return cosf(x); }
-static inline float ImSin(float x) { return sinf(x); }
-static inline float ImAcos(float x) { return acosf(x); }
-static inline float ImAtan2(float y, float x) { return atan2f(y, x); }
-static inline double ImAtof(const char* s) { return atof(s); }
-static inline float ImFloorStd(float x) { return floorf(x); } // we already uses our own ImFloor() { return (float)(int)v } internally so the standard one wrapper is named differently (it's used by stb_truetype)
-static inline float ImCeil(float x) { return ceilf(x); }
+#ifndef IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS
+#define ImFabs(X) fabsf(X)
+#define ImSqrt(X) sqrtf(X)
+#define ImFmod(X, Y) fmodf((X), (Y))
+#define ImCos(X) cosf(X)
+#define ImSin(X) sinf(X)
+#define ImAcos(X) acosf(X)
+#define ImAtan2(Y, X) atan2f((Y), (X))
+#define ImAtof(STR) atof(STR)
+#define ImFloorStd(X) floorf(X) // We already uses our own ImFloor() { return (float)(int)v } internally so the standard one wrapper is named differently (it's used by e.g. stb_truetype)
+#define ImCeil(X) ceilf(X)
+static inline float ImPow(float x, float y) { return powf(x, y); } // DragBehaviorT/SliderBehaviorT uses ImPow with either float/double and need the precision
+static inline double ImPow(double x, double y) { return pow(x, y); }
+static inline float ImLog(float x) { return logf(x); } // DragBehaviorT/SliderBehaviorT uses ImLog with either float/double and need the precision
+static inline double ImLog(double x) { return log(x); }
+static inline float ImAbs(float x) { return fabsf(x); }
+static inline double ImAbs(double x) { return fabs(x); }
+static inline float ImSign(float x) { return (x < 0.0f) ? -1.0f : ((x > 0.0f) ? 1.0f : 0.0f); } // Sign operator - returns -1, 0 or 1 based on sign of argument
+static inline double ImSign(double x) { return (x < 0.0) ? -1.0 : ((x > 0.0) ? 1.0 : 0.0); }
#endif
-// - ImMin/ImMax/ImClamp/ImLerp/ImSwap are used by widgets which support for variety of types: signed/unsigned int/long long float/double
-// (Exceptionally using templates here but we could also redefine them for variety of types)
+// - ImMin/ImMax/ImClamp/ImLerp/ImSwap are used by widgets which support variety of types: signed/unsigned int/long long float/double
+// (Exceptionally using templates here but we could also redefine them for those types)
template static inline T ImMin(T lhs, T rhs) { return lhs < rhs ? lhs : rhs; }
template static inline T ImMax(T lhs, T rhs) { return lhs >= rhs ? lhs : rhs; }
template static inline T ImClamp(T v, T mn, T mx) { return (v < mn) ? mn : (v > mx) ? mx : v; }
@@ -271,111 +391,354 @@ static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, float t)
static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, const ImVec2& t) { return ImVec2(a.x + (b.x - a.x) * t.x, a.y + (b.y - a.y) * t.y); }
static inline ImVec4 ImLerp(const ImVec4& a, const ImVec4& b, float t) { return ImVec4(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t, a.z + (b.z - a.z) * t, a.w + (b.w - a.w) * t); }
static inline float ImSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f : f; }
-static inline float ImLengthSqr(const ImVec2& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y; }
-static inline float ImLengthSqr(const ImVec4& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y + lhs.z*lhs.z + lhs.w*lhs.w; }
-static inline float ImInvLength(const ImVec2& lhs, float fail_value) { float d = lhs.x*lhs.x + lhs.y*lhs.y; if (d > 0.0f) return 1.0f / ImSqrt(d); return fail_value; }
-static inline float ImFloor(float f) { return (float)(int)f; }
-static inline ImVec2 ImFloor(const ImVec2& v) { return ImVec2((float)(int)v.x, (float)(int)v.y); }
+static inline float ImLengthSqr(const ImVec2& lhs) { return (lhs.x * lhs.x) + (lhs.y * lhs.y); }
+static inline float ImLengthSqr(const ImVec4& lhs) { return (lhs.x * lhs.x) + (lhs.y * lhs.y) + (lhs.z * lhs.z) + (lhs.w * lhs.w); }
+static inline float ImInvLength(const ImVec2& lhs, float fail_value) { float d = (lhs.x * lhs.x) + (lhs.y * lhs.y); if (d > 0.0f) return 1.0f / ImSqrt(d); return fail_value; }
+static inline float ImFloor(float f) { return (float)(int)(f); }
+static inline ImVec2 ImFloor(const ImVec2& v) { return ImVec2((float)(int)(v.x), (float)(int)(v.y)); }
static inline int ImModPositive(int a, int b) { return (a + b) % b; }
static inline float ImDot(const ImVec2& a, const ImVec2& b) { return a.x * b.x + a.y * b.y; }
static inline ImVec2 ImRotate(const ImVec2& v, float cos_a, float sin_a) { return ImVec2(v.x * cos_a - v.y * sin_a, v.x * sin_a + v.y * cos_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); }
-// Helper: ImBoolVector. Store 1-bit per value.
-// Note that Resize() currently clears the whole vector.
-struct ImBoolVector
+// Helpers: Geometry
+IMGUI_API ImVec2 ImBezierCubicCalc(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, float t);
+IMGUI_API ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments); // For curves with explicit number of segments
+IMGUI_API ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol);// For auto-tessellated curves you can use tess_tol = style.CurveTessellationTol
+IMGUI_API ImVec2 ImBezierQuadraticCalc(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, float t);
+IMGUI_API ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p);
+IMGUI_API bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p);
+IMGUI_API ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p);
+IMGUI_API void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w);
+inline float ImTriangleArea(const ImVec2& a, const ImVec2& b, const ImVec2& c) { return ImFabs((a.x * (b.y - c.y)) + (b.x * (c.y - a.y)) + (c.x * (a.y - b.y))) * 0.5f; }
+IMGUI_API ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy);
+
+// Helper: ImVec1 (1D vector)
+// (this odd construct is used to facilitate the transition between 1D and 2D, and the maintenance of some branches/patches)
+struct ImVec1
{
- ImVector Storage;
- ImBoolVector() { }
- void Resize(int sz) { Storage.resize((sz + 31) >> 5); memset(Storage.Data, 0, (size_t)Storage.Size * sizeof(Storage.Data[0])); }
- void Clear() { Storage.clear(); }
- bool GetBit(int n) const { int off = (n >> 5); int mask = 1 << (n & 31); return (Storage[off] & mask) != 0; }
- void SetBit(int n, bool v) { int off = (n >> 5); int mask = 1 << (n & 31); if (v) Storage[off] |= mask; else Storage[off] &= ~mask; }
+ float x;
+ ImVec1() { x = 0.0f; }
+ ImVec1(float _x) { x = _x; }
};
-// Helper: ImPool<>. Basic keyed storage for contiguous instances, slow/amortized insertion, O(1) indexable, O(Log N) queries by ID over a dense/hot buffer,
+// Helper: ImVec2ih (2D vector, half-size integer, for long-term packed storage)
+struct ImVec2ih
+{
+ short x, y;
+ ImVec2ih() { x = y = 0; }
+ ImVec2ih(short _x, short _y) { x = _x; y = _y; }
+ explicit ImVec2ih(const ImVec2& rhs) { x = (short)rhs.x; y = (short)rhs.y; }
+};
+
+// Helper: ImRect (2D axis aligned bounding-box)
+// NB: we can't rely on ImVec2 math operators being available here!
+struct IMGUI_API ImRect
+{
+ ImVec2 Min; // Upper-left
+ ImVec2 Max; // Lower-right
+
+ ImRect() : Min(0.0f, 0.0f), Max(0.0f, 0.0f) {}
+ ImRect(const ImVec2& min, const ImVec2& max) : Min(min), Max(max) {}
+ 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& 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& d) { Min.x += d.x; Min.y += d.y; Max.x += d.x; Max.y += d.y; }
+ void TranslateX(float dx) { Min.x += dx; Max.x += dx; }
+ void TranslateY(float dy) { Min.y += dy; Max.y += dy; }
+ 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 = IM_FLOOR(Min.x); Min.y = IM_FLOOR(Min.y); Max.x = IM_FLOOR(Max.x); Max.y = IM_FLOOR(Max.y); }
+ bool IsInverted() const { return Min.x > Max.x || Min.y > Max.y; }
+ ImVec4 ToVec4() const { return ImVec4(Min.x, Min.y, Max.x, Max.y); }
+};
+
+// Helper: ImBitArray
+inline bool ImBitArrayTestBit(const ImU32* arr, int n) { ImU32 mask = (ImU32)1 << (n & 31); return (arr[n >> 5] & mask) != 0; }
+inline void ImBitArrayClearBit(ImU32* arr, int n) { ImU32 mask = (ImU32)1 << (n & 31); arr[n >> 5] &= ~mask; }
+inline void ImBitArraySetBit(ImU32* arr, int n) { ImU32 mask = (ImU32)1 << (n & 31); arr[n >> 5] |= mask; }
+inline void ImBitArraySetBitRange(ImU32* arr, int n, int n2) // Works on range [n..n2)
+{
+ n2--;
+ while (n <= n2)
+ {
+ int a_mod = (n & 31);
+ int b_mod = (n2 > (n | 31) ? 31 : (n2 & 31)) + 1;
+ ImU32 mask = (ImU32)(((ImU64)1 << b_mod) - 1) & ~(ImU32)(((ImU64)1 << a_mod) - 1);
+ arr[n >> 5] |= mask;
+ n = (n + 32) & ~31;
+ }
+}
+
+// Helper: ImBitArray class (wrapper over ImBitArray functions)
+// Store 1-bit per value. NOT CLEARED by constructor.
+template
+struct IMGUI_API ImBitArray
+{
+ ImU32 Storage[(BITCOUNT + 31) >> 5];
+ ImBitArray() { }
+ void ClearAllBits() { memset(Storage, 0, sizeof(Storage)); }
+ void SetAllBits() { memset(Storage, 255, sizeof(Storage)); }
+ bool TestBit(int n) const { IM_ASSERT(n < BITCOUNT); return ImBitArrayTestBit(Storage, n); }
+ void SetBit(int n) { IM_ASSERT(n < BITCOUNT); ImBitArraySetBit(Storage, n); }
+ void ClearBit(int n) { IM_ASSERT(n < BITCOUNT); ImBitArrayClearBit(Storage, n); }
+ void SetBitRange(int n, int n2) { ImBitArraySetBitRange(Storage, n, n2); } // Works on range [n..n2)
+};
+
+// Helper: ImBitVector
+// Store 1-bit per value.
+struct IMGUI_API ImBitVector
+{
+ ImVector Storage;
+ void Create(int sz) { Storage.resize((sz + 31) >> 5); memset(Storage.Data, 0, (size_t)Storage.Size * sizeof(Storage.Data[0])); }
+ void Clear() { Storage.clear(); }
+ bool TestBit(int n) const { IM_ASSERT(n < (Storage.Size << 5)); return ImBitArrayTestBit(Storage.Data, n); }
+ void SetBit(int n) { IM_ASSERT(n < (Storage.Size << 5)); ImBitArraySetBit(Storage.Data, n); }
+ void ClearBit(int n) { IM_ASSERT(n < (Storage.Size << 5)); ImBitArrayClearBit(Storage.Data, n); }
+};
+
+// Helper: ImSpan<>
+// Pointing to a span of data we don't own.
+template
+struct ImSpan
+{
+ T* Data;
+ T* DataEnd;
+
+ // Constructors, destructor
+ inline ImSpan() { Data = DataEnd = NULL; }
+ inline ImSpan(T* data, int size) { Data = data; DataEnd = data + size; }
+ inline ImSpan(T* data, T* data_end) { Data = data; DataEnd = data_end; }
+
+ inline void set(T* data, int size) { Data = data; DataEnd = data + size; }
+ inline void set(T* data, T* data_end) { Data = data; DataEnd = data_end; }
+ inline int size() const { return (int)(ptrdiff_t)(DataEnd - Data); }
+ inline int size_in_bytes() const { return (int)(ptrdiff_t)(DataEnd - Data) * (int)sizeof(T); }
+ inline T& operator[](int i) { T* p = Data + i; IM_ASSERT(p >= Data && p < DataEnd); return *p; }
+ inline const T& operator[](int i) const { const T* p = Data + i; IM_ASSERT(p >= Data && p < DataEnd); return *p; }
+
+ inline T* begin() { return Data; }
+ inline const T* begin() const { return Data; }
+ inline T* end() { return DataEnd; }
+ inline const T* end() const { return DataEnd; }
+
+ // Utilities
+ inline int index_from_ptr(const T* it) const { IM_ASSERT(it >= Data && it < DataEnd); const ptrdiff_t off = it - Data; return (int)off; }
+};
+
+// Helper: ImSpanAllocator<>
+// Facilitate storing multiple chunks into a single large block (the "arena")
+template
+struct ImSpanAllocator
+{
+ char* BasePtr;
+ int TotalSize;
+ int CurrSpan;
+ int Offsets[CHUNKS];
+
+ ImSpanAllocator() { memset(this, 0, sizeof(*this)); }
+ inline void ReserveBytes(int n, size_t sz) { IM_ASSERT(n == CurrSpan && n < CHUNKS); IM_UNUSED(n); Offsets[CurrSpan++] = TotalSize; TotalSize += (int)sz; }
+ inline int GetArenaSizeInBytes() { return TotalSize; }
+ inline void SetArenaBasePtr(void* base_ptr) { BasePtr = (char*)base_ptr; }
+ inline void* GetSpanPtrBegin(int n) { IM_ASSERT(n >= 0 && n < CHUNKS && CurrSpan == CHUNKS); return (void*)(BasePtr + Offsets[n]); }
+ inline void* GetSpanPtrEnd(int n) { IM_ASSERT(n >= 0 && n < CHUNKS && CurrSpan == CHUNKS); return (n + 1 < CHUNKS) ? BasePtr + Offsets[n + 1] : (void*)(BasePtr + TotalSize); }
+ template
+ inline void GetSpan(int n, ImSpan* span) { span->set((T*)GetSpanPtrBegin(n), (T*)GetSpanPtrEnd(n)); }
+};
+
+// Helper: ImPool<>
+// Basic keyed storage for contiguous instances, slow/amortized insertion, O(1) indexable, O(Log N) queries by ID over a dense/hot buffer,
// Honor constructor/destructor. Add/remove invalidate all pointers. Indexes have the same lifetime as the associated object.
typedef int ImPoolIdx;
template
struct IMGUI_API ImPool
{
- ImVector Data; // Contiguous data
+ ImVector Buf; // Contiguous data
ImGuiStorage Map; // ID->Index
ImPoolIdx FreeIdx; // Next free idx to use
ImPool() { FreeIdx = 0; }
~ImPool() { Clear(); }
- T* GetByKey(ImGuiID key) { int idx = Map.GetInt(key, -1); return (idx != -1) ? &Data[idx] : NULL; }
- T* GetByIndex(ImPoolIdx n) { return &Data[n]; }
- ImPoolIdx GetIndex(const T* p) const { IM_ASSERT(p >= Data.Data && p < Data.Data + Data.Size); return (ImPoolIdx)(p - Data.Data); }
- T* GetOrAddByKey(ImGuiID key) { int* p_idx = Map.GetIntRef(key, -1); if (*p_idx != -1) return &Data[*p_idx]; *p_idx = FreeIdx; return Add(); }
- bool Contains(const T* p) const { return (p >= Data.Data && p < Data.Data + Data.Size); }
- void Clear() { for (int n = 0; n < Map.Data.Size; n++) { int idx = Map.Data[n].val_i; if (idx != -1) Data[idx].~T(); } Map.Clear(); Data.clear(); FreeIdx = 0; }
- T* Add() { int idx = FreeIdx; if (idx == Data.Size) { Data.resize(Data.Size + 1); FreeIdx++; } else { FreeIdx = *(int*)&Data[idx]; } IM_PLACEMENT_NEW(&Data[idx]) T(); return &Data[idx]; }
+ T* GetByKey(ImGuiID key) { int idx = Map.GetInt(key, -1); return (idx != -1) ? &Buf[idx] : NULL; }
+ T* GetByIndex(ImPoolIdx n) { return &Buf[n]; }
+ ImPoolIdx GetIndex(const T* p) const { IM_ASSERT(p >= Buf.Data && p < Buf.Data + Buf.Size); return (ImPoolIdx)(p - Buf.Data); }
+ T* GetOrAddByKey(ImGuiID key) { int* p_idx = Map.GetIntRef(key, -1); if (*p_idx != -1) return &Buf[*p_idx]; *p_idx = FreeIdx; return Add(); }
+ bool Contains(const T* p) const { return (p >= Buf.Data && p < Buf.Data + Buf.Size); }
+ void Clear() { for (int n = 0; n < Map.Data.Size; n++) { int idx = Map.Data[n].val_i; if (idx != -1) Buf[idx].~T(); } Map.Clear(); Buf.clear(); FreeIdx = 0; }
+ T* Add() { int idx = FreeIdx; if (idx == Buf.Size) { Buf.resize(Buf.Size + 1); FreeIdx++; } else { FreeIdx = *(int*)&Buf[idx]; } IM_PLACEMENT_NEW(&Buf[idx]) T(); return &Buf[idx]; }
void Remove(ImGuiID key, const T* p) { Remove(key, GetIndex(p)); }
- void Remove(ImGuiID key, ImPoolIdx idx) { Data[idx].~T(); *(int*)&Data[idx] = FreeIdx; FreeIdx = idx; Map.SetInt(key, -1); }
- void Reserve(int capacity) { Data.reserve(capacity); Map.Data.reserve(capacity); }
- int GetSize() const { return Data.Size; }
+ void Remove(ImGuiID key, ImPoolIdx idx) { Buf[idx].~T(); *(int*)&Buf[idx] = FreeIdx; FreeIdx = idx; Map.SetInt(key, -1); }
+ void Reserve(int capacity) { Buf.reserve(capacity); Map.Data.reserve(capacity); }
+ int GetSize() const { return Buf.Size; }
+};
+
+// Helper: ImChunkStream<>
+// Build and iterate a contiguous stream of variable-sized structures.
+// This is used by Settings to store persistent data while reducing allocation count.
+// We store the chunk size first, and align the final size on 4 bytes boundaries (this what the '(X + 3) & ~3' statement is for)
+// The tedious/zealous amount of casting is to avoid -Wcast-align warnings.
+template
+struct IMGUI_API ImChunkStream
+{
+ ImVector Buf;
+
+ void clear() { Buf.clear(); }
+ bool empty() const { return Buf.Size == 0; }
+ int size() const { return Buf.Size; }
+ T* alloc_chunk(size_t sz) { size_t HDR_SZ = 4; sz = ((HDR_SZ + sz) + 3u) & ~3u; int off = Buf.Size; Buf.resize(off + (int)sz); ((int*)(void*)(Buf.Data + off))[0] = (int)sz; return (T*)(void*)(Buf.Data + off + (int)HDR_SZ); }
+ T* begin() { size_t HDR_SZ = 4; if (!Buf.Data) return NULL; return (T*)(void*)(Buf.Data + HDR_SZ); }
+ T* next_chunk(T* p) { size_t HDR_SZ = 4; IM_ASSERT(p >= begin() && p < end()); p = (T*)(void*)((char*)(void*)p + chunk_size(p)); if (p == (T*)(void*)((char*)end() + HDR_SZ)) return (T*)0; IM_ASSERT(p < end()); return p; }
+ int chunk_size(const T* p) { return ((const int*)p)[-1]; }
+ T* end() { return (T*)(void*)(Buf.Data + Buf.Size); }
+ int offset_from_ptr(const T* p) { IM_ASSERT(p >= begin() && p < end()); const ptrdiff_t off = (const char*)p - Buf.Data; return (int)off; }
+ T* ptr_from_offset(int off) { IM_ASSERT(off >= 4 && off < Buf.Size); return (T*)(void*)(Buf.Data + off); }
+ void swap(ImChunkStream& rhs) { rhs.Buf.swap(Buf); }
+
};
//-----------------------------------------------------------------------------
-// Misc data structures
+// [SECTION] ImDrawList support
//-----------------------------------------------------------------------------
-enum ImGuiButtonFlags_
+// ImDrawList: Helper function to calculate a circle's segment count given its radius and a "maximum error" value.
+// FIXME: the minimum number of auto-segment may be undesirably high for very small radiuses (e.g. 1.0f)
+#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MIN 12
+#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX 512
+#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(_RAD,_MAXERROR) ImClamp((int)((IM_PI * 2.0f) / ImAcos(((_RAD) - (_MAXERROR)) / (_RAD))), IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MIN, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX)
+
+// ImDrawList: You may set this to higher values (e.g. 2 or 3) to increase tessellation of fast rounded corners path.
+#ifndef IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER
+#define IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER 1
+#endif
+
+// Data shared between all ImDrawList instances
+// You may want to create your own instance of this if you want to use ImDrawList completely without ImGui. In that case, watch out for future changes to this structure.
+struct IMGUI_API ImDrawListSharedData
{
- ImGuiButtonFlags_None = 0,
- ImGuiButtonFlags_Repeat = 1 << 0, // hold to repeat
- ImGuiButtonFlags_PressedOnClickRelease = 1 << 1, // [Default] return true on click + release on same item
- ImGuiButtonFlags_PressedOnClick = 1 << 2, // return true on click (default requires click+release)
- ImGuiButtonFlags_PressedOnRelease = 1 << 3, // return true on release (default requires click+release)
- ImGuiButtonFlags_PressedOnDoubleClick = 1 << 4, // return true on double-click (default requires click+release)
- ImGuiButtonFlags_FlattenChildren = 1 << 5, // allow interactions even if a child window is overlapping
- ImGuiButtonFlags_AllowItemOverlap = 1 << 6, // require previous frame HoveredId to either match id or be null before being usable, use along with SetItemAllowOverlap()
- ImGuiButtonFlags_DontClosePopups = 1 << 7, // disable automatically closing parent popup on press // [UNUSED]
- ImGuiButtonFlags_Disabled = 1 << 8, // disable interactions
- 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_NoNavFocus = 1 << 13, // don't override navigation focus when activated
- ImGuiButtonFlags_NoHoveredOnNav = 1 << 14 // don't report as hovered when navigated on
+ ImVec2 TexUvWhitePixel; // UV of white pixel in the atlas
+ ImFont* Font; // Current/default font (optional, for simplified AddText overload)
+ float FontSize; // Current/default font size (optional, for simplified AddText overload)
+ float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo()
+ float CircleSegmentMaxError; // Number of circle segments to use per pixel of radius for AddCircle() etc
+ ImVec4 ClipRectFullscreen; // Value for PushClipRectFullscreen()
+ ImDrawListFlags InitialFlags; // Initial flags at the beginning of the frame (it is possible to alter flags on a per-drawlist basis afterwards)
+
+ // [Internal] Lookup tables
+ ImVec2 ArcFastVtx[12 * IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER]; // FIXME: Bake rounded corners fill/borders in atlas
+ ImU8 CircleSegmentCounts[64]; // Precomputed segment count for given radius before we calculate it dynamically (to avoid calculation overhead)
+ const ImVec4* TexUvLines; // UV of anti-aliased lines in the atlas
+
+ ImDrawListSharedData();
+ void SetCircleSegmentMaxError(float max_error);
};
-enum ImGuiSliderFlags_
+struct ImDrawDataBuilder
{
- ImGuiSliderFlags_None = 0,
- ImGuiSliderFlags_Vertical = 1 << 0
+ ImVector 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();
};
-enum ImGuiDragFlags_
+//-----------------------------------------------------------------------------
+// [SECTION] Widgets support: flags, enums, data structures
+//-----------------------------------------------------------------------------
+
+// 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_
{
- ImGuiDragFlags_None = 0,
- ImGuiDragFlags_Vertical = 1 << 0
+ ImGuiItemFlags_None = 0,
+ ImGuiItemFlags_NoTabStop = 1 << 0, // false
+ ImGuiItemFlags_ButtonRepeat = 1 << 1, // false // Button() will return true multiple times based on io.KeyRepeatDelay and io.KeyRepeatRate settings.
+ ImGuiItemFlags_Disabled = 1 << 2, // false // [BETA] Disable interactions but doesn't affect visuals yet. See github.com/ocornut/imgui/issues/211
+ ImGuiItemFlags_NoNav = 1 << 3, // false
+ ImGuiItemFlags_NoNavDefaultFocus = 1 << 4, // false
+ ImGuiItemFlags_SelectableDontClosePopup = 1 << 5, // false // MenuItem/Selectable() automatically closes current Popup window
+ ImGuiItemFlags_MixedValue = 1 << 6, // false // [BETA] Represent a mixed/indeterminate value, generally multi-selection where values differ. Currently only supported by Checkbox() (later should support all sorts of widgets)
+ ImGuiItemFlags_ReadOnly = 1 << 7, // false // [ALPHA] Allow hovering interactions but underlying value is not changed.
+ ImGuiItemFlags_Default_ = 0
};
-enum ImGuiColumnsFlags_
+// Storage for LastItem data
+enum ImGuiItemStatusFlags_
{
- // Default: 0
- ImGuiColumnsFlags_None = 0,
- ImGuiColumnsFlags_NoBorder = 1 << 0, // Disable column dividers
- ImGuiColumnsFlags_NoResize = 1 << 1, // Disable resizing columns when clicking on the dividers
- ImGuiColumnsFlags_NoPreserveWidths = 1 << 2, // Disable column width preservation when adjusting columns
- ImGuiColumnsFlags_NoForceWithinWindow = 1 << 3, // Disable forcing columns to fit within window
- ImGuiColumnsFlags_GrowParentContentsSize= 1 << 4 // (WIP) Restore pre-1.51 behavior of extending the parent window contents size but _without affecting the columns width at all_. Will eventually remove.
+ ImGuiItemStatusFlags_None = 0,
+ ImGuiItemStatusFlags_HoveredRect = 1 << 0,
+ ImGuiItemStatusFlags_HasDisplayRect = 1 << 1,
+ ImGuiItemStatusFlags_Edited = 1 << 2, // Value exposed by item was edited in the current frame (should match the bool return value of most widgets)
+ ImGuiItemStatusFlags_ToggledSelection = 1 << 3, // Set when Selectable(), TreeNode() reports toggling a selection. We can't report "Selected" because reporting the change allows us to handle clipping with less issues.
+ ImGuiItemStatusFlags_ToggledOpen = 1 << 4, // Set when TreeNode() reports toggling their open state.
+ ImGuiItemStatusFlags_HasDeactivated = 1 << 5, // Set if the widget/group is able to provide data for the ImGuiItemStatusFlags_Deactivated flag.
+ ImGuiItemStatusFlags_Deactivated = 1 << 6 // Only valid if ImGuiItemStatusFlags_HasDeactivated is set.
+
+#ifdef IMGUI_ENABLE_TEST_ENGINE
+ , // [imgui_tests only]
+ ImGuiItemStatusFlags_Openable = 1 << 10, //
+ ImGuiItemStatusFlags_Opened = 1 << 11, //
+ ImGuiItemStatusFlags_Checkable = 1 << 12, //
+ ImGuiItemStatusFlags_Checked = 1 << 13 //
+#endif
+};
+
+// Extend ImGuiButtonFlags_
+enum ImGuiButtonFlagsPrivate_
+{
+ ImGuiButtonFlags_PressedOnClick = 1 << 4, // return true on click (mouse down event)
+ ImGuiButtonFlags_PressedOnClickRelease = 1 << 5, // [Default] return true on click + release on same item <-- this is what the majority of Button are using
+ ImGuiButtonFlags_PressedOnClickReleaseAnywhere = 1 << 6, // return true on click + release even if the release event is not done while hovering the item
+ ImGuiButtonFlags_PressedOnRelease = 1 << 7, // return true on release (default requires click+release)
+ ImGuiButtonFlags_PressedOnDoubleClick = 1 << 8, // return true on double-click (default requires click+release)
+ ImGuiButtonFlags_PressedOnDragDropHold = 1 << 9, // return true when held into while we are drag and dropping another item (used by e.g. tree nodes, collapsing headers)
+ ImGuiButtonFlags_Repeat = 1 << 10, // hold to repeat
+ ImGuiButtonFlags_FlattenChildren = 1 << 11, // allow interactions even if a child window is overlapping
+ ImGuiButtonFlags_AllowItemOverlap = 1 << 12, // require previous frame HoveredId to either match id or be null before being usable, use along with SetItemAllowOverlap()
+ ImGuiButtonFlags_DontClosePopups = 1 << 13, // disable automatically closing parent popup on press // [UNUSED]
+ ImGuiButtonFlags_Disabled = 1 << 14, // disable interactions
+ ImGuiButtonFlags_AlignTextBaseLine = 1 << 15, // 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 << 16, // disable mouse interaction if a key modifier is held
+ ImGuiButtonFlags_NoHoldingActiveId = 1 << 17, // don't set ActiveId while holding the mouse (ImGuiButtonFlags_PressedOnClick only)
+ ImGuiButtonFlags_NoNavFocus = 1 << 18, // don't override navigation focus when activated
+ ImGuiButtonFlags_NoHoveredOnFocus = 1 << 19, // don't report as hovered when nav focus is on this item
+ ImGuiButtonFlags_PressedOnMask_ = ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick | ImGuiButtonFlags_PressedOnDragDropHold,
+ ImGuiButtonFlags_PressedOnDefault_ = ImGuiButtonFlags_PressedOnClickRelease
+};
+
+// Extend ImGuiSliderFlags_
+enum ImGuiSliderFlagsPrivate_
+{
+ ImGuiSliderFlags_Vertical = 1 << 20, // Should this slider be orientated vertically?
+ ImGuiSliderFlags_ReadOnly = 1 << 21
};
// Extend ImGuiSelectableFlags_
enum ImGuiSelectableFlagsPrivate_
{
// NB: need to be in sync with last value of ImGuiSelectableFlags_
- ImGuiSelectableFlags_NoHoldingActiveID = 1 << 20,
- ImGuiSelectableFlags_PressedOnClick = 1 << 21,
- ImGuiSelectableFlags_PressedOnRelease = 1 << 22,
- ImGuiSelectableFlags_DrawFillAvailWidth = 1 << 23, // FIXME: We may be able to remove this (added in 6251d379 for menus)
- ImGuiSelectableFlags_DrawHoveredWhenHeld= 1 << 24, // Always show active when held, even is not hovered. This concept could probably be renamed/formalized somehow.
- ImGuiSelectableFlags_SetNavIdOnHover = 1 << 25
+ ImGuiSelectableFlags_NoHoldingActiveID = 1 << 20,
+ ImGuiSelectableFlags_SelectOnClick = 1 << 21, // Override button behavior to react on Click (default is Click+Release)
+ ImGuiSelectableFlags_SelectOnRelease = 1 << 22, // Override button behavior to react on Release (default is Click+Release)
+ ImGuiSelectableFlags_SpanAvailWidth = 1 << 23, // Span all avail width even if we declared less for layout purpose. FIXME: We may be able to remove this (added in 6251d379, 2bcafc86 for menus)
+ ImGuiSelectableFlags_DrawHoveredWhenHeld = 1 << 24, // Always show active when held, even is not hovered. This concept could probably be renamed/formalized somehow.
+ ImGuiSelectableFlags_SetNavIdOnHover = 1 << 25, // Set Nav/Focus ID on mouse hover (used by MenuItem)
+ ImGuiSelectableFlags_NoPadWithHalfSpacing = 1 << 26 // Disable padding each side with ItemSpacing * 0.5f
};
// Extend ImGuiTreeNodeFlags_
@@ -392,47 +755,18 @@ enum ImGuiSeparatorFlags_
ImGuiSeparatorFlags_SpanAllColumns = 1 << 2
};
-// 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_None = 0,
- ImGuiItemFlags_NoTabStop = 1 << 0, // false
- ImGuiItemFlags_ButtonRepeat = 1 << 1, // false // Button() will return true multiple times based on io.KeyRepeatDelay and io.KeyRepeatRate settings.
- ImGuiItemFlags_Disabled = 1 << 2, // false // [BETA] Disable interactions but doesn't affect visuals yet. See github.com/ocornut/imgui/issues/211
- ImGuiItemFlags_NoNav = 1 << 3, // false
- ImGuiItemFlags_NoNavDefaultFocus = 1 << 4, // false
- ImGuiItemFlags_SelectableDontClosePopup = 1 << 5, // false // MenuItem/Selectable() automatically closes current Popup window
- ImGuiItemFlags_MixedValue = 1 << 6, // false // [BETA] Represent a mixed/indeterminate value, generally multi-selection where values differ. Currently only supported by Checkbox() (later should support all sorts of widgets)
- ImGuiItemFlags_Default_ = 0
-};
-
-// Storage for LastItem data
-enum ImGuiItemStatusFlags_
-{
- ImGuiItemStatusFlags_None = 0,
- ImGuiItemStatusFlags_HoveredRect = 1 << 0,
- ImGuiItemStatusFlags_HasDisplayRect = 1 << 1,
- ImGuiItemStatusFlags_Edited = 1 << 2, // Value exposed by item was edited in the current frame (should match the bool return value of most widgets)
- ImGuiItemStatusFlags_ToggledSelection = 1 << 3, // Set when Selectable(), TreeNode() reports toggling a selection. We can't report "Selected" because reporting the change allows us to handle clipping with less issues.
- ImGuiItemStatusFlags_HasDeactivated = 1 << 4, // Set if the widget/group is able to provide data for the ImGuiItemStatusFlags_Deactivated flag.
- ImGuiItemStatusFlags_Deactivated = 1 << 5 // Only valid if ImGuiItemStatusFlags_HasDeactivated is set.
-
-#ifdef IMGUI_ENABLE_TEST_ENGINE
- , // [imgui_tests only]
- ImGuiItemStatusFlags_Openable = 1 << 10, //
- ImGuiItemStatusFlags_Opened = 1 << 11, //
- ImGuiItemStatusFlags_Checkable = 1 << 12, //
- ImGuiItemStatusFlags_Checked = 1 << 13 //
-#endif
-};
-
enum ImGuiTextFlags_
{
ImGuiTextFlags_None = 0,
ImGuiTextFlags_NoWidthForLargeClippedText = 1 << 0
};
+enum ImGuiTooltipFlags_
+{
+ ImGuiTooltipFlags_None = 0,
+ ImGuiTooltipFlags_OverridePreviousTooltip = 1 << 0 // Override will clear/ignore previously submitted tooltip (defaults to append)
+};
+
// FIXME: this is in development, not exposed/functional as a generic feature yet.
// Horizontal/Vertical enums are fixed to 0/1 so they may be used to index ImVec2
enum ImGuiLayoutType_
@@ -531,70 +865,32 @@ enum ImGuiNavLayer
enum ImGuiPopupPositionPolicy
{
ImGuiPopupPositionPolicy_Default,
- ImGuiPopupPositionPolicy_ComboBox
+ ImGuiPopupPositionPolicy_ComboBox,
+ ImGuiPopupPositionPolicy_Tooltip
};
-// 1D vector (this odd construct is used to facilitate the transition between 1D and 2D, and the maintenance of some branches/patches)
-struct ImVec1
+struct ImGuiDataTypeTempStorage
{
- float x;
- ImVec1() { x = 0.0f; }
- ImVec1(float _x) { x = _x; }
-};
-
-// 2D vector (half-size integer)
-struct ImVec2ih
-{
- short x, y;
- ImVec2ih() { x = y = 0; }
- ImVec2ih(short _x, short _y) { x = _x; y = _y; }
- explicit ImVec2ih(const ImVec2& rhs) { x = (short)rhs.x; y = (short)rhs.y; }
-};
-
-// 2D axis aligned bounding-box
-// NB: we can't rely on ImVec2 math operators being available here
-struct IMGUI_API ImRect
-{
- ImVec2 Min; // Upper-left
- ImVec2 Max; // Lower-right
-
- ImRect() : Min(FLT_MAX,FLT_MAX), Max(-FLT_MAX,-FLT_MAX) {}
- ImRect(const ImVec2& min, const ImVec2& max) : Min(min), Max(max) {}
- 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& 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& d) { Min.x += d.x; Min.y += d.y; Max.x += d.x; Max.y += d.y; }
- void TranslateX(float dx) { Min.x += dx; Max.x += dx; }
- void TranslateY(float dy) { Min.y += dy; Max.y += dy; }
- 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 = IM_FLOOR(Min.x); Min.y = IM_FLOOR(Min.y); Max.x = IM_FLOOR(Max.x); Max.y = IM_FLOOR(Max.y); }
- bool IsInverted() const { return Min.x > Max.x || Min.y > Max.y; }
+ ImU8 Data[8]; // Can fit any data up to ImGuiDataType_COUNT
};
// Type information associated to one ImGuiDataType. Retrieve with DataTypeGetInfo().
struct ImGuiDataTypeInfo
{
- size_t Size; // Size in byte
+ size_t Size; // Size in bytes
+ const char* Name; // Short descriptive name for the type, for debugging
const char* PrintFmt; // Default printf format for the type
const char* ScanFmt; // Default scanf format for the type
};
+// Extend ImGuiDataType_
+enum ImGuiDataTypePrivate_
+{
+ ImGuiDataType_String = ImGuiDataType_COUNT + 1,
+ ImGuiDataType_Pointer,
+ ImGuiDataType_ID
+};
+
// Stacked color modifier, backup of modified data so we can restore it
struct ImGuiColorMod
{
@@ -615,6 +911,7 @@ struct ImGuiStyleMod
// Stacked storage data for BeginGroup()/EndGroup()
struct ImGuiGroupData
{
+ ImGuiID WindowID;
ImVec2 BackupCursorPos;
ImVec2 BackupCursorMaxPos;
ImVec1 BackupIndent;
@@ -633,17 +930,18 @@ struct IMGUI_API ImGuiMenuColumns
float Width, NextWidth;
float Pos[3], NextWidths[3];
- ImGuiMenuColumns();
+ ImGuiMenuColumns() { memset(this, 0, sizeof(*this)); }
void Update(int count, float spacing, bool clear);
float DeclColumns(float w0, float w1, float w2);
- float CalcExtraSpace(float avail_w);
+ float CalcExtraSpace(float avail_w) const;
};
// Internal state of the currently focused/edited text input box
+// For a given item ID, access with ImGui::GetInputTextState()
struct IMGUI_API ImGuiInputTextState
{
ImGuiID ID; // widget id owning the text state
- int CurLenW, CurLenA; // we need to maintain our buffer length in both UTF-8 and wchar format. UTF-8 len is valid even if TextA is not.
+ int CurLenW, CurLenA; // we need to maintain our buffer length in both UTF-8 and wchar format. UTF-8 length is valid even if TextA is not.
ImVector TextW; // edit buffer, we need to persist but can't guarantee the persistence of the user-provided buffer. so we copy into own buffer.
ImVector TextA; // temporary UTF8 buffer for callbacks and other operations. this is not updated in every code-path! size=capacity.
ImVector InitialTextA; // backup of end-user buffer at the time of focus (in UTF-8, unaltered)
@@ -654,6 +952,7 @@ struct IMGUI_API ImGuiInputTextState
float CursorAnim; // timer for cursor blink, reset on every user action so the cursor reappears immediately
bool CursorFollow; // set when we want scrolling to follow the current cursor position (not always!)
bool SelectedAllMouseLock; // after a double-click to select all, we ignore further mouse drags to update selection
+ bool Edited; // edited this frame
ImGuiInputTextFlags UserFlags; // Temporarily set while we call user's callback
ImGuiInputTextCallback UserCallback; // "
void* UserCallbackData; // "
@@ -673,35 +972,6 @@ struct IMGUI_API ImGuiInputTextState
void SelectAll() { Stb.select_start = 0; Stb.cursor = Stb.select_end = CurLenW; Stb.has_preferred_x = 0; }
};
-// Windows data saved in imgui.ini file
-struct ImGuiWindowSettings
-{
- char* Name;
- ImGuiID ID;
- ImVec2ih Pos; // NB: Settings position are stored RELATIVE to the viewport! Whereas runtime ones are absolute positions.
- ImVec2ih Size;
- ImVec2ih ViewportPos;
- ImGuiID ViewportId;
- ImGuiID DockId; // ID of last known DockNode (even if the DockNode is invisible because it has only 1 active window), or 0 if none.
- ImGuiID ClassId; // ID of window class if specified
- short DockOrder; // Order of the last time the window was visible within its DockNode. This is used to reorder windows that are reappearing on the same frame. Same value between windows that were active and windows that were none are possible.
- bool Collapsed;
-
- ImGuiWindowSettings() { Name = NULL; ID = 0; Pos = Size = ViewportPos = ImVec2ih(0, 0); ViewportId = DockId = ClassId = 0; DockOrder = -1; Collapsed = false; }
-};
-
-struct ImGuiSettingsHandler
-{
- const char* TypeName; // Short description stored in .ini file. Disallowed characters: '[' ']'
- ImGuiID TypeHash; // == ImHashStr(TypeName)
- void* (*ReadOpenFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, const char* name); // Read: Called when entering into a new ini entry e.g. "[Window][Name]"
- void (*ReadLineFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, void* entry, const char* line); // Read: Called for every line of text within an ini entry
- void (*WriteAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* out_buf); // Write: Output every entries into 'out_buf'
- void* UserData;
-
- ImGuiSettingsHandler() { memset(this, 0, sizeof(*this)); }
-};
-
// Storage for current popup stack
struct ImGuiPopupData
{
@@ -713,119 +983,21 @@ struct ImGuiPopupData
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
- ImGuiPopupData() { PopupId = 0; Window = SourceWindow = NULL; OpenFrameCount = -1; OpenParentId = 0; }
-};
-
-struct ImGuiColumnData
-{
- float OffsetNorm; // Column start offset, normalized 0.0 (far left) -> 1.0 (far right)
- float OffsetNormBeforeResize;
- ImGuiColumnsFlags Flags; // Not exposed
- ImRect ClipRect;
-
- ImGuiColumnData() { OffsetNorm = OffsetNormBeforeResize = 0.0f; Flags = ImGuiColumnsFlags_None; }
-};
-
-struct ImGuiColumns
-{
- ImGuiID ID;
- ImGuiColumnsFlags Flags;
- bool IsFirstFrame;
- bool IsBeingResized;
- int Current;
- int Count;
- float OffMinX, OffMaxX; // Offsets from HostWorkRect.Min.x
- float LineMinY, LineMaxY;
- float HostCursorPosY; // Backup of CursorPos at the time of BeginColumns()
- float HostCursorMaxPosX; // Backup of CursorMaxPos at the time of BeginColumns()
- ImRect HostClipRect; // Backup of ClipRect at the time of BeginColumns()
- ImRect HostWorkRect; // Backup of WorkRect at the time of BeginColumns()
- ImVector Columns;
-
- ImGuiColumns() { Clear(); }
- void Clear()
- {
- ID = 0;
- Flags = ImGuiColumnsFlags_None;
- IsFirstFrame = false;
- IsBeingResized = false;
- Current = 0;
- Count = 1;
- OffMinX = OffMaxX = 0.0f;
- LineMinY = LineMaxY = 0.0f;
- HostCursorPosY = 0.0f;
- HostCursorMaxPosX = 0.0f;
- Columns.clear();
- }
-};
-
-// Data shared between all ImDrawList instances
-struct IMGUI_API ImDrawListSharedData
-{
- ImVec2 TexUvWhitePixel; // UV of white pixel in the atlas
- ImFont* Font; // Current/default font (optional, for simplified AddText overload)
- float FontSize; // Current/default font size (optional, for simplified AddText overload)
- float CurveTessellationTol;
- ImVec4 ClipRectFullscreen; // Value for PushClipRectFullscreen()
- ImDrawListFlags InitialFlags; // Initial flags at the beginning of the frame (it is possible to alter flags on a per-drawlist basis afterwards)
-
- // Const data
- // FIXME: Bake rounded corners fill/borders in atlas
- ImVec2 CircleVtx12[12];
-
- ImDrawListSharedData();
-};
-
-struct ImDrawDataBuilder
-{
- ImVector 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();
-};
-
-// ImGuiViewport Private/Internals fields (cardinal sin: we are using inheritance!)
-// Note that every instance of ImGuiViewport is in fact a ImGuiViewportP.
-struct ImGuiViewportP : public ImGuiViewport
-{
- int Idx;
- int LastFrameActive; // Last frame number this viewport was activated by a window
- int LastFrameDrawLists[2]; // Last frame number the background (0) and foreground (1) draw lists were used
- int LastFrontMostStampCount; // Last stamp number from when a window hosted by this viewport was made front-most (by comparing this value between two viewport we have an implicit viewport z-order
- ImGuiID LastNameHash;
- ImVec2 LastPos;
- float Alpha; // Window opacity (when dragging dockable windows/viewports we make them transparent)
- float LastAlpha;
- short PlatformMonitor;
- bool PlatformWindowCreated;
- ImGuiWindow* Window; // Set when the viewport is owned by a window (and ImGuiViewportFlags_CanHostOtherWindows is NOT set)
- ImDrawList* DrawLists[2]; // Convenience background (0) and foreground (1) draw lists. We use them to draw software mouser cursor when io.MouseDrawCursor is set and to draw most debug overlays.
- ImDrawData DrawDataP;
- ImDrawDataBuilder DrawDataBuilder;
- ImVec2 LastPlatformPos;
- ImVec2 LastPlatformSize;
- ImVec2 LastRendererSize;
-
- ImGuiViewportP() { Idx = -1; LastFrameActive = LastFrameDrawLists[0] = LastFrameDrawLists[1] = LastFrontMostStampCount = -1; LastNameHash = 0; Alpha = LastAlpha = 1.0f; PlatformMonitor = -1; PlatformWindowCreated = false; Window = NULL; DrawLists[0] = DrawLists[1] = NULL; LastPlatformPos = LastPlatformSize = LastRendererSize = ImVec2(FLT_MAX, FLT_MAX); }
- ~ImGuiViewportP() { if (DrawLists[0]) IM_DELETE(DrawLists[0]); if (DrawLists[1]) IM_DELETE(DrawLists[1]); }
- ImRect GetRect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); }
- ImVec2 GetCenter() const { return ImVec2(Pos.x + Size.x * 0.5f, Pos.y + Size.y * 0.5f); }
- void ClearRequestFlags() { PlatformRequestClose = PlatformRequestMove = PlatformRequestResize = false; }
+ ImGuiPopupData() { memset(this, 0, sizeof(*this)); OpenFrameCount = -1; }
};
struct ImGuiNavMoveResult
{
- ImGuiID ID; // Best candidate
- ImGuiID SelectScopeId;// Best candidate window current selectable group ID
- 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
+ ImGuiWindow* Window; // Best candidate window
+ ImGuiID ID; // Best candidate ID
+ ImGuiID FocusScopeId; // Best candidate focus scope ID
+ 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 = SelectScopeId = 0; Window = NULL; DistBox = DistCenter = DistAxial = FLT_MAX; RectRel = ImRect(); }
+ void Clear() { Window = NULL; ID = FocusScopeId = 0; DistBox = DistCenter = DistAxial = FLT_MAX; RectRel = ImRect(); }
};
enum ImGuiNextWindowDataFlags_
@@ -838,9 +1010,7 @@ enum ImGuiNextWindowDataFlags_
ImGuiNextWindowDataFlags_HasSizeConstraint = 1 << 4,
ImGuiNextWindowDataFlags_HasFocus = 1 << 5,
ImGuiNextWindowDataFlags_HasBgAlpha = 1 << 6,
- ImGuiNextWindowDataFlags_HasViewport = 1 << 7,
- ImGuiNextWindowDataFlags_HasDock = 1 << 8,
- ImGuiNextWindowDataFlags_HasWindowClass = 1 << 9
+ ImGuiNextWindowDataFlags_HasScroll = 1 << 7
};
// Storage for SetNexWindow** functions
@@ -850,20 +1020,16 @@ struct ImGuiNextWindowData
ImGuiCond PosCond;
ImGuiCond SizeCond;
ImGuiCond CollapsedCond;
- ImGuiCond DockCond;
ImVec2 PosVal;
ImVec2 PosPivotVal;
ImVec2 SizeVal;
ImVec2 ContentSizeVal;
- bool PosUndock;
+ ImVec2 ScrollVal;
bool CollapsedVal;
ImRect SizeConstraintRect;
ImGuiSizeCallback SizeCallback;
void* SizeCallbackUserData;
- float BgAlphaVal;
- ImGuiID ViewportId;
- ImGuiID DockId;
- ImGuiWindowClass WindowClass;
+ float BgAlphaVal; // Override background alpha
ImVec2 MenuBarOffsetMinVal; // *Always on* This is not exposed publicly, so we don't clear it.
ImGuiNextWindowData() { memset(this, 0, sizeof(*this)); }
@@ -880,138 +1046,213 @@ enum ImGuiNextItemDataFlags_
struct ImGuiNextItemData
{
ImGuiNextItemDataFlags Flags;
- float Width; // Set by SetNextItemWidth().
- bool OpenVal; // Set by SetNextItemOpen() function.
+ float Width; // Set by SetNextItemWidth()
+ ImGuiID FocusScopeId; // Set by SetNextItemMultiSelectData() (!= 0 signify value has been set, so it's an alternate version of HasSelectionData, we don't use Flags for this because they are cleared too early. This is mostly used for debugging)
ImGuiCond OpenCond;
+ bool OpenVal; // Set by SetNextItemOpen()
ImGuiNextItemData() { memset(this, 0, sizeof(*this)); }
- inline void ClearFlags() { Flags = ImGuiNextItemDataFlags_None; }
+ inline void ClearFlags() { Flags = ImGuiNextItemDataFlags_None; } // Also cleared manually by ItemAdd()!
};
-//-----------------------------------------------------------------------------
-// Docking, Tabs
-//-----------------------------------------------------------------------------
-
struct ImGuiShrinkWidthItem
{
- int Index;
- float Width;
+ int Index;
+ float Width;
};
struct ImGuiPtrOrIndex
{
- void* Ptr; // Either field can be set, not both. e.g. Dock node tab bars are loose while BeginTabBar() ones are in a pool.
- int Index; // Usually index in a main pool.
+ void* Ptr; // Either field can be set, not both. e.g. Dock node tab bars are loose while BeginTabBar() ones are in a pool.
+ int Index; // Usually index in a main pool.
- ImGuiPtrOrIndex(void* ptr) { Ptr = ptr; Index = -1; }
- ImGuiPtrOrIndex(int index) { Ptr = NULL; Index = index; }
-};
-
-// Extend ImGuiDockNodeFlags_
-enum ImGuiDockNodeFlagsPrivate_
-{
- // [Internal]
- ImGuiDockNodeFlags_DockSpace = 1 << 10, // Local, Saved // A dockspace is a node that occupy space within an existing user window. Otherwise the node is floating and create its own window.
- ImGuiDockNodeFlags_CentralNode = 1 << 11, // Local, Saved //
- ImGuiDockNodeFlags_NoTabBar = 1 << 12, // Local, Saved // Tab bar is completely unavailable. No triangle in the corner to enable it back.
- ImGuiDockNodeFlags_HiddenTabBar = 1 << 13, // Local, Saved // Tab bar is hidden, with a triangle in the corner to show it again (NB: actual tab-bar instance may be destroyed as this is only used for single-window tab bar)
- ImGuiDockNodeFlags_NoWindowMenuButton = 1 << 14, // Local, Saved // Disable window/docking menu (that one that appears instead of the collapse button)
- ImGuiDockNodeFlags_NoCloseButton = 1 << 15, // Local, Saved //
- ImGuiDockNodeFlags_NoDocking = 1 << 16, // Local, Saved // Disable any form of docking in this dockspace or individual node. (On a whole dockspace, this pretty much defeat the purpose of using a dockspace at all). Note: when turned on, existing docked nodes will be preserved.
- ImGuiDockNodeFlags_SharedFlagsInheritMask_ = ~0,
- ImGuiDockNodeFlags_LocalFlagsMask_ = ImGuiDockNodeFlags_NoSplit | ImGuiDockNodeFlags_NoResize | ImGuiDockNodeFlags_AutoHideTabBar | ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar | ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton | ImGuiDockNodeFlags_NoDocking,
- ImGuiDockNodeFlags_LocalFlagsTransferMask_ = ImGuiDockNodeFlags_LocalFlagsMask_ & ~ImGuiDockNodeFlags_DockSpace, // When splitting those flags are moved to the inheriting child, never duplicated
- ImGuiDockNodeFlags_SavedFlagsMask_ = ImGuiDockNodeFlags_NoResize | ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar | ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton | ImGuiDockNodeFlags_NoDocking
-};
-
-// Store the source authority (dock node vs window) of a field
-enum ImGuiDataAuthority_
-{
- ImGuiDataAuthority_Auto,
- ImGuiDataAuthority_DockNode,
- ImGuiDataAuthority_Window
-};
-
-enum ImGuiDockNodeState
-{
- ImGuiDockNodeState_Unknown,
- ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow,
- ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing,
- ImGuiDockNodeState_HostWindowVisible
-};
-
-// sizeof() 116~160
-struct ImGuiDockNode
-{
- ImGuiID ID;
- ImGuiDockNodeFlags SharedFlags; // Flags shared by all nodes of a same dockspace hierarchy (inherited from the root node)
- ImGuiDockNodeFlags LocalFlags; // Flags specific to this node
- ImGuiDockNode* ParentNode;
- ImGuiDockNode* ChildNodes[2]; // [Split node only] Child nodes (left/right or top/bottom). Consider switching to an array.
- ImVector Windows; // Note: unordered list! Iterate TabBar->Tabs for user-order.
- ImGuiTabBar* TabBar;
- ImVec2 Pos; // Current position
- ImVec2 Size; // Current size
- ImVec2 SizeRef; // [Split node only] Last explicitly written-to size (overridden when using a splitter affecting the node), used to calculate Size.
- int SplitAxis; // [Split node only] Split axis (X or Y)
- ImGuiWindowClass WindowClass;
-
- ImGuiDockNodeState State;
- ImGuiWindow* HostWindow;
- ImGuiWindow* VisibleWindow; // Generally point to window which is ID is == SelectedTabID, but when CTRL+Tabbing this can be a different window.
- ImGuiDockNode* CentralNode; // [Root node only] Pointer to central node.
- ImGuiDockNode* OnlyNodeWithWindows; // [Root node only] Set when there is a single visible node within the hierarchy.
- int LastFrameAlive; // Last frame number the node was updated or kept alive explicitly with DockSpace() + ImGuiDockNodeFlags_KeepAliveOnly
- int LastFrameActive; // Last frame number the node was updated.
- int LastFrameFocused; // Last frame number the node was focused.
- ImGuiID LastFocusedNodeID; // [Root node only] Which of our child docking node (any ancestor in the hierarchy) was last focused.
- ImGuiID SelectedTabID; // [Leaf node only] Which of our tab/window is selected.
- ImGuiID WantCloseTabID; // [Leaf node only] Set when closing a specific tab/window.
- ImGuiDataAuthority AuthorityForPos :3;
- ImGuiDataAuthority AuthorityForSize :3;
- ImGuiDataAuthority AuthorityForViewport :3;
- bool IsVisible :1; // Set to false when the node is hidden (usually disabled as it has no active window)
- bool IsFocused :1;
- bool HasCloseButton :1;
- bool HasWindowMenuButton :1;
- bool EnableCloseButton :1;
- bool WantCloseAll :1; // Set when closing all tabs at once.
- bool WantLockSizeOnce :1;
- bool WantMouseMove :1; // After a node extraction we need to transition toward moving the newly created host window
- bool WantHiddenTabBarUpdate :1;
- bool WantHiddenTabBarToggle :1;
- bool MarkedForPosSizeWrite :1; // Update by DockNodeTreeUpdatePosSize() write-filtering
-
- ImGuiDockNode(ImGuiID id);
- ~ImGuiDockNode();
- bool IsRootNode() const { return ParentNode == NULL; }
- bool IsDockSpace() const { return (LocalFlags & ImGuiDockNodeFlags_DockSpace) != 0; }
- bool IsFloatingNode() const { return ParentNode == NULL && (LocalFlags & ImGuiDockNodeFlags_DockSpace) == 0; }
- bool IsCentralNode() const { return (LocalFlags & ImGuiDockNodeFlags_CentralNode) != 0; }
- bool IsHiddenTabBar() const { return (LocalFlags & ImGuiDockNodeFlags_HiddenTabBar) != 0; } // Hidden tab bar can be shown back by clicking the small triangle
- bool IsNoTabBar() const { return (LocalFlags & ImGuiDockNodeFlags_NoTabBar) != 0; } // Never show a tab bar
- bool IsSplitNode() const { return ChildNodes[0] != NULL; }
- bool IsLeafNode() const { return ChildNodes[0] == NULL; }
- bool IsEmpty() const { return ChildNodes[0] == NULL && Windows.Size == 0; }
- ImGuiDockNodeFlags GetMergedFlags() const { return SharedFlags | LocalFlags; }
- ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); }
+ ImGuiPtrOrIndex(void* ptr) { Ptr = ptr; Index = -1; }
+ ImGuiPtrOrIndex(int index) { Ptr = NULL; Index = index; }
};
//-----------------------------------------------------------------------------
-// Main imgui context
+// [SECTION] Columns support
+//-----------------------------------------------------------------------------
+
+// Flags for internal's BeginColumns(). Prefix using BeginTable() nowadays!
+enum ImGuiOldColumnFlags_
+{
+ ImGuiOldColumnFlags_None = 0,
+ ImGuiOldColumnFlags_NoBorder = 1 << 0, // Disable column dividers
+ ImGuiOldColumnFlags_NoResize = 1 << 1, // Disable resizing columns when clicking on the dividers
+ ImGuiOldColumnFlags_NoPreserveWidths = 1 << 2, // Disable column width preservation when adjusting columns
+ ImGuiOldColumnFlags_NoForceWithinWindow = 1 << 3, // Disable forcing columns to fit within window
+ ImGuiOldColumnFlags_GrowParentContentsSize = 1 << 4 // (WIP) Restore pre-1.51 behavior of extending the parent window contents size but _without affecting the columns width at all_. Will eventually remove.
+
+ // Obsolete names (will be removed)
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ , ImGuiColumnsFlags_None = ImGuiOldColumnFlags_None,
+ ImGuiColumnsFlags_NoBorder = ImGuiOldColumnFlags_NoBorder,
+ ImGuiColumnsFlags_NoResize = ImGuiOldColumnFlags_NoResize,
+ ImGuiColumnsFlags_NoPreserveWidths = ImGuiOldColumnFlags_NoPreserveWidths,
+ ImGuiColumnsFlags_NoForceWithinWindow = ImGuiOldColumnFlags_NoForceWithinWindow,
+ ImGuiColumnsFlags_GrowParentContentsSize = ImGuiOldColumnFlags_GrowParentContentsSize
+#endif
+};
+
+struct ImGuiOldColumnData
+{
+ float OffsetNorm; // Column start offset, normalized 0.0 (far left) -> 1.0 (far right)
+ float OffsetNormBeforeResize;
+ ImGuiOldColumnFlags Flags; // Not exposed
+ ImRect ClipRect;
+
+ ImGuiOldColumnData() { memset(this, 0, sizeof(*this)); }
+};
+
+struct ImGuiOldColumns
+{
+ ImGuiID ID;
+ ImGuiOldColumnFlags Flags;
+ bool IsFirstFrame;
+ bool IsBeingResized;
+ int Current;
+ int Count;
+ float OffMinX, OffMaxX; // Offsets from HostWorkRect.Min.x
+ float LineMinY, LineMaxY;
+ float HostCursorPosY; // Backup of CursorPos at the time of BeginColumns()
+ float HostCursorMaxPosX; // Backup of CursorMaxPos at the time of BeginColumns()
+ ImRect HostInitialClipRect; // Backup of ClipRect at the time of BeginColumns()
+ ImRect HostBackupClipRect; // Backup of ClipRect during PushColumnsBackground()/PopColumnsBackground()
+ ImRect HostBackupParentWorkRect;//Backup of WorkRect at the time of BeginColumns()
+ ImVector Columns;
+ ImDrawListSplitter Splitter;
+
+ ImGuiOldColumns() { memset(this, 0, sizeof(*this)); }
+};
+
+//-----------------------------------------------------------------------------
+// [SECTION] Multi-select support
+//-----------------------------------------------------------------------------
+
+#ifdef IMGUI_HAS_MULTI_SELECT
+//
+#endif // #ifdef IMGUI_HAS_MULTI_SELECT
+
+//-----------------------------------------------------------------------------
+// [SECTION] Docking support
+//-----------------------------------------------------------------------------
+
+#ifdef IMGUI_HAS_DOCK
+//
+#endif // #ifdef IMGUI_HAS_DOCK
+
+//-----------------------------------------------------------------------------
+// [SECTION] Viewport support
+//-----------------------------------------------------------------------------
+
+#ifdef IMGUI_HAS_VIEWPORT
+//
+#endif // #ifdef IMGUI_HAS_VIEWPORT
+
+//-----------------------------------------------------------------------------
+// [SECTION] Settings support
+//-----------------------------------------------------------------------------
+
+// Windows data saved in imgui.ini file
+// Because we never destroy or rename ImGuiWindowSettings, we can store the names in a separate buffer easily.
+// (this is designed to be stored in a ImChunkStream buffer, with the variable-length Name following our structure)
+struct ImGuiWindowSettings
+{
+ ImGuiID ID;
+ ImVec2ih Pos;
+ ImVec2ih Size;
+ bool Collapsed;
+ bool WantApply; // Set when loaded from .ini data (to enable merging/loading .ini data into an already running context)
+
+ ImGuiWindowSettings() { memset(this, 0, sizeof(*this)); }
+ char* GetName() { return (char*)(this + 1); }
+};
+
+struct ImGuiSettingsHandler
+{
+ const char* TypeName; // Short description stored in .ini file. Disallowed characters: '[' ']'
+ ImGuiID TypeHash; // == ImHashStr(TypeName)
+ void (*ClearAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Clear all settings data
+ void (*ReadInitFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Read: Called before reading (in registration order)
+ void* (*ReadOpenFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, const char* name); // Read: Called when entering into a new ini entry e.g. "[Window][Name]"
+ void (*ReadLineFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, void* entry, const char* line); // Read: Called for every line of text within an ini entry
+ void (*ApplyAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Read: Called after reading (in registration order)
+ void (*WriteAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* out_buf); // Write: Output every entries into 'out_buf'
+ void* UserData;
+
+ ImGuiSettingsHandler() { memset(this, 0, sizeof(*this)); }
+};
+
+//-----------------------------------------------------------------------------
+// [SECTION] Metrics, Debug
+//-----------------------------------------------------------------------------
+
+struct ImGuiMetricsConfig
+{
+ bool ShowWindowsRects;
+ bool ShowWindowsBeginOrder;
+ bool ShowTablesRects;
+ bool ShowDrawCmdMesh;
+ bool ShowDrawCmdBoundingBoxes;
+ int ShowWindowsRectsType;
+ int ShowTablesRectsType;
+
+ ImGuiMetricsConfig()
+ {
+ ShowWindowsRects = false;
+ ShowWindowsBeginOrder = false;
+ ShowTablesRects = false;
+ ShowDrawCmdMesh = true;
+ ShowDrawCmdBoundingBoxes = true;
+ ShowWindowsRectsType = -1;
+ ShowTablesRectsType = -1;
+ }
+};
+
+struct IMGUI_API ImGuiStackSizes
+{
+ short SizeOfIDStack;
+ short SizeOfColorStack;
+ short SizeOfStyleVarStack;
+ short SizeOfFontStack;
+ short SizeOfFocusScopeStack;
+ short SizeOfGroupStack;
+ short SizeOfBeginPopupStack;
+
+ ImGuiStackSizes() { memset(this, 0, sizeof(*this)); }
+ void SetToCurrentState();
+ void CompareWithCurrentState();
+};
+
+//-----------------------------------------------------------------------------
+// [SECTION] Generic context hooks
+//-----------------------------------------------------------------------------
+
+typedef void (*ImGuiContextHookCallback)(ImGuiContext* ctx, ImGuiContextHook* hook);
+enum ImGuiContextHookType { ImGuiContextHookType_NewFramePre, ImGuiContextHookType_NewFramePost, ImGuiContextHookType_EndFramePre, ImGuiContextHookType_EndFramePost, ImGuiContextHookType_RenderPre, ImGuiContextHookType_RenderPost, ImGuiContextHookType_Shutdown, ImGuiContextHookType_PendingRemoval_ };
+
+struct ImGuiContextHook
+{
+ ImGuiID HookId; // A unique ID assigned by AddContextHook()
+ ImGuiContextHookType Type;
+ ImGuiID Owner;
+ ImGuiContextHookCallback Callback;
+ void* UserData;
+
+ ImGuiContextHook() { memset(this, 0, sizeof(*this)); }
+};
+
+//-----------------------------------------------------------------------------
+// [SECTION] ImGuiContext (main imgui context)
//-----------------------------------------------------------------------------
struct ImGuiContext
{
bool Initialized;
- bool FrameScopeActive; // Set by NewFrame(), cleared by EndFrame()
- bool FrameScopePushedFallbackWindow; // Set by NewFrame(), cleared by EndFrame()
- bool FontAtlasOwnedByContext; // Io.Fonts-> is owned by the ImGuiContext and will be destructed along with it.
+ bool FontAtlasOwnedByContext; // IO.Fonts-> is owned by the ImGuiContext and will be destructed along with it.
ImGuiIO IO;
- ImGuiPlatformIO PlatformIO;
ImGuiStyle Style;
- ImGuiConfigFlags ConfigFlagsCurrFrame; // = g.IO.ConfigFlags at the time of NewFrame()
- ImGuiConfigFlags ConfigFlagsLastFrame;
ImFont* Font; // (Shortcut) == FontStack.empty() ? IO.Font : FontStack.back()
float FontSize; // (Shortcut) == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize(). Text height for current window.
float FontBaseSize; // (Shortcut) == IO.FontGlobalScale * Font->Scale * Font->FontSize. Base text height.
@@ -1019,29 +1260,38 @@ struct ImGuiContext
double Time;
int FrameCount;
int FrameCountEnded;
- int FrameCountPlatformEnded;
int FrameCountRendered;
+ bool WithinFrameScope; // Set by NewFrame(), cleared by EndFrame()
+ bool WithinFrameScopeWithImplicitWindow; // Set by NewFrame(), cleared by EndFrame() when the implicit debug window has been pushed
+ bool WithinEndChild; // Set within EndChild()
+ bool GcCompactAll; // Request full GC
+ bool TestEngineHookItems; // Will call test engine hooks: ImGuiTestEngineHook_ItemAdd(), ImGuiTestEngineHook_ItemInfo(), ImGuiTestEngineHook_Log()
+ ImGuiID TestEngineHookIdInfo; // Will call test engine hooks: ImGuiTestEngineHook_IdInfo() from GetID()
+ void* TestEngine; // Test engine user data
// Windows state
ImVector Windows; // Windows, sorted in display order, back to front
- ImVector WindowsFocusOrder; // Windows, sorted in focus order, back to front
- ImVector WindowsSortBuffer;
+ ImVector WindowsFocusOrder; // Windows, sorted in focus order, back to front. (FIXME: We could only store root windows here! Need to sort out the Docking equivalent which is RootWindowDockStop and is unfortunately a little more dynamic)
+ ImVector WindowsTempSortBuffer; // Temporary buffer used in EndFrame() to reorder windows so parents are kept before their child
ImVector CurrentWindowStack;
- ImGuiStorage WindowsById;
- int WindowsActiveCount;
- ImGuiWindow* CurrentWindow; // Being drawn into
- ImGuiWindow* HoveredWindow; // Will catch mouse inputs
- ImGuiWindow* HoveredRootWindow; // Will catch mouse inputs (for focus/move only)
+ ImGuiStorage WindowsById; // Map window's ImGuiID to ImGuiWindow*
+ int WindowsActiveCount; // Number of unique windows submitted by frame
+ ImGuiWindow* CurrentWindow; // Window being drawn into
+ ImGuiWindow* HoveredWindow; // Window the mouse is hovering. Will typically catch mouse inputs.
+ ImGuiWindow* HoveredRootWindow; // == HoveredWindow ? HoveredWindow->RootWindow : NULL, merely a shortcut to avoid null test in some situation.
ImGuiWindow* HoveredWindowUnderMovingWindow; // Hovered window ignoring MovingWindow. Only set if MovingWindow is set.
- ImGuiWindow* MovingWindow; // Track the window we clicked on (in order to preserve focus). The actually window that is moved is generally MovingWindow->RootWindow.
- ImGuiWindow* WheelingWindow;
+ ImGuiWindow* MovingWindow; // Track the window we clicked on (in order to preserve focus). The actual window that is moved is generally MovingWindow->RootWindow.
+ ImGuiWindow* WheelingWindow; // Track the window we started mouse-wheeling on. Until a timer elapse or mouse has moved, generally keep scrolling the same window even if during the course of scrolling the mouse ends up hovering a child window.
ImVec2 WheelingWindowRefMousePos;
float WheelingWindowTimer;
// Item/widgets state and tracking information
- ImGuiID HoveredId; // Hovered widget
- bool HoveredIdAllowOverlap;
+ ImGuiID HoveredId; // Hovered widget, filled during the frame
ImGuiID HoveredIdPreviousFrame;
+ bool HoveredIdAllowOverlap;
+ bool HoveredIdUsingMouseWheel; // Hovered widget will use mouse wheel. Blocks scrolling the underlying window.
+ bool HoveredIdPreviousFrameUsingMouseWheel;
+ bool HoveredIdDisabled; // At least one widget passed the rect test, but has been discarded by disabled flag or popup inhibit. May be true even if HoveredId == 0.
float HoveredIdTimer; // Measure contiguous hovering time
float HoveredIdNotActiveTimer; // Measure contiguous hovering time where the item has not been active
ImGuiID ActiveId; // Active widget
@@ -1049,20 +1299,22 @@ struct ImGuiContext
float ActiveIdTimer;
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)
+ bool ActiveIdNoClearOnFocusLoss; // Disable losing active id if the active id window gets unfocused.
bool ActiveIdHasBeenPressedBefore; // Track whether the active id led to a press (this is to allow changing between PressOnClick and PressOnRelease without pressing twice). Used by range_select branch.
bool ActiveIdHasBeenEditedBefore; // Was the value associated to the widget Edited over the course of the Active state.
bool ActiveIdHasBeenEditedThisFrame;
- ImU32 ActiveIdUsingNavDirMask; // Active widget will want to read those directional navigation requests (e.g. can activate a button and move away from it)
+ bool ActiveIdUsingMouseWheel; // Active widget will want to read mouse wheel. Blocks scrolling the underlying window.
+ ImU32 ActiveIdUsingNavDirMask; // Active widget will want to read those nav move requests (e.g. can activate a button and move away from it)
ImU32 ActiveIdUsingNavInputMask; // Active widget will want to read those nav inputs.
ImU64 ActiveIdUsingKeyInputMask; // Active widget will want to read those key inputs. When we grow the ImGuiKey enum we'll need to either to order the enum to make useful keys come first, either redesign this into e.g. a small array.
ImVec2 ActiveIdClickOffset; // Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior)
ImGuiWindow* ActiveIdWindow;
ImGuiInputSource ActiveIdSource; // Activating with mouse or nav (gamepad/keyboard)
+ int ActiveIdMouseButton;
ImGuiID ActiveIdPreviousFrame;
bool ActiveIdPreviousFrameIsAlive;
bool ActiveIdPreviousFrameHasBeenEditedBefore;
ImGuiWindow* ActiveIdPreviousFrameWindow;
-
ImGuiID LastActiveId; // Store the last non-zero ActiveId, useful for animation.
float LastActiveIdTimer; // Store the last non-zero ActiveId timer since the beginning of activation, useful for animation.
@@ -1071,90 +1323,104 @@ struct ImGuiContext
ImGuiNextItemData NextItemData; // Storage for SetNextItem** functions
// Shared stacks
- ImVector ColorModifiers; // Stack for PushStyleColor()/PopStyleColor()
- ImVector StyleModifiers; // Stack for PushStyleVar()/PopStyleVar()
- ImVector FontStack; // Stack for PushFont()/PopFont()
+ ImVector ColorStack; // Stack for PushStyleColor()/PopStyleColor() - inherited by Begin()
+ ImVector StyleVarStack; // Stack for PushStyleVar()/PopStyleVar() - inherited by Begin()
+ ImVector FontStack; // Stack for PushFont()/PopFont() - inherited by Begin()
+ ImVector FocusScopeStack; // Stack for PushFocusScope()/PopFocusScope() - not inherited by Begin(), unless child window
+ ImVectorItemFlagsStack; // Stack for PushItemFlag()/PopItemFlag() - inherited by Begin()
+ ImVectorGroupStack; // Stack for BeginGroup()/EndGroup() - not inherited by Begin()
ImVectorOpenPopupStack; // Which popups are open (persistent)
ImVectorBeginPopupStack; // Which level of BeginPopup() we are in (reset every frame)
- // Viewports
- ImVector Viewports; // Active viewports (always 1+, and generally 1 unless multi-viewports are enabled). Each viewports hold their copy of ImDrawData.
- ImGuiViewportP* CurrentViewport; // We track changes of viewport (happening in Begin) so we can call Platform_OnChangedViewport()
- ImGuiViewportP* MouseViewport;
- ImGuiViewportP* MouseLastHoveredViewport; // Last known viewport that was hovered by mouse (even if we are not hovering any viewport any more) + honoring the _NoInputs flag.
- ImGuiID PlatformLastFocusedViewport; // Record of last focused platform window/viewport, when this changes we stamp the viewport as front-most
- int ViewportFrontMostStampCount; // Every time the front-most window changes, we stamp its viewport with an incrementing counter
-
- // Navigation data (for gamepad/keyboard)
+ // Gamepad/keyboard Navigation
ImGuiWindow* NavWindow; // Focused window for navigation. Could be called 'FocusWindow'
ImGuiID NavId; // Focused item for navigation
+ ImGuiID NavFocusScopeId; // Identify a selection scope (selection code often wants to "clear other items" when landing on an item of the selection set)
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 NavJustMovedToMultiSelectScopeId; // Just navigated to this select scope id (result of a successfully MoveRequest).
+ ImGuiID NavJustMovedToFocusScopeId; // Just navigated to this focus scope id (result of a successfully MoveRequest).
+ ImGuiKeyModFlags NavJustMovedToKeyMods;
ImGuiID NavNextActivateId; // Set by ActivateItem(), queued until next frame.
ImGuiInputSource NavInputSource; // Keyboard or Gamepad mode? THIS WILL ONLY BE None or NavGamepad or NavKeyboard.
- ImRect NavScoringRectScreen; // Rectangle used for scoring, in screen space. Based of window->DC.NavRefRectRel[], modified for directional navigation scoring.
+ ImRect NavScoringRect; // Rectangle used for scoring, in screen space. Based of window->NavRectRel[], 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 top-most.
- ImGuiWindow* NavWindowingTargetAnim; // Record of last valid NavWindowingTarget until DimBgRatio and NavWindowingHighlightAlpha becomes 0.0f
- ImGuiWindow* NavWindowingList;
- float NavWindowingTimer;
- float NavWindowingHighlightAlpha;
- bool NavWindowingToggleLayer;
ImGuiNavLayer 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 NavIdIsAlive; // Nav widget has been seen this frame ~~ NavRectRel 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
+ ImGuiID NavInitResultId; // Init request result (first item of the window, or one for which SetItemDefaultFocus() was called)
+ ImRect NavInitResultRectRel; // Init request result rectangle (relative to parent window)
bool NavMoveRequest; // Move request for this frame
ImGuiNavMoveFlags NavMoveRequestFlags;
ImGuiNavForward NavMoveRequestForward; // None / ForwardQueued / ForwardActive (this is used to navigate sibling parent menus from a child menu)
+ ImGuiKeyModFlags NavMoveRequestKeyMods;
ImGuiDir NavMoveDir, NavMoveDirLast; // Direction of the move request (left/right/up/down), direction of the previous move request
ImGuiDir NavMoveClipDir; // FIXME-NAV: Describe the purpose of this better. Might want to rename?
ImGuiNavMoveResult NavMoveResultLocal; // Best move request candidate within NavWindow
ImGuiNavMoveResult NavMoveResultLocalVisibleSet; // Best move request candidate within NavWindow that are mostly visible (when using ImGuiNavMoveFlags_AlsoScoreVisibleSet flag)
ImGuiNavMoveResult NavMoveResultOther; // Best move request candidate within NavWindow's flattened hierarchy (when using ImGuiWindowFlags_NavFlattened flag)
+ ImGuiWindow* NavWrapRequestWindow; // Window which requested trying nav wrap-around.
+ ImGuiNavMoveFlags NavWrapRequestFlags; // Wrap-around operation flags.
- // Tabbing system (older than Nav, active even if Nav is disabled. FIXME-NAV: This needs a redesign!)
+ // Navigation: Windowing (CTRL+TAB for list, or Menu button + keys or directional pads to move/resize)
+ ImGuiWindow* NavWindowingTarget; // Target window when doing CTRL+Tab (or Pad Menu + FocusPrev/Next), this window is temporarily displayed top-most!
+ ImGuiWindow* NavWindowingTargetAnim; // Record of last valid NavWindowingTarget until DimBgRatio and NavWindowingHighlightAlpha becomes 0.0f, so the fade-out can stay on it.
+ ImGuiWindow* NavWindowingListWindow; // Internal window actually listing the CTRL+Tab contents
+ float NavWindowingTimer;
+ float NavWindowingHighlightAlpha;
+ bool NavWindowingToggleLayer;
+
+ // Legacy Focus/Tabbing system (older than Nav, active even if Nav is disabled, misnamed. FIXME-NAV: This needs a redesign!)
ImGuiWindow* FocusRequestCurrWindow; //
ImGuiWindow* FocusRequestNextWindow; //
- int FocusRequestCurrCounterAll; // Any item being requested for focus, stored as an index (we on layout to be stable between the frame pressing TAB and the next frame, semi-ouch)
- int FocusRequestCurrCounterTab; // Tab item being requested for focus, stored as an index
- int FocusRequestNextCounterAll; // Stored for next frame
- int FocusRequestNextCounterTab; // "
+ int FocusRequestCurrCounterRegular; // Any item being requested for focus, stored as an index (we on layout to be stable between the frame pressing TAB and the next frame, semi-ouch)
+ int FocusRequestCurrCounterTabStop; // Tab item being requested for focus, stored as an index
+ int FocusRequestNextCounterRegular; // Stored for next frame
+ int FocusRequestNextCounterTabStop; // "
bool FocusTabPressed; //
// Render
+ ImDrawData DrawData; // Main ImDrawData instance to pass render information to the user
+ ImDrawDataBuilder DrawDataBuilder;
float DimBgRatio; // 0.0..1.0 animation when fading in a dimming background (for modal window and CTRL+TAB list)
+ ImDrawList BackgroundDrawList; // First draw list to be rendered.
+ ImDrawList ForegroundDrawList; // Last draw list to be rendered. This is where we the render software mouse cursor (if io.MouseDrawCursor is set) and most debug overlays.
ImGuiMouseCursor MouseCursor;
// Drag and Drop
bool DragDropActive;
- bool DragDropWithinSourceOrTarget;
+ bool DragDropWithinSource; // Set when within a BeginDragDropXXX/EndDragDropXXX block for a drag source.
+ bool DragDropWithinTarget; // Set when within a BeginDragDropXXX/EndDragDropXXX block for a drag target.
ImGuiDragDropFlags DragDropSourceFlags;
int DragDropSourceFrameCount;
int DragDropMouseButton;
ImGuiPayload DragDropPayload;
- ImRect DragDropTargetRect;
+ ImRect DragDropTargetRect; // Store rectangle of current target candidate (we favor small targets when overlapping)
ImGuiID DragDropTargetId;
ImGuiDragDropFlags DragDropAcceptFlags;
float DragDropAcceptIdCurrRectSurface; // Target item surface (we resolve overlapping targets by prioritizing the smaller surface)
ImGuiID DragDropAcceptIdCurr; // Target item id (set at the time of accepting the payload)
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 DragDropPayloadBufHeap; // We don't expose the ImVector<> directly
- unsigned char DragDropPayloadBufLocal[8]; // Local buffer for small payloads
+ ImGuiID DragDropHoldJustPressedId; // Set when holding a payload just made ButtonBehavior() return a press.
+ ImVector DragDropPayloadBufHeap; // We don't expose the ImVector<> directly, ImGuiPayload only holds pointer+size
+ unsigned char DragDropPayloadBufLocal[16]; // Local buffer for small payloads
+
+ // Table
+ ImGuiTable* CurrentTable;
+ ImPool Tables;
+ ImVector CurrentTableStack;
+ ImVector TablesLastTimeActive; // Last used timestamp of each tables (SOA, for efficient GC)
+ ImVector DrawChannelsTempMergeBuffer;
// Tab bars
ImGuiTabBar* CurrentTabBar;
@@ -1166,42 +1432,42 @@ struct ImGuiContext
ImVec2 LastValidMousePos;
ImGuiInputTextState InputTextState;
ImFont InputTextPasswordFont;
- ImGuiID TempInputTextId; // Temporary text input when CTRL+clicking on a slider, etc.
+ ImGuiID TempInputId; // Temporary text input when CTRL+clicking on a slider, etc.
ImGuiColorEditFlags ColorEditOptions; // Store user options for color edit widgets
- float ColorEditLastHue;
+ float ColorEditLastHue; // Backup of last Hue associated to LastColor[3], so we can restore Hue in lossy RGB<>HSV round trips
+ float ColorEditLastSat; // Backup of last Saturation associated to LastColor[3], so we can restore Saturation in lossy RGB<>HSV round trips
float ColorEditLastColor[3];
- ImVec4 ColorPickerRef;
+ ImVec4 ColorPickerRef; // Initial/reference color at the time of opening the color picker.
+ float SliderCurrentAccum; // Accumulated slider delta when using navigation controls.
+ bool SliderCurrentAccumDirty; // Has the accumulated slider delta changed since last time we tried to apply it?
bool DragCurrentAccumDirty;
float DragCurrentAccum; // Accumulator for dragging modification. Always high-precision, not rounded by end-user precision settings
float DragSpeedDefaultRatio; // If speed == 0.0f, uses (max-min) * DragSpeedDefaultRatio
float ScrollbarClickDeltaToGrabCenter; // Distance between mouse and center of grab box, normalized in parent space. Use storage?
int TooltipOverrideCount;
- ImVector PrivateClipboard; // If no custom clipboard handler is defined
-
- // Range-Select/Multi-Select
- // [This is unused in this branch, but left here to facilitate merging/syncing multiple branches]
- ImGuiID MultiSelectScopeId;
+ float TooltipSlowDelay; // Time before slow tooltips appears (FIXME: This is temporary until we merge in tooltip timer+priority work)
+ ImVector ClipboardHandlerData; // If no custom clipboard handler is defined
+ ImVector MenusIdSubmittedThisFrame; // A list of menu IDs that were rendered at least once
// Platform support
ImVec2 PlatformImePos; // Cursor position request & last passed to the OS Input Method Editor
ImVec2 PlatformImeLastPos;
- ImGuiViewportP* PlatformImePosViewport;
-
- // Extensions
- // FIXME: We could provide an API to register one slot in an array held in ImGuiContext?
- ImGuiDockContext* DockContext;
+ char PlatformLocaleDecimalPoint; // '.' or *localeconv()->decimal_point
// Settings
- bool SettingsLoaded;
- float SettingsDirtyTimer; // Save .ini Settings to memory when time reaches zero
- ImGuiTextBuffer SettingsIniData; // In memory .ini settings
- ImVector SettingsHandlers; // List of .ini settings handlers
- ImVector SettingsWindows; // ImGuiWindow .ini settings entries (parsed from the last loaded .ini file and maintained on saving)
+ bool SettingsLoaded;
+ float SettingsDirtyTimer; // Save .ini Settings to memory when time reaches zero
+ ImGuiTextBuffer SettingsIniData; // In memory .ini settings
+ ImVector SettingsHandlers; // List of .ini settings handlers
+ ImChunkStream SettingsWindows; // ImGuiWindow .ini settings entries
+ ImChunkStream SettingsTables; // ImGuiTable .ini settings entries
+ ImVector Hooks; // Hooks for extensions (e.g. test engine)
+ ImGuiID HookIdNext; // Next available HookId
- // Logging
- bool LogEnabled;
- ImGuiLogType LogType;
- FILE* LogFile; // If != NULL log to stdout/ file
+ // Capture/Logging
+ bool LogEnabled; // Currently capturing
+ ImGuiLogType LogType; // Capture target
+ ImFileHandle LogFile; // If != NULL log to stdout/ file
ImGuiTextBuffer LogBuffer; // Accumulation buffer when log to clipboard. This is pointer so our GImGui static constructor doesn't call heap allocators.
float LogLinePosY;
bool LogLineFirstItem;
@@ -1210,8 +1476,9 @@ struct ImGuiContext
int LogDepthToExpandDefault; // Default/stored value for LogDepthMaxExpand if not specified in the LogXXX function call.
// Debug Tools
- bool DebugItemPickerActive;
- ImGuiID DebugItemPickerBreakID; // Will call IM_DEBUG_BREAK() when encountering this id
+ bool DebugItemPickerActive; // Item picker is active (started with DebugStartItemPicker())
+ ImGuiID DebugItemPickerBreakId; // Will call IM_DEBUG_BREAK() when encountering this id
+ ImGuiMetricsConfig DebugMetricsConfig;
// Misc
float FramerateSecPerFrame[120]; // Calculate estimate of framerate for user over the last 2 seconds.
@@ -1220,20 +1487,23 @@ struct ImGuiContext
int WantCaptureMouseNextFrame; // Explicit capture via CaptureKeyboardFromApp()/CaptureMouseFromApp() sets those flags
int WantCaptureKeyboardNextFrame;
int WantTextInputNextFrame;
- char TempBuffer[1024*3+1]; // Temporary text buffer
+ char TempBuffer[1024 * 3 + 1]; // Temporary text buffer
- ImGuiContext(ImFontAtlas* shared_font_atlas)
+ ImGuiContext(ImFontAtlas* shared_font_atlas) : BackgroundDrawList(&DrawListSharedData), ForegroundDrawList(&DrawListSharedData)
{
Initialized = false;
- FrameScopeActive = FrameScopePushedFallbackWindow = false;
- ConfigFlagsCurrFrame = ConfigFlagsLastFrame = ImGuiConfigFlags_None;
+ FontAtlasOwnedByContext = shared_font_atlas ? false : true;
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 = FrameCountPlatformEnded = FrameCountRendered = -1;
+ FrameCountEnded = FrameCountRendered = -1;
+ WithinFrameScope = WithinFrameScopeWithImplicitWindow = WithinEndChild = false;
+ GcCompactAll = false;
+ TestEngineHookItems = false;
+ TestEngineHookIdInfo = 0;
+ TestEngine = NULL;
WindowsActiveCount = 0;
CurrentWindow = NULL;
@@ -1244,47 +1514,42 @@ struct ImGuiContext
WheelingWindow = NULL;
WheelingWindowTimer = 0.0f;
- HoveredId = 0;
+ HoveredId = HoveredIdPreviousFrame = 0;
HoveredIdAllowOverlap = false;
- HoveredIdPreviousFrame = 0;
+ HoveredIdUsingMouseWheel = HoveredIdPreviousFrameUsingMouseWheel = false;
+ HoveredIdDisabled = false;
HoveredIdTimer = HoveredIdNotActiveTimer = 0.0f;
ActiveId = 0;
ActiveIdIsAlive = 0;
ActiveIdTimer = 0.0f;
ActiveIdIsJustActivated = false;
ActiveIdAllowOverlap = false;
+ ActiveIdNoClearOnFocusLoss = false;
ActiveIdHasBeenPressedBefore = false;
ActiveIdHasBeenEditedBefore = false;
ActiveIdHasBeenEditedThisFrame = false;
+ ActiveIdUsingMouseWheel = false;
ActiveIdUsingNavDirMask = 0x00;
ActiveIdUsingNavInputMask = 0x00;
ActiveIdUsingKeyInputMask = 0x00;
- ActiveIdClickOffset = ImVec2(-1,-1);
+ ActiveIdClickOffset = ImVec2(-1, -1);
ActiveIdWindow = NULL;
ActiveIdSource = ImGuiInputSource_None;
-
+ ActiveIdMouseButton = 0;
ActiveIdPreviousFrame = 0;
ActiveIdPreviousFrameIsAlive = false;
ActiveIdPreviousFrameHasBeenEditedBefore = false;
ActiveIdPreviousFrameWindow = NULL;
-
LastActiveId = 0;
LastActiveIdTimer = 0.0f;
- CurrentViewport = NULL;
- MouseViewport = MouseLastHoveredViewport = NULL;
- PlatformLastFocusedViewport = 0;
- ViewportFrontMostStampCount = 0;
-
NavWindow = NULL;
- NavId = NavActivateId = NavActivateDownId = NavActivatePressedId = NavInputId = 0;
- NavJustTabbedId = NavJustMovedToId = NavJustMovedToMultiSelectScopeId = NavNextActivateId = 0;
+ NavId = NavFocusScopeId = NavActivateId = NavActivateDownId = NavActivatePressedId = NavInputId = 0;
+ NavJustTabbedId = NavJustMovedToId = NavJustMovedToFocusScopeId = NavNextActivateId = 0;
+ NavJustMovedToKeyMods = ImGuiKeyModFlags_None;
NavInputSource = ImGuiInputSource_None;
- NavScoringRectScreen = ImRect();
+ NavScoringRect = ImRect();
NavScoringCount = 0;
- NavWindowingTarget = NavWindowingTargetAnim = NavWindowingList = NULL;
- NavWindowingTimer = NavWindowingHighlightAlpha = 0.0f;
- NavWindowingToggleLayer = false;
NavLayer = ImGuiNavLayer_Main;
NavIdTabCounter = INT_MAX;
NavIdIsAlive = false;
@@ -1295,53 +1560,63 @@ struct ImGuiContext
NavInitRequest = false;
NavInitRequestFromMove = false;
NavInitResultId = 0;
- NavMoveFromClampedRefRect = false;
NavMoveRequest = false;
- NavMoveRequestFlags = 0;
+ NavMoveRequestFlags = ImGuiNavMoveFlags_None;
NavMoveRequestForward = ImGuiNavForward_None;
+ NavMoveRequestKeyMods = ImGuiKeyModFlags_None;
NavMoveDir = NavMoveDirLast = NavMoveClipDir = ImGuiDir_None;
+ NavWrapRequestWindow = NULL;
+ NavWrapRequestFlags = ImGuiNavMoveFlags_None;
+
+ NavWindowingTarget = NavWindowingTargetAnim = NavWindowingListWindow = NULL;
+ NavWindowingTimer = NavWindowingHighlightAlpha = 0.0f;
+ NavWindowingToggleLayer = false;
FocusRequestCurrWindow = FocusRequestNextWindow = NULL;
- FocusRequestCurrCounterAll = FocusRequestCurrCounterTab = INT_MAX;
- FocusRequestNextCounterAll = FocusRequestNextCounterTab = INT_MAX;
+ FocusRequestCurrCounterRegular = FocusRequestCurrCounterTabStop = INT_MAX;
+ FocusRequestNextCounterRegular = FocusRequestNextCounterTabStop = INT_MAX;
FocusTabPressed = false;
DimBgRatio = 0.0f;
+ BackgroundDrawList._OwnerName = "##Background"; // Give it a name for debugging
+ ForegroundDrawList._OwnerName = "##Foreground"; // Give it a name for debugging
MouseCursor = ImGuiMouseCursor_Arrow;
- DragDropActive = DragDropWithinSourceOrTarget = false;
- DragDropSourceFlags = 0;
+ DragDropActive = DragDropWithinSource = DragDropWithinTarget = false;
+ DragDropSourceFlags = ImGuiDragDropFlags_None;
DragDropSourceFrameCount = -1;
DragDropMouseButton = -1;
DragDropTargetId = 0;
- DragDropAcceptFlags = 0;
+ DragDropAcceptFlags = ImGuiDragDropFlags_None;
DragDropAcceptIdCurrRectSurface = 0.0f;
DragDropAcceptIdPrev = DragDropAcceptIdCurr = 0;
DragDropAcceptFrameCount = -1;
+ DragDropHoldJustPressedId = 0;
memset(DragDropPayloadBufLocal, 0, sizeof(DragDropPayloadBufLocal));
+ CurrentTable = NULL;
CurrentTabBar = NULL;
LastValidMousePos = ImVec2(0.0f, 0.0f);
- TempInputTextId = 0;
+ TempInputId = 0;
ColorEditOptions = ImGuiColorEditFlags__OptionsDefault;
- ColorEditLastHue = 0.0f;
+ ColorEditLastHue = ColorEditLastSat = 0.0f;
ColorEditLastColor[0] = ColorEditLastColor[1] = ColorEditLastColor[2] = FLT_MAX;
+ SliderCurrentAccum = 0.0f;
+ SliderCurrentAccumDirty = false;
DragCurrentAccumDirty = false;
DragCurrentAccum = 0.0f;
DragSpeedDefaultRatio = 1.0f / 100.0f;
ScrollbarClickDeltaToGrabCenter = 0.0f;
TooltipOverrideCount = 0;
-
- MultiSelectScopeId = 0;
+ TooltipSlowDelay = 0.50f;
PlatformImePos = PlatformImeLastPos = ImVec2(FLT_MAX, FLT_MAX);
- PlatformImePosViewport = 0;
-
- DockContext = NULL;
+ PlatformLocaleDecimalPoint = '.';
SettingsLoaded = false;
SettingsDirtyTimer = 0.0f;
+ HookIdNext = 0;
LogEnabled = false;
LogType = ImGuiLogType_None;
@@ -1352,7 +1627,7 @@ struct ImGuiContext
LogDepthToExpand = LogDepthToExpandDefault = 2;
DebugItemPickerActive = false;
- DebugItemPickerBreakID = 0;
+ DebugItemPickerBreakId = 0;
memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame));
FramerateSecPerFrameIdx = 0;
@@ -1363,108 +1638,81 @@ struct ImGuiContext
};
//-----------------------------------------------------------------------------
-// ImGuiWindow
+// [SECTION] ImGuiWindowTempData, ImGuiWindow
//-----------------------------------------------------------------------------
// Transient per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the DC variable name in ImGuiWindow.
-// FIXME: That's theory, in practice the delimitation between ImGuiWindow and ImGuiWindowTempData is quite tenuous and could be reconsidered.
+// (That's theory, in practice the delimitation between ImGuiWindow and ImGuiWindowTempData is quite tenuous and could be reconsidered..)
+// (This doesn't need a constructor because we zero-clear it as part of ImGuiWindow and all frame-temporary data are setup on Begin)
struct IMGUI_API ImGuiWindowTempData
{
+ // Layout
ImVec2 CursorPos; // Current emitting position, in absolute coordinates.
ImVec2 CursorPosPrevLine;
ImVec2 CursorStartPos; // Initial position after Begin(), generally ~ window position + WindowPadding.
- ImVec2 CursorMaxPos; // Used to implicitly calculate the size of our contents, always growing during the frame. Used to calculate window->ContentSize at the beginning of next frame
+ ImVec2 CursorMaxPos; // Used to implicitly calculate ContentSize at the beginning of next frame, for scrolling range and auto-resize. Always growing during the frame.
+ ImVec2 IdealMaxPos; // Used to implicitly calculate ContentSizeIdeal at the beginning of next frame, for auto-resize only. Always growing during the frame.
ImVec2 CurrLineSize;
ImVec2 PrevLineSize;
float CurrLineTextBaseOffset; // Baseline offset (0.0f by default on a new line, generally == style.FramePadding.y when a framed item has been added).
float PrevLineTextBaseOffset;
- int TreeDepth; // Current tree depth.
- ImU32 TreeMayJumpToParentOnPopMask; // Store a copy of !g.NavIdIsAlive for TreeDepth 0..31.. Could be turned into a ImU64 if necessary.
+ ImVec1 Indent; // Indentation / start position from left of window (increased by TreePush/TreePop, etc.)
+ ImVec1 ColumnsOffset; // Offset to the current column (if ColumnsCurrent > 0). FIXME: This and the above should be a stack to allow use cases like Tree->Column->Tree. Need revamp columns API.
+ ImVec1 GroupOffset;
+
+ // Last item status
ImGuiID LastItemId; // ID for last item
ImGuiItemStatusFlags LastItemStatusFlags; // Status flags for last item (see ImGuiItemStatusFlags_)
ImRect LastItemRect; // Interaction rect for last item
ImRect LastItemDisplayRect; // End-user display rect for last item (only valid if LastItemStatusFlags & ImGuiItemStatusFlags_HasDisplayRect)
+
+ // Keyboard/Gamepad navigation
ImGuiNavLayer 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)
+ int NavLayerActiveMask; // Which layers have been written to (result from previous frame)
+ int NavLayerActiveMaskNext; // Which layers have been written to (accumulator for current frame)
+ ImGuiID NavFocusScopeIdCurrent; // Current focus scope ID while appending
bool NavHideHighlightOneFrame;
bool NavHasScroll; // Set when scrolling can be used (ScrollMax > 0.0f)
+
+ // Miscellaneous
bool MenuBarAppending; // FIXME: Remove this
ImVec2 MenuBarOffset; // MenuBarOffset.x is sort of equivalent of a per-layer CursorPos.x, saved/restored as we switch to the menu bar. The only situation when MenuBarOffset.y is > 0 if when (SafeAreaPadding.y > FramePadding.y), often used on TVs.
+ ImGuiMenuColumns MenuColumns; // Simplified columns storage for menu items measurement
+ int TreeDepth; // Current tree depth.
+ ImU32 TreeJumpToParentOnPopMask; // Store a copy of !g.NavIdIsAlive for TreeDepth 0..31.. Could be turned into a ImU64 if necessary.
ImVector ChildWindows;
ImGuiStorage* StateStorage; // Current persistent per-window storage (store e.g. tree node open/close state)
+ ImGuiOldColumns* CurrentColumns; // Current columns set
+ int CurrentTableIdx; // Current table index (into g.Tables)
ImGuiLayoutType LayoutType;
ImGuiLayoutType ParentLayoutType; // Layout type of parent window at the time of Begin()
- int FocusCounterAll; // Counter for focus/tabbing system. Start at -1 and increase as assigned via FocusableItemRegister() (FIXME-NAV: Needs redesign)
- int FocusCounterTab; // (same, but only count widgets which you can Tab through)
+ int FocusCounterRegular; // (Legacy Focus/Tabbing system) Sequential counter, start at -1 and increase as assigned via FocusableItemRegister() (FIXME-NAV: Needs redesign)
+ int FocusCounterTabStop; // (Legacy Focus/Tabbing system) Same, but only count widgets which you can Tab through.
+ // Local parameters stacks
// 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]
- float ItemWidth; // == ItemWidthStack.back(). 0.0: default, >0.0: width in pixels, <0.0: align xx pixels to the right of window
- float TextWrapPos; // == TextWrapPosStack.back() [empty == -1.0f]
- ImVectorItemFlagsStack;
- ImVector ItemWidthStack;
- ImVector TextWrapPosStack;
- ImVectorGroupStack;
- short StackSizesBackup[6]; // Store size of various stacks for asserting
-
- ImVec1 Indent; // Indentation / start position from left of window (increased by TreePush/TreePop, etc.)
- ImVec1 GroupOffset;
- ImVec1 ColumnsOffset; // Offset to the current column (if ColumnsCurrent > 0). FIXME: This and the above should be a stack to allow use cases like Tree->Column->Tree. Need revamp columns API.
- ImGuiColumns* CurrentColumns; // Current columns set
-
- ImGuiWindowTempData()
- {
- CursorPos = CursorPosPrevLine = CursorStartPos = CursorMaxPos = ImVec2(0.0f, 0.0f);
- CurrLineSize = PrevLineSize = ImVec2(0.0f, 0.0f);
- CurrLineTextBaseOffset = PrevLineTextBaseOffset = 0.0f;
- TreeDepth = 0;
- TreeMayJumpToParentOnPopMask = 0x00;
- LastItemId = 0;
- LastItemStatusFlags = 0;
- LastItemRect = LastItemDisplayRect = ImRect();
- NavLayerActiveMask = NavLayerActiveMaskNext = 0x00;
- NavLayerCurrent = ImGuiNavLayer_Main;
- NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
- NavHideHighlightOneFrame = false;
- NavHasScroll = false;
- MenuBarAppending = false;
- MenuBarOffset = ImVec2(0.0f, 0.0f);
- StateStorage = NULL;
- LayoutType = ParentLayoutType = ImGuiLayoutType_Vertical;
- FocusCounterAll = FocusCounterTab = -1;
-
- ItemFlags = ImGuiItemFlags_Default_;
- ItemWidth = 0.0f;
- TextWrapPos = -1.0f;
- memset(StackSizesBackup, 0, sizeof(StackSizesBackup));
-
- Indent = ImVec1(0.0f);
- GroupOffset = ImVec1(0.0f);
- ColumnsOffset = ImVec1(0.0f);
- CurrentColumns = NULL;
- }
+ ImGuiItemFlags ItemFlags; // == g.ItemFlagsStack.back()
+ float ItemWidth; // Current item width (>0.0: width in pixels, <0.0: align xx pixels to the right of window).
+ float TextWrapPos; // Current text wrap pos.
+ ImVector ItemWidthStack; // Store item widths to restore (attention: .back() is not == ItemWidth)
+ ImVector TextWrapPosStack; // Store text wrap pos to restore (attention: .back() is not == TextWrapPos)
+ ImGuiStackSizes StackSizesOnBegin; // Store size of various stacks for asserting
};
// Storage for one window
struct IMGUI_API ImGuiWindow
{
- char* Name;
+ char* Name; // Window name, owned by the window.
ImGuiID ID; // == ImHashStr(Name)
- ImGuiWindowFlags Flags, FlagsPreviousFrame; // See enum ImGuiWindowFlags_
- ImGuiWindowClass WindowClass; // Advanced users only. Set with SetNextWindowClass()
- ImGuiViewportP* Viewport; // Always set in Begin(), only inactive windows may have a NULL value here
- ImGuiID ViewportId; // We backup the viewport id (since the viewport may disappear or never be created if the window is inactive)
- ImVec2 ViewportPos; // We backup the viewport position (since the viewport may disappear or never be created if the window is inactive)
- int ViewportAllowPlatformMonitorExtend; // Reset to -1 every frame (index is guaranteed to be valid between NewFrame..EndFrame), only used in the Appearing frame of a tooltip/popup to enforce clamping to a given monitor
+ ImGuiWindowFlags Flags; // See enum ImGuiWindowFlags_
ImVec2 Pos; // Position (always rounded-up to nearest pixel)
ImVec2 Size; // Current size (==SizeFull or collapsed title bar size)
ImVec2 SizeFull; // Size when non collapsed
ImVec2 ContentSize; // Size of contents/scrollable client area (calculated from the extents reach of the cursor) from previous frame. Does not include window decoration or window padding.
+ ImVec2 ContentSizeIdeal;
ImVec2 ContentSizeExplicit; // Size of contents/scrollable client area explicitly request by the user via SetNextWindowContentSize().
ImVec2 WindowPadding; // Window padding at the time of Begin().
- float WindowRounding; // Window rounding at the time of Begin().
+ float WindowRounding; // Window rounding at the time of Begin(). May be clamped lower to avoid rendering artifacts with title bar, menu bar etc.
float WindowBorderSize; // Window border size at the time of Begin().
int NameBufLen; // Size of buffer storing Name. May be larger than strlen(Name)!
ImGuiID MoveId; // == window->GetID("#MOVE")
@@ -1473,9 +1721,9 @@ struct IMGUI_API ImGuiWindow
ImVec2 ScrollMax;
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
- ImVec2 ScrollbarSizes; // Size taken by scrollbars on each axis
+ ImVec2 ScrollTargetEdgeSnapDist; // 0.0f = no snapping, >0.0f snapping threshold
+ ImVec2 ScrollbarSizes; // Size taken by each scrollbars on their smaller axis. Pay attention! ScrollbarSizes.x == width of the vertical scrollbar, ScrollbarSizes.y = height of the horizontal scrollbar.
bool ScrollbarX, ScrollbarY; // Are scrollbars visible?
- bool ViewportOwned;
bool Active; // Set to true on Begin(), unless Collapsed
bool WasActive;
bool WriteAccessed; // Set to true when any widget access the current window
@@ -1483,8 +1731,8 @@ struct IMGUI_API ImGuiWindow
bool WantCollapseToggle;
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 Hidden; // Do not display (== (HiddenFrames*** > 0))
- bool IsFallbackWindow;
+ bool Hidden; // Do not display (== HiddenFrames*** > 0)
+ bool IsFallbackWindow; // Set on the "Debug##Default" window.
bool HasCloseButton; // Set when the window has a close button (p_open != NULL)
signed char ResizeBorderHeld; // Current border being held for resize (-1: none, otherwise 0-3)
short BeginCount; // Number of Begin() during the current frame (generally 0 or 1, 1+ if appending via multiple Begin/End pairs)
@@ -1495,44 +1743,42 @@ struct IMGUI_API ImGuiWindow
ImS8 AutoFitChildAxises;
bool AutoFitOnlyGrows;
ImGuiDir AutoPosLastDirection;
- int HiddenFramesCanSkipItems; // Hide the window for N frames
- int HiddenFramesCannotSkipItems; // Hide the window for N frames while allowing items to be submitted so we can measure their size
- ImGuiCond SetWindowPosAllowFlags; // store acceptable condition flags for SetNextWindowPos() use.
- ImGuiCond SetWindowSizeAllowFlags; // store acceptable condition flags for SetNextWindowSize() use.
- ImGuiCond SetWindowCollapsedAllowFlags; // store acceptable condition flags for SetNextWindowCollapsed() use.
- ImGuiCond SetWindowDockAllowFlags; // store acceptable condition flags for SetNextWindowDock() use.
+ ImS8 HiddenFramesCanSkipItems; // Hide the window for N frames
+ ImS8 HiddenFramesCannotSkipItems; // Hide the window for N frames while allowing items to be submitted so we can measure their size
+ ImS8 HiddenFramesForRenderOnly; // Hide the window until frame N at Render() time only
+ ImGuiCond SetWindowPosAllowFlags : 8; // store acceptable condition flags for SetNextWindowPos() use.
+ ImGuiCond SetWindowSizeAllowFlags : 8; // store acceptable condition flags for SetNextWindowSize() use.
+ ImGuiCond SetWindowCollapsedAllowFlags : 8; // store acceptable condition flags for SetNextWindowCollapsed() use.
ImVec2 SetWindowPosVal; // store window position when using a non-zero Pivot (position set needs to be processed when we know the window size)
- ImVec2 SetWindowPosPivot; // store window pivot for positioning. ImVec2(0,0) when positioning from top-left corner; ImVec2(0.5f,0.5f) for centering; ImVec2(1,1) for bottom right.
+ ImVec2 SetWindowPosPivot; // store window pivot for positioning. ImVec2(0, 0) when positioning from top-left corner; ImVec2(0.5f, 0.5f) for centering; ImVec2(1, 1) for bottom right.
ImVector IDStack; // ID stack. ID are hashes seeded with the value at the top of the stack. (In theory this should be in the TempData structure)
ImGuiWindowTempData DC; // Temporary per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the "DC" variable name.
- // The best way to understand what those rectangles are is to use the 'Metrics -> Tools -> Show windows rectangles' viewer.
+ // The best way to understand what those rectangles are is to use the 'Metrics->Tools->Show Windows Rectangles' viewer.
// The main 'OuterRect', omitted as a field, is window->Rect().
ImRect OuterRectClipped; // == Window->Rect() just after setup in Begin(). == window->Rect() for root window.
ImRect InnerRect; // Inner rectangle (omit title bar, menu bar, scroll bar)
ImRect InnerClipRect; // == InnerRect shrunk by WindowPadding*0.5f on each side, clipped within viewport or parent clip rect.
- ImRect WorkRect; // Cover the whole scrolling region, shrunk by WindowPadding*1.0f on each side. This is meant to replace ContentsRegionRect over time (from 1.71+ onward).
+ ImRect WorkRect; // Initially covers the whole scrolling region. Reduced by containers e.g columns/tables when active. Shrunk by WindowPadding*1.0f on each side. This is meant to replace ContentRegionRect over time (from 1.71+ onward).
+ ImRect ParentWorkRect; // Backup of WorkRect before entering a container such as columns/tables. Used by e.g. SpanAllColumns functions to easily access. Stacked containers are responsible for maintaining this. // FIXME-WORKRECT: Could be a stack?
ImRect ClipRect; // Current clipping/scissoring rectangle, evolve as we are using PushClipRect(), etc. == DrawList->clip_rect_stack.back().
- ImRect ContentsRegionRect; // FIXME: This is currently confusing/misleading. It is essentially WorkRect but not handling of scrolling. We currently rely on it as right/bottom aligned sizing operation need some size to rely on.
- ImVec2ih HitTestHoleSize, HitTestHoleOffset;
+ ImRect ContentRegionRect; // FIXME: This is currently confusing/misleading. It is essentially WorkRect but not handling of scrolling. We currently rely on it as right/bottom aligned sizing operation need some size to rely on.
+ ImVec2ih HitTestHoleSize; // Define an optional rectangular hole where mouse will pass-through the window.
+ ImVec2ih HitTestHoleOffset;
int LastFrameActive; // Last frame number the window was Active.
- int LastFrameJustFocused; // Last frame number the window was made Focused.
float LastTimeActive; // Last timestamp the window was Active (using float as we don't need high precision there)
float ItemWidthDefault;
- ImGuiMenuColumns MenuColumns; // Simplified columns storage for menu items
ImGuiStorage StateStorage;
- ImVector ColumnsStorage;
+ ImVector ColumnsStorage;
float FontWindowScale; // User scale multiplier per-window, via SetWindowFontScale()
- float FontDpiScale;
- int SettingsIdx; // Index into SettingsWindow[] (indices are always valid as we only grow the array from the back)
+ int SettingsOffset; // Offset into SettingsWindows[] (offsets are always valid as we only grow the array from the back)
ImDrawList* DrawList; // == &DrawListInst (for backward compatibility reason with code using imgui_internal.h we keep this a pointer)
ImDrawList DrawListInst;
ImGuiWindow* ParentWindow; // If we are a child _or_ popup window, this is pointing to our parent. Otherwise NULL.
- ImGuiWindow* RootWindow; // Point to ourself or first ancestor that is not a child window.
- ImGuiWindow* RootWindowDockStop; // Point to ourself or first ancestor that is not a child window. Doesn't cross through dock nodes. We use this so IsWindowFocused() can behave consistently regardless of docking state.
+ ImGuiWindow* RootWindow; // Point to ourself or first ancestor that is not a child window == Top-level window.
ImGuiWindow* RootWindowForTitleBarHighlight; // Point to ourself or first ancestor which will display TitleBgActive color when this window is active.
ImGuiWindow* RootWindowForNav; // Point to ourself or first ancestor which doesn't have the NavFlattened flag.
@@ -1540,20 +1786,9 @@ struct IMGUI_API ImGuiWindow
ImGuiID NavLastIds[ImGuiNavLayer_COUNT]; // Last known NavId for this window, per layer (0/1)
ImRect NavRectRel[ImGuiNavLayer_COUNT]; // Reference rectangle, in window relative space
- bool MemoryCompacted;
- int MemoryDrawListIdxCapacity;
+ int MemoryDrawListIdxCapacity; // Backup of last idx/vtx count, so when waking up the window we can preallocate and avoid iterative alloc/copy
int MemoryDrawListVtxCapacity;
-
- // Docking
- ImGuiDockNode* DockNode; // Which node are we docked into
- ImGuiDockNode* DockNodeAsHost; // Which node are we owning (for parent windows)
- ImGuiID DockId; // Backup of last valid DockNode->Id, so single value remember their dock node id
- ImGuiItemStatusFlags DockTabItemStatusFlags;
- ImRect DockTabItemRect;
- short DockOrder; // Order of the last time the window was visible within its DockNode. This is used to reorder windows that are reappearing on the same frame. Same value between windows that were active and windows that were none are possible.
- bool DockIsActive :1; // =~ (DockNode != NULL) && (DockNode->Windows.Size > 1)
- bool DockTabIsVisible :1; // Is the window visible this frame? =~ is the corresponding tab selected?
- bool DockTabWantClose :1;
+ bool MemoryCompacted; // Set when window extraneous data have been garbage collected
public:
ImGuiWindow(ImGuiContext* context, const char* name);
@@ -1568,29 +1803,29 @@ public:
ImGuiID GetIDFromRectangle(const ImRect& r_abs);
// We don't use g.FontSize because the window may be != g.CurrentWidow.
- ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x+Size.x, Pos.y+Size.y); }
- float CalcFontSize() const { ImGuiContext& g = *GImGui; float scale = g.FontBaseSize * FontWindowScale * FontDpiScale; if (ParentWindow) scale *= ParentWindow->FontWindowScale; return scale; }
- float TitleBarHeight() const { ImGuiContext& g = *GImGui; return (Flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : CalcFontSize() + g.Style.FramePadding.y * 2.0f; }
- ImRect TitleBarRect() const { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight())); }
- float MenuBarHeight() const { ImGuiContext& g = *GImGui; return (Flags & ImGuiWindowFlags_MenuBar) ? DC.MenuBarOffset.y + CalcFontSize() + g.Style.FramePadding.y * 2.0f : 0.0f; }
- ImRect MenuBarRect() const { float y1 = Pos.y + TitleBarHeight(); return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight()); }
+ ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); }
+ float CalcFontSize() const { ImGuiContext& g = *GImGui; float scale = g.FontBaseSize * FontWindowScale; if (ParentWindow) scale *= ParentWindow->FontWindowScale; return scale; }
+ float TitleBarHeight() const { ImGuiContext& g = *GImGui; return (Flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : CalcFontSize() + g.Style.FramePadding.y * 2.0f; }
+ ImRect TitleBarRect() const { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight())); }
+ float MenuBarHeight() const { ImGuiContext& g = *GImGui; return (Flags & ImGuiWindowFlags_MenuBar) ? DC.MenuBarOffset.y + CalcFontSize() + g.Style.FramePadding.y * 2.0f : 0.0f; }
+ ImRect MenuBarRect() const { float y1 = Pos.y + TitleBarHeight(); return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight()); }
};
// 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
+struct ImGuiLastItemDataBackup
{
ImGuiID LastItemId;
ImGuiItemStatusFlags LastItemStatusFlags;
ImRect LastItemRect;
ImRect LastItemDisplayRect;
- ImGuiItemHoveredDataBackup() { Backup(); }
+ ImGuiLastItemDataBackup() { Backup(); }
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; }
};
//-----------------------------------------------------------------------------
-// Tab bar, tab item
+// [SECTION] Tab bar, Tab item support
//-----------------------------------------------------------------------------
// Extend ImGuiTabBarFlags_
@@ -1604,31 +1839,33 @@ enum ImGuiTabBarFlagsPrivate_
// Extend ImGuiTabItemFlags_
enum ImGuiTabItemFlagsPrivate_
{
- ImGuiTabItemFlags_NoCloseButton = 1 << 20, // Store whether p_open is set or not, which we need to recompute WidthContents during layout.
- ImGuiTabItemFlags_Unsorted = 1 << 21, // [Docking] Trailing tabs with the _Unsorted flag will be sorted based on the DockOrder of their Window.
- ImGuiTabItemFlags_Preview = 1 << 22 // [Docking] Display tab shape for docking preview (height is adjusted slightly to compensate for the yet missing tab bar)
+ ImGuiTabItemFlags_NoCloseButton = 1 << 20, // Track whether p_open was set or not (we'll need this info on the next frame to recompute ContentWidth during layout)
+ ImGuiTabItemFlags_Button = 1 << 21 // Used by TabItemButton, change the tab item behavior to mimic a button
};
-// Storage for one active tab item (sizeof() 32~40 bytes)
+// Storage for one active tab item (sizeof() 28~32 bytes)
struct ImGuiTabItem
{
ImGuiID ID;
ImGuiTabItemFlags Flags;
- ImGuiWindow* Window; // When TabItem is part of a DockNode's TabBar, we hold on to a window.
int LastFrameVisible;
int LastFrameSelected; // This allows us to infer an ordered list of the last activated tabs with little maintenance
- int NameOffset; // When Window==NULL, offset to name within parent ImGuiTabBar::TabsNames
float Offset; // Position relative to beginning of tab
float Width; // Width currently displayed
- float WidthContents; // Width of actual contents, stored during BeginTabItem() call
+ float ContentWidth; // Width of label, stored during BeginTabItem() call
+ ImS16 NameOffset; // When Window==NULL, offset to name within parent ImGuiTabBar::TabsNames
+ ImS16 BeginOrder; // BeginTabItem() order, used to re-order tabs after toggling ImGuiTabBarFlags_Reorderable
+ ImS16 IndexDuringLayout; // Index only used during TabBarLayout()
+ bool WantClose; // Marked as closed by SetTabItemClosed()
- ImGuiTabItem() { ID = Flags = 0; Window = NULL; LastFrameVisible = LastFrameSelected = -1; NameOffset = -1; Offset = Width = WidthContents = 0.0f; }
+ ImGuiTabItem() { memset(this, 0, sizeof(*this)); LastFrameVisible = LastFrameSelected = -1; NameOffset = BeginOrder = IndexDuringLayout = -1; }
};
-// Storage for a tab bar (sizeof() 92~96 bytes)
+// Storage for a tab bar (sizeof() 152 bytes)
struct ImGuiTabBar
{
ImVector Tabs;
+ ImGuiTabBarFlags Flags;
ImGuiID ID; // Zero for tab-bars used by docking
ImGuiID SelectedTabId; // Selected tab/window
ImGuiID NextSelectedTabId;
@@ -1636,41 +1873,286 @@ struct ImGuiTabBar
int CurrFrameVisible;
int PrevFrameVisible;
ImRect BarRect;
- float LastTabContentHeight; // Record the height of contents submitted below the tab bar
- float OffsetMax; // Distance from BarRect.Min.x, locked during layout
- float OffsetMaxIdeal; // Ideal offset if all tabs were visible and not clipped
- float OffsetNextTab; // Distance from BarRect.Min.x, incremented with each BeginTabItem() call, not used if ImGuiTabBarFlags_Reorderable if set.
+ float CurrTabsContentsHeight;
+ float PrevTabsContentsHeight; // Record the height of contents submitted below the tab bar
+ float WidthAllTabs; // Actual width of all tabs (locked during layout)
+ float WidthAllTabsIdeal; // Ideal width if all tabs were visible and not clipped
float ScrollingAnim;
float ScrollingTarget;
float ScrollingTargetDistToVisibility;
float ScrollingSpeed;
- ImGuiTabBarFlags Flags;
+ float ScrollingRectMinX;
+ float ScrollingRectMaxX;
ImGuiID ReorderRequestTabId;
ImS8 ReorderRequestDir;
+ ImS8 BeginCount;
bool WantLayout;
bool VisibleTabWasSubmitted;
- short LastTabItemIdx; // For BeginTabItem()/EndTabItem()
+ bool TabsAddedNew; // Set to true when a new tab item or button has been added to the tab bar during last frame
+ ImS16 TabsActiveCount; // Number of tabs submitted this frame.
+ ImS16 LastTabItemIdx; // Index of last BeginTabItem() tab for use by EndTabItem()
+ float ItemSpacingY;
ImVec2 FramePadding; // style.FramePadding locked at the time of BeginTabBar()
+ ImVec2 BackupCursorPos;
ImGuiTextBuffer TabsNames; // For non-docking tab bar we re-append names in a contiguous buffer.
ImGuiTabBar();
int GetTabOrder(const ImGuiTabItem* tab) const { return Tabs.index_from_ptr(tab); }
const char* GetTabName(const ImGuiTabItem* tab) const
{
- if (tab->Window)
- return tab->Window->Name;
- IM_ASSERT(tab->NameOffset != -1 && tab->NameOffset < TabsNames.Buf.Size);
+ IM_ASSERT(tab->NameOffset != -1 && (int)tab->NameOffset < TabsNames.Buf.Size);
return TabsNames.Buf.Data + tab->NameOffset;
}
};
//-----------------------------------------------------------------------------
-// Internal API
-// No guarantee of forward compatibility here.
+// [SECTION] Table support
+//-----------------------------------------------------------------------------
+
+#ifdef IMGUI_HAS_TABLE
+
+#define IM_COL32_DISABLE IM_COL32(0,0,0,1) // Special sentinel code which cannot be used as a regular color.
+#define IMGUI_TABLE_MAX_COLUMNS 64 // sizeof(ImU64) * 8. This is solely because we frequently encode columns set in a ImU64.
+#define IMGUI_TABLE_MAX_DRAW_CHANNELS (4 + 64 * 2) // See TableSetupDrawChannels()
+
+// Our current column maximum is 64 but we may raise that in the future.
+typedef ImS8 ImGuiTableColumnIdx;
+typedef ImU8 ImGuiTableDrawChannelIdx;
+
+// [Internal] sizeof() ~ 104
+// We use the terminology "Enabled" to refer to a column that is not Hidden by user/api.
+// We use the terminology "Clipped" to refer to a column that is out of sight because of scrolling/clipping.
+// This is in contrast with some user-facing api such as IsItemVisible() / IsRectVisible() which use "Visible" to mean "not clipped".
+struct ImGuiTableColumn
+{
+ ImGuiTableColumnFlags Flags; // Flags after some patching (not directly same as provided by user). See ImGuiTableColumnFlags_
+ float WidthGiven; // Final/actual width visible == (MaxX - MinX), locked in TableUpdateLayout(). May be > WidthRequest to honor minimum width, may be < WidthRequest to honor shrinking columns down in tight space.
+ float MinX; // Absolute positions
+ float MaxX;
+ float WidthRequest; // Master width absolute value when !(Flags & _WidthStretch). When Stretch this is derived every frame from StretchWeight in TableUpdateLayout()
+ float WidthAuto; // Automatic width
+ float StretchWeight; // Master width weight when (Flags & _WidthStretch). Often around ~1.0f initially.
+ float InitStretchWeightOrWidth; // Value passed to TableSetupColumn(). For Width it is a content width (_without padding_).
+ ImRect ClipRect; // Clipping rectangle for the column
+ ImGuiID UserID; // Optional, value passed to TableSetupColumn()
+ float WorkMinX; // Contents region min ~(MinX + CellPaddingX + CellSpacingX1) == cursor start position when entering column
+ float WorkMaxX; // Contents region max ~(MaxX - CellPaddingX - CellSpacingX2)
+ float ItemWidth; // Current item width for the column, preserved across rows
+ float ContentMaxXFrozen; // Contents maximum position for frozen rows (apart from headers), from which we can infer content width.
+ float ContentMaxXUnfrozen;
+ float ContentMaxXHeadersUsed; // Contents maximum position for headers rows (regardless of freezing). TableHeader() automatically softclip itself + report ideal desired size, to avoid creating extraneous draw calls
+ float ContentMaxXHeadersIdeal;
+ ImS16 NameOffset; // Offset into parent ColumnsNames[]
+ ImGuiTableColumnIdx DisplayOrder; // Index within Table's IndexToDisplayOrder[] (column may be reordered by users)
+ ImGuiTableColumnIdx IndexWithinEnabledSet; // Index within enabled/visible set (<= IndexToDisplayOrder)
+ ImGuiTableColumnIdx PrevEnabledColumn; // Index of prev enabled/visible column within Columns[], -1 if first enabled/visible column
+ ImGuiTableColumnIdx NextEnabledColumn; // Index of next enabled/visible column within Columns[], -1 if last enabled/visible column
+ ImGuiTableColumnIdx SortOrder; // Index of this column within sort specs, -1 if not sorting on this column, 0 for single-sort, may be >0 on multi-sort
+ ImGuiTableDrawChannelIdx DrawChannelCurrent; // Index within DrawSplitter.Channels[]
+ ImGuiTableDrawChannelIdx DrawChannelFrozen;
+ ImGuiTableDrawChannelIdx DrawChannelUnfrozen;
+ bool IsEnabled; // Is the column not marked Hidden by the user? (even if off view, e.g. clipped by scrolling).
+ bool IsEnabledNextFrame;
+ bool IsVisibleX; // Is actually in view (e.g. overlapping the host window clipping rectangle, not scrolled).
+ bool IsVisibleY;
+ bool IsRequestOutput; // Return value for TableSetColumnIndex() / TableNextColumn(): whether we request user to output contents or not.
+ bool IsSkipItems; // Do we want item submissions to this column to be completely ignored (no layout will happen).
+ bool IsPreserveWidthAuto;
+ ImS8 NavLayerCurrent; // ImGuiNavLayer in 1 byte
+ ImU8 AutoFitQueue; // Queue of 8 values for the next 8 frames to request auto-fit
+ ImU8 CannotSkipItemsQueue; // Queue of 8 values for the next 8 frames to disable Clipped/SkipItem
+ ImU8 SortDirection : 2; // ImGuiSortDirection_Ascending or ImGuiSortDirection_Descending
+ ImU8 SortDirectionsAvailCount : 2; // Number of available sort directions (0 to 3)
+ ImU8 SortDirectionsAvailMask : 4; // Mask of available sort directions (1-bit each)
+ ImU8 SortDirectionsAvailList; // Ordered of available sort directions (2-bits each)
+
+ ImGuiTableColumn()
+ {
+ memset(this, 0, sizeof(*this));
+ StretchWeight = WidthRequest = -1.0f;
+ NameOffset = -1;
+ DisplayOrder = IndexWithinEnabledSet = -1;
+ PrevEnabledColumn = NextEnabledColumn = -1;
+ SortOrder = -1;
+ SortDirection = ImGuiSortDirection_None;
+ DrawChannelCurrent = DrawChannelFrozen = DrawChannelUnfrozen = (ImU8)-1;
+ }
+};
+
+// Transient cell data stored per row.
+// sizeof() ~ 6
+struct ImGuiTableCellData
+{
+ ImU32 BgColor; // Actual color
+ ImGuiTableColumnIdx Column; // Column number
+};
+
+// FIXME-TABLE: transient data could be stored in a per-stacked table structure: DrawSplitter, SortSpecs, incoming RowData
+struct ImGuiTable
+{
+ ImGuiID ID;
+ ImGuiTableFlags Flags;
+ void* RawData; // Single allocation to hold Columns[], DisplayOrderToIndex[] and RowCellData[]
+ ImSpan Columns; // Point within RawData[]
+ ImSpan DisplayOrderToIndex; // Point within RawData[]. Store display order of columns (when not reordered, the values are 0...Count-1)
+ ImSpan RowCellData; // Point within RawData[]. Store cells background requests for current row.
+ ImU64 EnabledMaskByDisplayOrder; // Column DisplayOrder -> IsEnabled map
+ ImU64 EnabledMaskByIndex; // Column Index -> IsEnabled map (== not hidden by user/api) in a format adequate for iterating column without touching cold data
+ ImU64 VisibleMaskByIndex; // Column Index -> IsVisibleX|IsVisibleY map (== not hidden by user/api && not hidden by scrolling/cliprect)
+ ImU64 RequestOutputMaskByIndex; // Column Index -> IsVisible || AutoFit (== expect user to submit items)
+ ImGuiTableFlags SettingsLoadedFlags; // Which data were loaded from the .ini file (e.g. when order is not altered we won't save order)
+ int SettingsOffset; // Offset in g.SettingsTables
+ int LastFrameActive;
+ int ColumnsCount; // Number of columns declared in BeginTable()
+ int CurrentRow;
+ int CurrentColumn;
+ ImS16 InstanceCurrent; // Count of BeginTable() calls with same ID in the same frame (generally 0). This is a little bit similar to BeginCount for a window, but multiple table with same ID look are multiple tables, they are just synched.
+ ImS16 InstanceInteracted; // Mark which instance (generally 0) of the same ID is being interacted with
+ float RowPosY1;
+ float RowPosY2;
+ float RowMinHeight; // Height submitted to TableNextRow()
+ float RowTextBaseline;
+ float RowIndentOffsetX;
+ ImGuiTableRowFlags RowFlags : 16; // Current row flags, see ImGuiTableRowFlags_
+ ImGuiTableRowFlags LastRowFlags : 16;
+ int RowBgColorCounter; // Counter for alternating background colors (can be fast-forwarded by e.g clipper), not same as CurrentRow because header rows typically don't increase this.
+ ImU32 RowBgColor[2]; // Background color override for current row.
+ ImU32 BorderColorStrong;
+ ImU32 BorderColorLight;
+ float BorderX1;
+ float BorderX2;
+ float HostIndentX;
+ float MinColumnWidth;
+ float OuterPaddingX;
+ float CellPaddingX; // Padding from each borders
+ float CellPaddingY;
+ float CellSpacingX1; // Spacing between non-bordered cells
+ float CellSpacingX2;
+ float LastOuterHeight; // Outer height from last frame
+ float LastFirstRowHeight; // Height of first row from last frame
+ float InnerWidth; // User value passed to BeginTable(), see comments at the top of BeginTable() for details.
+ float ColumnsGivenWidth; // Sum of current column width
+ float ColumnsAutoFitWidth; // Sum of ideal column width in order nothing to be clipped, used for auto-fitting and content width submission in outer window
+ float ResizedColumnNextWidth;
+ float ResizeLockMinContentsX2; // Lock minimum contents width while resizing down in order to not create feedback loops. But we allow growing the table.
+ float RefScale; // Reference scale to be able to rescale columns on font/dpi changes.
+ ImRect OuterRect; // Note: for non-scrolling table, OuterRect.Max.y is often FLT_MAX until EndTable(), unless a height has been specified in BeginTable().
+ ImRect InnerRect; // InnerRect but without decoration. As with OuterRect, for non-scrolling tables, InnerRect.Max.y is
+ ImRect WorkRect;
+ ImRect InnerClipRect;
+ ImRect BgClipRect; // We use this to cpu-clip cell background color fill
+ ImRect Bg0ClipRectForDrawCmd; // Actual ImDrawCmd clip rect for BG0/1 channel. This tends to be == OuterWindow->ClipRect at BeginTable() because output in BG0/BG1 is cpu-clipped
+ ImRect Bg2ClipRectForDrawCmd; // Actual ImDrawCmd clip rect for BG2 channel. This tends to be a correct, tight-fit, because output to BG2 are done by widgets relying on regular ClipRect.
+ ImRect HostClipRect; // This is used to check if we can eventually merge our columns draw calls into the current draw call of the current window.
+ ImRect HostBackupWorkRect; // Backup of InnerWindow->WorkRect at the end of BeginTable()
+ ImRect HostBackupParentWorkRect; // Backup of InnerWindow->ParentWorkRect at the end of BeginTable()
+ ImRect HostBackupInnerClipRect; // Backup of InnerWindow->ClipRect during PushTableBackground()/PopTableBackground()
+ ImVec2 HostBackupPrevLineSize; // Backup of InnerWindow->DC.PrevLineSize at the end of BeginTable()
+ ImVec2 HostBackupCurrLineSize; // Backup of InnerWindow->DC.CurrLineSize at the end of BeginTable()
+ ImVec2 HostBackupCursorMaxPos; // Backup of InnerWindow->DC.CursorMaxPos at the end of BeginTable()
+ ImVec2 UserOuterSize; // outer_size.x passed to BeginTable()
+ ImVec1 HostBackupColumnsOffset; // Backup of OuterWindow->DC.ColumnsOffset at the end of BeginTable()
+ float HostBackupItemWidth; // Backup of OuterWindow->DC.ItemWidth at the end of BeginTable()
+ int HostBackupItemWidthStackSize;// Backup of OuterWindow->DC.ItemWidthStack.Size at the end of BeginTable()
+ ImGuiWindow* OuterWindow; // Parent window for the table
+ ImGuiWindow* InnerWindow; // Window holding the table data (== OuterWindow or a child window)
+ ImGuiTextBuffer ColumnsNames; // Contiguous buffer holding columns names
+ ImDrawListSplitter DrawSplitter; // We carry our own ImDrawList splitter to allow recursion (FIXME: could be stored outside, worst case we need 1 splitter per recursing table)
+ ImGuiTableColumnSortSpecs SortSpecsSingle;
+ ImVector SortSpecsMulti; // FIXME-OPT: Using a small-vector pattern would work be good.
+ ImGuiTableSortSpecs SortSpecs; // Public facing sorts specs, this is what we return in TableGetSortSpecs()
+ ImGuiTableColumnIdx SortSpecsCount;
+ ImGuiTableColumnIdx ColumnsEnabledCount; // Number of enabled columns (<= ColumnsCount)
+ ImGuiTableColumnIdx ColumnsEnabledFixedCount; // Number of enabled columns (<= ColumnsCount)
+ ImGuiTableColumnIdx DeclColumnsCount; // Count calls to TableSetupColumn()
+ ImGuiTableColumnIdx HoveredColumnBody; // Index of column whose visible region is being hovered. Important: == ColumnsCount when hovering empty region after the right-most column!
+ ImGuiTableColumnIdx HoveredColumnBorder; // Index of column whose right-border is being hovered (for resizing).
+ ImGuiTableColumnIdx AutoFitSingleColumn; // Index of single column requesting auto-fit.
+ ImGuiTableColumnIdx ResizedColumn; // Index of column being resized. Reset when InstanceCurrent==0.
+ ImGuiTableColumnIdx LastResizedColumn; // Index of column being resized from previous frame.
+ ImGuiTableColumnIdx HeldHeaderColumn; // Index of column header being held.
+ ImGuiTableColumnIdx ReorderColumn; // Index of column being reordered. (not cleared)
+ ImGuiTableColumnIdx ReorderColumnDir; // -1 or +1
+ ImGuiTableColumnIdx LeftMostStretchedColumn; // Index of left-most stretched column.
+ ImGuiTableColumnIdx RightMostStretchedColumn; // Index of right-most stretched column.
+ ImGuiTableColumnIdx RightMostEnabledColumn; // Index of right-most non-hidden column.
+ ImGuiTableColumnIdx ContextPopupColumn; // Column right-clicked on, of -1 if opening context menu from a neutral/empty spot
+ ImGuiTableColumnIdx FreezeRowsRequest; // Requested frozen rows count
+ ImGuiTableColumnIdx FreezeRowsCount; // Actual frozen row count (== FreezeRowsRequest, or == 0 when no scrolling offset)
+ ImGuiTableColumnIdx FreezeColumnsRequest; // Requested frozen columns count
+ ImGuiTableColumnIdx FreezeColumnsCount; // Actual frozen columns count (== FreezeColumnsRequest, or == 0 when no scrolling offset)
+ ImGuiTableColumnIdx RowCellDataCurrent; // Index of current RowCellData[] entry in current row
+ ImGuiTableDrawChannelIdx DummyDrawChannel; // Redirect non-visible columns here.
+ ImGuiTableDrawChannelIdx Bg2DrawChannelCurrent; // For Selectable() and other widgets drawing accross columns after the freezing line. Index within DrawSplitter.Channels[]
+ ImGuiTableDrawChannelIdx Bg2DrawChannelUnfrozen;
+ bool IsLayoutLocked; // Set by TableUpdateLayout() which is called when beginning the first row.
+ bool IsInsideRow; // Set when inside TableBeginRow()/TableEndRow().
+ bool IsInitializing;
+ bool IsSortSpecsDirty;
+ bool IsUsingHeaders; // Set when the first row had the ImGuiTableRowFlags_Headers flag.
+ bool IsContextPopupOpen; // Set when default context menu is open (also see: ContextPopupColumn, InstanceInteracted).
+ bool IsSettingsRequestLoad;
+ bool IsSettingsDirty; // Set when table settings have changed and needs to be reported into ImGuiTableSetttings data.
+ bool IsDefaultDisplayOrder; // Set when display order is unchanged from default (DisplayOrder contains 0...Count-1)
+ bool IsResetAllRequest;
+ bool IsResetDisplayOrderRequest;
+ bool IsUnfrozenRows; // Set when we got past the frozen row.
+ bool IsDefaultSizingPolicy; // Set if user didn't explicitely set a sizing policy in BeginTable()
+ bool MemoryCompacted;
+ bool HostSkipItems; // Backup of InnerWindow->SkipItem at the end of BeginTable(), because we will overwrite InnerWindow->SkipItem on a per-column basis
+
+ IMGUI_API ImGuiTable() { memset(this, 0, sizeof(*this)); LastFrameActive = -1; }
+ IMGUI_API ~ImGuiTable() { IM_FREE(RawData); }
+};
+
+// sizeof() ~ 12
+struct ImGuiTableColumnSettings
+{
+ float WidthOrWeight;
+ ImGuiID UserID;
+ ImGuiTableColumnIdx Index;
+ ImGuiTableColumnIdx DisplayOrder;
+ ImGuiTableColumnIdx SortOrder;
+ ImU8 SortDirection : 2;
+ ImU8 IsEnabled : 1; // "Visible" in ini file
+ ImU8 IsStretch : 1;
+
+ ImGuiTableColumnSettings()
+ {
+ WidthOrWeight = 0.0f;
+ UserID = 0;
+ Index = -1;
+ DisplayOrder = SortOrder = -1;
+ SortDirection = ImGuiSortDirection_None;
+ IsEnabled = 1;
+ IsStretch = 0;
+ }
+};
+
+// This is designed to be stored in a single ImChunkStream (1 header followed by N ImGuiTableColumnSettings, etc.)
+struct ImGuiTableSettings
+{
+ ImGuiID ID; // Set to 0 to invalidate/delete the setting
+ ImGuiTableFlags SaveFlags; // Indicate data we want to save using the Resizable/Reorderable/Sortable/Hideable flags (could be using its own flags..)
+ float RefScale; // Reference scale to be able to rescale columns on font/dpi changes.
+ ImGuiTableColumnIdx ColumnsCount;
+ ImGuiTableColumnIdx ColumnsCountMax; // Maximum number of columns this settings instance can store, we can recycle a settings instance with lower number of columns but not higher
+ bool WantApply; // Set when loaded from .ini data (to enable merging/loading .ini data into an already running context)
+
+ ImGuiTableSettings() { memset(this, 0, sizeof(*this)); }
+ ImGuiTableColumnSettings* GetColumnSettings() { return (ImGuiTableColumnSettings*)(this + 1); }
+};
+
+#endif // #ifdef IMGUI_HAS_TABLE
+
+//-----------------------------------------------------------------------------
+// [SECTION] ImGui internal API
+// No guarantee of forward compatibility here!
//-----------------------------------------------------------------------------
namespace ImGui
{
+ // Windows
// We should always have a CurrentWindow in the stack (there is an implicit "Debug" window)
// If this ever crash because g.CurrentWindow is NULL it means that either
// - ImGui::NewFrame() has never been called, which is illegal.
@@ -1679,25 +2161,28 @@ namespace ImGui
inline ImGuiWindow* GetCurrentWindow() { ImGuiContext& g = *GImGui; g.CurrentWindow->WriteAccessed = true; return g.CurrentWindow; }
IMGUI_API ImGuiWindow* FindWindowByID(ImGuiID id);
IMGUI_API ImGuiWindow* FindWindowByName(const char* name);
- IMGUI_API void FocusWindow(ImGuiWindow* window);
- IMGUI_API void FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window);
- IMGUI_API void BringWindowToFocusFront(ImGuiWindow* window);
- IMGUI_API void BringWindowToDisplayFront(ImGuiWindow* window);
- IMGUI_API void BringWindowToDisplayBack(ImGuiWindow* window);
IMGUI_API void UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window);
- IMGUI_API ImVec2 CalcWindowExpectedSize(ImGuiWindow* window);
+ IMGUI_API ImVec2 CalcWindowNextAutoFitSize(ImGuiWindow* window);
IMGUI_API bool IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent);
+ IMGUI_API bool IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below);
IMGUI_API bool IsWindowNavFocusable(ImGuiWindow* window);
IMGUI_API ImRect GetWindowAllowedExtentRect(ImGuiWindow* window);
IMGUI_API void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond = 0);
IMGUI_API void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond = 0);
IMGUI_API void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond = 0);
- IMGUI_API void GcCompactTransientWindowBuffers(ImGuiWindow* window);
- IMGUI_API void GcAwakeTransientWindowBuffers(ImGuiWindow* window);
+ IMGUI_API void SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size);
+ // Windows: Display Order and Focus Order
+ IMGUI_API void FocusWindow(ImGuiWindow* window);
+ IMGUI_API void FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window);
+ IMGUI_API void BringWindowToFocusFront(ImGuiWindow* window);
+ IMGUI_API void BringWindowToDisplayFront(ImGuiWindow* window);
+ IMGUI_API void BringWindowToDisplayBack(ImGuiWindow* window);
+
+ // Fonts, drawing
IMGUI_API void SetCurrentFont(ImFont* font);
inline ImFont* GetDefaultFont() { ImGuiContext& g = *GImGui; return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0]; }
- inline ImDrawList* GetForegroundDrawList(ImGuiWindow* window) { return GetForegroundDrawList(window->Viewport); }
+ inline ImDrawList* GetForegroundDrawList(ImGuiWindow* window) { IM_UNUSED(window); ImGuiContext& g = *GImGui; return &g.ForegroundDrawList; } // This seemingly unnecessary wrapper simplifies compatibility between the 'master' and 'docking' branches.
// Init
IMGUI_API void Initialize(ImGuiContext* context);
@@ -1706,43 +2191,46 @@ namespace ImGui
// NewFrame
IMGUI_API void UpdateHoveredWindowAndCaptureFlags();
IMGUI_API void StartMouseMovingWindow(ImGuiWindow* window);
- IMGUI_API void StartMouseDragFromTitleBar(ImGuiWindow* window, ImGuiDockNode* node, bool from_collapse_button);
IMGUI_API void UpdateMouseMovingWindowNewFrame();
IMGUI_API void UpdateMouseMovingWindowEndFrame();
- // Viewports
- IMGUI_API void TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos);
- IMGUI_API void ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale);
- IMGUI_API void DestroyPlatformWindow(ImGuiViewportP* viewport);
- IMGUI_API void ShowViewportThumbnails();
+ // Generic context hooks
+ IMGUI_API ImGuiID AddContextHook(ImGuiContext* context, const ImGuiContextHook* hook);
+ IMGUI_API void RemoveContextHook(ImGuiContext* context, ImGuiID hook_to_remove);
+ IMGUI_API void CallContextHooks(ImGuiContext* context, ImGuiContextHookType type);
// Settings
IMGUI_API void MarkIniSettingsDirty();
IMGUI_API void MarkIniSettingsDirty(ImGuiWindow* window);
+ IMGUI_API void ClearIniSettings();
IMGUI_API ImGuiWindowSettings* CreateNewWindowSettings(const char* name);
IMGUI_API ImGuiWindowSettings* FindWindowSettings(ImGuiID id);
IMGUI_API ImGuiWindowSettings* FindOrCreateWindowSettings(const char* name);
IMGUI_API ImGuiSettingsHandler* FindSettingsHandler(const char* type_name);
// Scrolling
- IMGUI_API void SetScrollX(ImGuiWindow* window, float new_scroll_x);
- IMGUI_API void SetScrollY(ImGuiWindow* window, float new_scroll_y);
- IMGUI_API void SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio = 0.5f);
- IMGUI_API void SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio = 0.5f);
+ IMGUI_API void SetNextWindowScroll(const ImVec2& scroll); // Use -1.0f on one axis to leave as-is
+ IMGUI_API void SetScrollX(ImGuiWindow* window, float scroll_x);
+ IMGUI_API void SetScrollY(ImGuiWindow* window, float scroll_y);
+ IMGUI_API void SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio);
+ IMGUI_API void SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio);
IMGUI_API ImVec2 ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_rect);
// Basic Accessors
- inline ImGuiID GetItemID() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DC.LastItemId; }
+ inline ImGuiID GetItemID() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DC.LastItemId; } // Get ID of last item (~~ often same ImGui::GetID(label) beforehand)
+ inline ImGuiItemStatusFlags GetItemStatusFlags() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DC.LastItemStatusFlags; }
inline ImGuiID GetActiveID() { ImGuiContext& g = *GImGui; return g.ActiveId; }
inline ImGuiID GetFocusID() { ImGuiContext& g = *GImGui; return g.NavId; }
+ inline ImGuiItemFlags GetItemsFlags() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DC.ItemFlags; }
IMGUI_API void SetActiveID(ImGuiID id, ImGuiWindow* window);
IMGUI_API void SetFocusID(ImGuiID id, ImGuiWindow* window);
IMGUI_API void ClearActiveID();
IMGUI_API ImGuiID GetHoveredID();
IMGUI_API void SetHoveredID(ImGuiID id);
IMGUI_API void KeepAliveID(ImGuiID id);
- IMGUI_API void MarkItemEdited(ImGuiID id);
- IMGUI_API void PushOverrideID(ImGuiID id);
+ IMGUI_API void MarkItemEdited(ImGuiID id); // Mark data associated to given item as "edited", used by IsItemDeactivatedAfterEdit() function.
+ IMGUI_API void PushOverrideID(ImGuiID id); // Push given value as-is at the top of the ID stack (whereas PushID combines old and new hashes)
+ IMGUI_API ImGuiID GetIDWithSeed(const char* str_id_begin, const char* str_id_end, ImGuiID seed);
// Basic Helpers for widget code
IMGUI_API void ItemSize(const ImVec2& size, float text_baseline_y = -1.0f);
@@ -1750,6 +2238,7 @@ namespace ImGui
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 void SetLastItemData(ImGuiWindow* window, ImGuiID item_id, ImGuiItemStatusFlags status_flags, const ImRect& item_rect);
IMGUI_API bool FocusableItemRegister(ImGuiWindow* window, ImGuiID id); // Return true if focus is requested
IMGUI_API void FocusableItemUnregister(ImGuiWindow* window);
IMGUI_API ImVec2 CalcItemSize(ImVec2 size, float default_w, float default_h);
@@ -1757,26 +2246,27 @@ namespace ImGui
IMGUI_API void PushMultiItemsWidths(int components, float width_full);
IMGUI_API void PushItemFlag(ImGuiItemFlags option, bool enabled);
IMGUI_API void PopItemFlag();
- IMGUI_API bool IsItemToggledSelection(); // Was the last item selection toggled? (after Selectable(), TreeNode() etc. We only returns toggle _event_ in order to handle clipping correctly)
+ IMGUI_API bool IsItemToggledSelection(); // Was the last item selection toggled? (after Selectable(), TreeNode() etc. We only returns toggle _event_ in order to handle clipping correctly)
IMGUI_API ImVec2 GetContentRegionMaxAbs();
IMGUI_API void ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess);
// Logging/Capture
- IMGUI_API void LogBegin(ImGuiLogType type, int auto_open_depth); // -> BeginCapture() when we design v2 api, for now stay under the radar by using the old name.
- IMGUI_API void LogToBuffer(int auto_open_depth = -1); // Start logging/capturing to internal buffer
+ IMGUI_API void LogBegin(ImGuiLogType type, int auto_open_depth); // -> BeginCapture() when we design v2 api, for now stay under the radar by using the old name.
+ IMGUI_API void LogToBuffer(int auto_open_depth = -1); // Start logging/capturing to internal buffer
// Popups, Modals, Tooltips
- IMGUI_API void OpenPopupEx(ImGuiID id);
+ IMGUI_API bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags);
+ IMGUI_API void OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags = ImGuiPopupFlags_None);
IMGUI_API void ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup);
IMGUI_API void ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup);
- IMGUI_API bool IsPopupOpen(ImGuiID id); // Test for id within current popup stack level (currently begin-ed into); this doesn't scan the whole popup stack!
+ IMGUI_API bool IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags);
IMGUI_API bool BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags);
- IMGUI_API void BeginTooltipEx(ImGuiWindowFlags extra_flags, bool override_previous_tooltip = true);
+ IMGUI_API void BeginTooltipEx(ImGuiWindowFlags extra_flags, ImGuiTooltipFlags tooltip_flags);
IMGUI_API ImGuiWindow* GetTopMostPopupModal();
IMGUI_API ImVec2 FindBestWindowPosForPopup(ImGuiWindow* window);
- IMGUI_API ImVec2 FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy = ImGuiPopupPositionPolicy_Default);
+ IMGUI_API ImVec2 FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy);
- // Navigation
+ // Gamepad/Keyboard Navigation
IMGUI_API void NavInitWindow(ImGuiWindow* window, bool force_reinit);
IMGUI_API bool NavMoveRequestButNoResultYet();
IMGUI_API void NavMoveRequestCancel();
@@ -1786,113 +2276,128 @@ namespace ImGui
IMGUI_API ImVec2 GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInputReadMode mode, float slow_factor = 0.0f, float fast_factor = 0.0f);
IMGUI_API int CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate);
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 void SetNavID(ImGuiID id, int nav_layer);
- IMGUI_API void SetNavIDWithRectRel(ImGuiID id, int nav_layer, const ImRect& rect_rel);
+ IMGUI_API void SetNavID(ImGuiID id, int nav_layer, ImGuiID focus_scope_id);
+ IMGUI_API void SetNavIDWithRectRel(ImGuiID id, int nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel);
+
+ // Focus Scope (WIP)
+ // This is generally used to identify a selection set (multiple of which may be in the same window), as selection
+ // patterns generally need to react (e.g. clear selection) when landing on an item of the set.
+ IMGUI_API void PushFocusScope(ImGuiID id);
+ IMGUI_API void PopFocusScope();
+ inline ImGuiID GetFocusedFocusScope() { ImGuiContext& g = *GImGui; return g.NavFocusScopeId; } // Focus scope which is actually active
+ inline ImGuiID GetFocusScope() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DC.NavFocusScopeIdCurrent; } // Focus scope we are outputting into, set by PushFocusScope()
// Inputs
// FIXME: Eventually we should aim to move e.g. IsActiveIdUsingKey() into IsKeyXXX functions.
+ IMGUI_API void SetItemUsingMouseWheel();
inline bool IsActiveIdUsingNavDir(ImGuiDir dir) { ImGuiContext& g = *GImGui; return (g.ActiveIdUsingNavDirMask & (1 << dir)) != 0; }
inline bool IsActiveIdUsingNavInput(ImGuiNavInput input) { ImGuiContext& g = *GImGui; return (g.ActiveIdUsingNavInputMask & (1 << input)) != 0; }
inline bool IsActiveIdUsingKey(ImGuiKey key) { ImGuiContext& g = *GImGui; IM_ASSERT(key < 64); return (g.ActiveIdUsingKeyInputMask & ((ImU64)1 << key)) != 0; }
- IMGUI_API bool IsMouseDragPastThreshold(int button, float lock_threshold = -1.0f);
+ IMGUI_API bool IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold = -1.0f);
inline bool IsKeyPressedMap(ImGuiKey key, bool repeat = true) { ImGuiContext& g = *GImGui; const int key_index = g.IO.KeyMap[key]; return (key_index >= 0) ? IsKeyPressed(key_index, repeat) : false; }
inline bool IsNavInputDown(ImGuiNavInput n) { ImGuiContext& g = *GImGui; return g.IO.NavInputs[n] > 0.0f; }
- inline bool IsNavInputPressed(ImGuiNavInput n, ImGuiInputReadMode mode) { return GetNavInputAmount(n, mode) > 0.0f; }
- inline bool IsNavInputPressedAnyOfTwo(ImGuiNavInput n1, ImGuiNavInput n2, ImGuiInputReadMode mode) { return (GetNavInputAmount(n1, mode) + GetNavInputAmount(n2, mode)) > 0.0f; }
-
- // Docking
- // (some functions are only declared in imgui.cpp, see Docking section)
- IMGUI_API void DockContextInitialize(ImGuiContext* ctx);
- IMGUI_API void DockContextShutdown(ImGuiContext* ctx);
- IMGUI_API void DockContextOnLoadSettings(ImGuiContext* ctx);
- IMGUI_API void DockContextRebuildNodes(ImGuiContext* ctx);
- IMGUI_API void DockContextUpdateUndocking(ImGuiContext* ctx);
- IMGUI_API void DockContextUpdateDocking(ImGuiContext* ctx);
- IMGUI_API ImGuiID DockContextGenNodeID(ImGuiContext* ctx);
- IMGUI_API void DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer);
- IMGUI_API void DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window);
- IMGUI_API void DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node);
- IMGUI_API bool DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos);
- inline ImGuiDockNode* DockNodeGetRootNode(ImGuiDockNode* node) { while (node->ParentNode) node = node->ParentNode; return node; }
- IMGUI_API bool GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window);
- IMGUI_API void BeginDocked(ImGuiWindow* window, bool* p_open);
- IMGUI_API void BeginAsDockableDragDropSource(ImGuiWindow* window);
- IMGUI_API void BeginAsDockableDragDropTarget(ImGuiWindow* window);
- IMGUI_API void SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond);
-
- // Docking - Builder function needs to be generally called before the DockSpace() node is submitted.
- // - The DockBuilderXXX functions are designed to _eventually_ become a public API, but it is too early to expose it and guarantee stability.
- // - You can create dockspace _or_ floating nodes with this API. To create a dockspace node, make sure to set the ImGuiDockNodeFlags_DockSpace flag.
- // - If you intend to split the node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand.
- // - Call DockBuilderFinish() after you are done.
- // - Important: do not hold on ImGuiDockNode* pointers! They may be invalidated by any split/merge/remove operation and every frame.
- IMGUI_API void DockBuilderDockWindow(const char* window_name, ImGuiID node_id);
- IMGUI_API ImGuiDockNode*DockBuilderGetNode(ImGuiID node_id);
- inline ImGuiDockNode* DockBuilderGetCentralNode(ImGuiID node_id) { ImGuiDockNode* node = DockBuilderGetNode(node_id); if (!node) return NULL; return DockNodeGetRootNode(node)->CentralNode; }
- IMGUI_API ImGuiID DockBuilderAddNode(ImGuiID node_id = 0, ImGuiDockNodeFlags flags = 0);
- IMGUI_API void DockBuilderRemoveNode(ImGuiID node_id); // Remove node and all its child, undock all windows
- IMGUI_API void DockBuilderRemoveNodeDockedWindows(ImGuiID node_id, bool clear_persistent_docking_references = true);
- IMGUI_API void DockBuilderRemoveNodeChildNodes(ImGuiID node_id); // Remove all split/hierarchy. All remaining docked windows will be re-docked to the root.
- IMGUI_API void DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos);
- IMGUI_API void DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size);
- IMGUI_API ImGuiID DockBuilderSplitNode(ImGuiID node_id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir);
- IMGUI_API void DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector* in_window_remap_pairs);
- IMGUI_API void DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector* out_node_remap_pairs);
- IMGUI_API void DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name);
- IMGUI_API void DockBuilderFinish(ImGuiID node_id);
+ inline bool IsNavInputTest(ImGuiNavInput n, ImGuiInputReadMode rm) { return (GetNavInputAmount(n, rm) > 0.0f); }
+ IMGUI_API ImGuiKeyModFlags GetMergedKeyModFlags();
// Drag and Drop
IMGUI_API bool BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id);
IMGUI_API void ClearDragDrop();
IMGUI_API bool IsDragDropPayloadBeingAccepted();
- // New Columns API (FIXME-WIP)
- IMGUI_API void BeginColumns(const char* str_id, int count, ImGuiColumnsFlags flags = 0); // setup number of columns. use an identifier to distinguish multiple column sets. close with EndColumns().
- IMGUI_API void EndColumns(); // close columns
+ // Internal Columns API (this is not exposed because we will encourage transitioning to the Tables API)
+ IMGUI_API void SetWindowClipRectBeforeSetChannel(ImGuiWindow* window, const ImRect& clip_rect);
+ IMGUI_API void BeginColumns(const char* str_id, int count, ImGuiOldColumnFlags flags = 0); // setup number of columns. use an identifier to distinguish multiple column sets. close with EndColumns().
+ IMGUI_API void EndColumns(); // close columns
IMGUI_API void PushColumnClipRect(int column_index);
IMGUI_API void PushColumnsBackground();
IMGUI_API void PopColumnsBackground();
IMGUI_API ImGuiID GetColumnsID(const char* str_id, int count);
- IMGUI_API ImGuiColumns* FindOrCreateColumns(ImGuiWindow* window, ImGuiID id);
- IMGUI_API float GetColumnOffsetFromNorm(const ImGuiColumns* columns, float offset_norm);
- IMGUI_API float GetColumnNormFromOffset(const ImGuiColumns* columns, float offset);
+ IMGUI_API ImGuiOldColumns* FindOrCreateColumns(ImGuiWindow* window, ImGuiID id);
+ IMGUI_API float GetColumnOffsetFromNorm(const ImGuiOldColumns* columns, float offset_norm);
+ IMGUI_API float GetColumnNormFromOffset(const ImGuiOldColumns* columns, float offset);
+
+ // Tables: Candidates for public API
+ IMGUI_API void TableOpenContextMenu(int column_n = -1);
+ IMGUI_API void TableSetColumnWidth(int column_n, float width);
+ IMGUI_API void TableSetColumnSortDirection(int column_n, ImGuiSortDirection sort_direction, bool append_to_sort_specs);
+ IMGUI_API int TableGetHoveredColumn(); // May use (TableGetColumnFlags() & ImGuiTableColumnFlags_IsHovered) instead. Return hovered column. return -1 when table is not hovered. return columns_count if the unused space at the right of visible columns is hovered.
+ IMGUI_API float TableGetHeaderRowHeight();
+ IMGUI_API void TablePushBackgroundChannel();
+ IMGUI_API void TablePopBackgroundChannel();
+
+ // Tables: Internals
+ IMGUI_API ImGuiTable* TableFindByID(ImGuiID id);
+ IMGUI_API bool BeginTableEx(const char* name, ImGuiID id, int columns_count, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0, 0), float inner_width = 0.0f);
+ IMGUI_API void TableBeginInitMemory(ImGuiTable* table, int columns_count);
+ IMGUI_API void TableBeginApplyRequests(ImGuiTable* table);
+ IMGUI_API void TableSetupDrawChannels(ImGuiTable* table);
+ IMGUI_API void TableUpdateLayout(ImGuiTable* table);
+ IMGUI_API void TableUpdateBorders(ImGuiTable* table);
+ IMGUI_API void TableUpdateColumnsWeightFromWidth(ImGuiTable* table);
+ IMGUI_API void TableDrawBorders(ImGuiTable* table);
+ IMGUI_API void TableDrawContextMenu(ImGuiTable* table);
+ IMGUI_API void TableMergeDrawChannels(ImGuiTable* table);
+ IMGUI_API void TableSortSpecsSanitize(ImGuiTable* table);
+ IMGUI_API void TableSortSpecsBuild(ImGuiTable* table);
+ IMGUI_API ImGuiSortDirection TableGetColumnNextSortDirection(ImGuiTableColumn* column);
+ IMGUI_API void TableFixColumnSortDirection(ImGuiTable* table, ImGuiTableColumn* column);
+ IMGUI_API float TableGetColumnWidthAuto(ImGuiTable* table, ImGuiTableColumn* column);
+ IMGUI_API void TableBeginRow(ImGuiTable* table);
+ IMGUI_API void TableEndRow(ImGuiTable* table);
+ IMGUI_API void TableBeginCell(ImGuiTable* table, int column_n);
+ IMGUI_API void TableEndCell(ImGuiTable* table);
+ IMGUI_API ImRect TableGetCellBgRect(const ImGuiTable* table, int column_n);
+ IMGUI_API const char* TableGetColumnName(const ImGuiTable* table, int column_n);
+ IMGUI_API ImGuiID TableGetColumnResizeID(const ImGuiTable* table, int column_n, int instance_no = 0);
+ IMGUI_API float TableGetMaxColumnWidth(const ImGuiTable* table, int column_n);
+ IMGUI_API void TableSetColumnWidthAutoSingle(ImGuiTable* table, int column_n);
+ IMGUI_API void TableSetColumnWidthAutoAll(ImGuiTable* table);
+ IMGUI_API void TableRemove(ImGuiTable* table);
+ IMGUI_API void TableGcCompactTransientBuffers(ImGuiTable* table);
+ IMGUI_API void TableGcCompactSettings();
+
+ // Tables: Settings
+ IMGUI_API void TableLoadSettings(ImGuiTable* table);
+ IMGUI_API void TableSaveSettings(ImGuiTable* table);
+ IMGUI_API void TableResetSettings(ImGuiTable* table);
+ IMGUI_API ImGuiTableSettings* TableGetBoundSettings(ImGuiTable* table);
+ IMGUI_API void TableSettingsInstallHandler(ImGuiContext* context);
+ IMGUI_API ImGuiTableSettings* TableSettingsCreate(ImGuiID id, int columns_count);
+ IMGUI_API ImGuiTableSettings* TableSettingsFindByID(ImGuiID id);
// Tab Bars
- IMGUI_API bool BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& bb, ImGuiTabBarFlags flags, ImGuiDockNode* dock_node);
+ IMGUI_API bool BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& bb, ImGuiTabBarFlags flags);
IMGUI_API ImGuiTabItem* TabBarFindTabByID(ImGuiTabBar* tab_bar, ImGuiID tab_id);
- IMGUI_API ImGuiTabItem* TabBarFindMostRecentlySelectedTabForActiveWindow(ImGuiTabBar* tab_bar);
- IMGUI_API void TabBarAddTab(ImGuiTabBar* tab_bar, ImGuiTabItemFlags tab_flags, ImGuiWindow* window);
IMGUI_API void TabBarRemoveTab(ImGuiTabBar* tab_bar, ImGuiID tab_id);
IMGUI_API void TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab);
- IMGUI_API void TabBarQueueChangeTabOrder(ImGuiTabBar* tab_bar, const ImGuiTabItem* tab, int dir);
- IMGUI_API bool TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags, ImGuiWindow* docked_window);
+ IMGUI_API void TabBarQueueReorder(ImGuiTabBar* tab_bar, const ImGuiTabItem* tab, int dir);
+ IMGUI_API bool TabBarProcessReorder(ImGuiTabBar* tab_bar);
+ IMGUI_API bool TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags);
IMGUI_API ImVec2 TabItemCalcSize(const char* label, bool has_close_button);
IMGUI_API void TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImU32 col);
- IMGUI_API bool TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id);
+ IMGUI_API void TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id, bool is_contents_visible, bool* out_just_closed, bool* out_text_clipped);
// Render helpers
// AVOID USING OUTSIDE OF IMGUI.CPP! NOT FOR PUBLIC CONSUMPTION. THOSE FUNCTIONS ARE A MESS. THEIR SIGNATURE AND BEHAVIOR WILL CHANGE, THEY NEED TO BE REFACTORED INTO SOMETHING DECENT.
// NB: All position are in absolute pixels coordinates (we are never using window coordinates internally)
IMGUI_API void RenderText(ImVec2 pos, const char* text, const char* text_end = NULL, bool hide_text_after_hash = true);
IMGUI_API void RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width);
- IMGUI_API void RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align = ImVec2(0,0), const ImRect* clip_rect = NULL);
+ IMGUI_API void RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align = ImVec2(0, 0), const ImRect* clip_rect = NULL);
IMGUI_API void RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align = ImVec2(0, 0), const ImRect* clip_rect = NULL);
IMGUI_API void RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end, const ImVec2* text_size_if_known);
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 RenderCheckMark(ImVec2 pos, ImU32 col, float sz);
+ IMGUI_API void RenderColorRectWithAlphaCheckerboard(ImDrawList* draw_list, 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 RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags = ImGuiNavHighlightFlags_TypeDefault); // Navigation highlight
- IMGUI_API void RenderMouseCursor(ImVec2 pos, float scale, ImGuiMouseCursor mouse_cursor = ImGuiMouseCursor_Arrow);
IMGUI_API const char* FindRenderedTextEnd(const char* text, const char* text_end = NULL); // Find the optional ## from which we stop displaying text.
IMGUI_API void LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end = NULL);
// Render helpers (those functions don't access any ImGui state!)
IMGUI_API void RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImU32 col, ImGuiDir dir, float scale = 1.0f);
IMGUI_API void RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col);
+ IMGUI_API void RenderCheckMark(ImDrawList* draw_list, ImVec2 pos, ImU32 col, float sz);
IMGUI_API void RenderMouseCursor(ImDrawList* draw_list, ImVec2 pos, float scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow);
IMGUI_API void RenderArrowPointingAt(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, ImGuiDir direction, ImU32 col);
- IMGUI_API void RenderArrowDockMenu(ImDrawList* draw_list, ImVec2 p_min, float sz, ImU32 col);
IMGUI_API void RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float x_start_norm, float x_end_norm, float rounding);
IMGUI_API void RenderRectFilledWithHole(ImDrawList* draw_list, ImRect outer, ImRect inner, ImU32 col, float rounding);
@@ -1904,19 +2409,24 @@ namespace ImGui
// Widgets
IMGUI_API void TextEx(const char* text, const char* text_end = NULL, ImGuiTextFlags flags = 0);
- IMGUI_API bool ButtonEx(const char* label, const ImVec2& size_arg = ImVec2(0,0), 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);
- IMGUI_API bool CollapseButton(ImGuiID id, const ImVec2& pos, ImGuiDockNode* dock_node);
- IMGUI_API bool ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size_arg, ImGuiButtonFlags flags);
+ IMGUI_API bool CollapseButton(ImGuiID id, const ImVec2& pos);
+ IMGUI_API bool ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size_arg, ImGuiButtonFlags flags = 0);
IMGUI_API void Scrollbar(ImGuiAxis axis);
IMGUI_API bool ScrollbarEx(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* p_scroll_v, float avail_v, float contents_v, ImDrawCornerFlags rounding_corners);
- IMGUI_API ImGuiID GetScrollbarID(ImGuiWindow* window, ImGuiAxis axis);
+ IMGUI_API bool ImageButtonEx(ImGuiID id, ImTextureID texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec2& padding, const ImVec4& bg_col, const ImVec4& tint_col);
+ IMGUI_API ImRect GetWindowScrollbarRect(ImGuiWindow* window, ImGuiAxis axis);
+ IMGUI_API ImGuiID GetWindowScrollbarID(ImGuiWindow* window, ImGuiAxis axis);
+ IMGUI_API ImGuiID GetWindowResizeID(ImGuiWindow* window, int n); // 0..3: corners, 4..7: borders
IMGUI_API void SeparatorEx(ImGuiSeparatorFlags flags);
+ IMGUI_API bool CheckboxFlags(const char* label, ImS64* flags, ImS64 flags_value);
+ IMGUI_API bool CheckboxFlags(const char* label, ImU64* flags, ImU64 flags_value);
// Widgets low-level behaviors
IMGUI_API bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags = 0);
- IMGUI_API bool DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragFlags flags);
- IMGUI_API bool SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb);
+ IMGUI_API bool DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags);
+ IMGUI_API bool SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb);
IMGUI_API bool SplitterBehavior(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend = 0.0f, float hover_visibility_delay = 0.0f);
IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL);
IMGUI_API bool TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags = 0); // Consume previous SetNextItemOpen() data, if any. May return true when logging
@@ -1925,21 +2435,27 @@ namespace ImGui
// Template functions are instantiated in imgui_widgets.cpp for a finite number of types.
// To use them externally (for custom widget) you may need an "extern template" statement in your code in order to link to existing instances and silence Clang warnings (see #2036).
// e.g. " extern template IMGUI_API float RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, float v); "
- template IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, T v_min, T v_max, const char* format, float power, ImGuiDragFlags flags);
- template IMGUI_API bool SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, T* v, T v_min, T v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb);
- template IMGUI_API float SliderCalcRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, float power, float linear_zero_pos);
+ template IMGUI_API float ScaleRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_size);
+ template IMGUI_API T ScaleValueFromRatioT(ImGuiDataType data_type, float t, T v_min, T v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_size);
+ template IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, T v_min, T v_max, const char* format, ImGuiSliderFlags flags);
+ template IMGUI_API bool SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, T* v, T v_min, T v_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb);
template IMGUI_API T RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, T v);
+ template IMGUI_API bool CheckboxFlagsT(const char* label, T* flags, T flags_value);
// Data type helpers
IMGUI_API const ImGuiDataTypeInfo* DataTypeGetInfo(ImGuiDataType data_type);
IMGUI_API int DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* p_data, const char* format);
- IMGUI_API void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* arg_1, const void* arg_2);
+ IMGUI_API void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, const void* arg_1, const void* arg_2);
IMGUI_API bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* p_data, const char* format);
+ IMGUI_API int DataTypeCompare(ImGuiDataType data_type, const void* arg_1, const void* arg_2);
+ IMGUI_API bool DataTypeClamp(ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max);
// InputText
IMGUI_API bool InputTextEx(const char* label, const char* hint, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);
- IMGUI_API bool TempInputTextScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format);
- inline bool TempInputTextIsActive(ImGuiID id) { ImGuiContext& g = *GImGui; return (g.ActiveId == id && g.TempInputTextId == id); }
+ IMGUI_API bool TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* buf, int buf_size, ImGuiInputTextFlags flags);
+ IMGUI_API bool TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min = NULL, const void* p_clamp_max = NULL);
+ inline bool TempInputIsActive(ImGuiID id) { ImGuiContext& g = *GImGui; return (g.ActiveId == id && g.TempInputId == id); }
+ inline ImGuiInputTextState* GetInputTextState(ImGuiID id) { ImGuiContext& g = *GImGui; return (g.InputTextState.ID == id) ? &g.InputTextState : NULL; } // Get input text state if active
// Color
IMGUI_API void ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags);
@@ -1947,56 +2463,81 @@ namespace ImGui
IMGUI_API void ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags flags);
// Plot
- IMGUI_API void PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 frame_size);
+ IMGUI_API int PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 frame_size);
// Shade functions (write over already created vertices)
IMGUI_API void ShadeVertsLinearColorGradientKeepAlpha(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, ImVec2 gradient_p0, ImVec2 gradient_p1, ImU32 col0, ImU32 col1);
IMGUI_API void ShadeVertsLinearUV(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, bool clamp);
+ // Garbage collection
+ IMGUI_API void GcCompactTransientMiscBuffers();
+ IMGUI_API void GcCompactTransientWindowBuffers(ImGuiWindow* window);
+ IMGUI_API void GcAwakeTransientWindowBuffers(ImGuiWindow* window);
+
// Debug Tools
+ IMGUI_API void ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data = NULL);
inline void DebugDrawItemRect(ImU32 col = IM_COL32(255,0,0,255)) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; GetForegroundDrawList(window)->AddRect(window->DC.LastItemRect.Min, window->DC.LastItemRect.Max, col); }
inline void DebugStartItemPicker() { ImGuiContext& g = *GImGui; g.DebugItemPickerActive = true; }
+ IMGUI_API void DebugNodeColumns(ImGuiOldColumns* columns);
+ IMGUI_API void DebugNodeDrawList(ImGuiWindow* window, const ImDrawList* draw_list, const char* label);
+ IMGUI_API void DebugNodeDrawCmdShowMeshAndBoundingBox(ImGuiWindow* window, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb);
+ IMGUI_API void DebugNodeStorage(ImGuiStorage* storage, const char* label);
+ IMGUI_API void DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label);
+ IMGUI_API void DebugNodeTable(ImGuiTable* table);
+ IMGUI_API void DebugNodeTableSettings(ImGuiTableSettings* settings);
+ IMGUI_API void DebugNodeWindow(ImGuiWindow* window, const char* label);
+ IMGUI_API void DebugNodeWindowSettings(ImGuiWindowSettings* settings);
+ IMGUI_API void DebugNodeWindowsList(ImVector* windows, const char* label);
+
} // namespace ImGui
-// ImFontAtlas internals
-IMGUI_API bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas);
-IMGUI_API void ImFontAtlasBuildRegisterDefaultCustomRects(ImFontAtlas* atlas);
-IMGUI_API void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent);
-IMGUI_API void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opaque);
-IMGUI_API void ImFontAtlasBuildFinish(ImFontAtlas* atlas);
-IMGUI_API void ImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256], float in_multiply_factor);
-IMGUI_API void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsigned char* pixels, int x, int y, int w, int h, int stride);
-// Debug Tools
-// Use 'Metrics->Tools->Item Picker' to break into the call-stack of a specific item.
-#ifndef IM_DEBUG_BREAK
-#if defined(__clang__)
-#define IM_DEBUG_BREAK() __builtin_debugtrap()
-#elif defined (_MSC_VER)
-#define IM_DEBUG_BREAK() __debugbreak()
-#else
-#define IM_DEBUG_BREAK() IM_ASSERT(0) // It is expected that you define IM_DEBUG_BREAK() into something that will break nicely in a debugger!
-#endif
-#endif // #ifndef IM_DEBUG_BREAK
+//-----------------------------------------------------------------------------
+// [SECTION] ImFontAtlas internal API
+//-----------------------------------------------------------------------------
+
+// This structure is likely to evolve as we add support for incremental atlas updates
+struct ImFontBuilderIO
+{
+ bool (*FontBuilder_Build)(ImFontAtlas* atlas);
+};
+
+// Helper for font builder
+IMGUI_API const ImFontBuilderIO* ImFontAtlasGetBuilderForStbTruetype();
+IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas* atlas);
+IMGUI_API void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent);
+IMGUI_API void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opaque);
+IMGUI_API void ImFontAtlasBuildFinish(ImFontAtlas* atlas);
+IMGUI_API void ImFontAtlasBuildRender8bppRectFromString(ImFontAtlas* atlas, int atlas_x, int atlas_y, int w, int h, const char* in_str, char in_marker_char, unsigned char in_marker_pixel_value);
+IMGUI_API void ImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256], float in_multiply_factor);
+IMGUI_API void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsigned char* pixels, int x, int y, int w, int h, int stride);
+
+//-----------------------------------------------------------------------------
+// [SECTION] Test Engine specific hooks (imgui_test_engine)
+//-----------------------------------------------------------------------------
-// Test Engine Hooks (imgui_tests)
-//#define IMGUI_ENABLE_TEST_ENGINE
#ifdef IMGUI_ENABLE_TEST_ENGINE
-extern void ImGuiTestEngineHook_PreNewFrame(ImGuiContext* ctx);
-extern void ImGuiTestEngineHook_PostNewFrame(ImGuiContext* ctx);
extern void ImGuiTestEngineHook_ItemAdd(ImGuiContext* ctx, const ImRect& bb, ImGuiID id);
extern void ImGuiTestEngineHook_ItemInfo(ImGuiContext* ctx, ImGuiID id, const char* label, ImGuiItemStatusFlags flags);
+extern void ImGuiTestEngineHook_IdInfo(ImGuiContext* ctx, ImGuiDataType data_type, ImGuiID id, const void* data_id);
+extern void ImGuiTestEngineHook_IdInfo(ImGuiContext* ctx, ImGuiDataType data_type, ImGuiID id, const void* data_id, const void* data_id_end);
extern void ImGuiTestEngineHook_Log(ImGuiContext* ctx, const char* fmt, ...);
-#define IMGUI_TEST_ENGINE_ITEM_ADD(_BB, _ID) ImGuiTestEngineHook_ItemAdd(&g, _BB, _ID) // Register item bounding box
-#define IMGUI_TEST_ENGINE_ITEM_INFO(_ID, _LABEL, _FLAGS) ImGuiTestEngineHook_ItemInfo(&g, _ID, _LABEL, _FLAGS) // Register item label and status flags (optional)
-#define IMGUI_TEST_ENGINE_LOG(_FMT, ...) ImGuiTestEngineHook_Log(&g, _FMT, __VA_ARGS__) // Custom log entry from user land into test log
+#define IMGUI_TEST_ENGINE_ITEM_ADD(_BB,_ID) if (g.TestEngineHookItems) ImGuiTestEngineHook_ItemAdd(&g, _BB, _ID) // Register item bounding box
+#define IMGUI_TEST_ENGINE_ITEM_INFO(_ID,_LABEL,_FLAGS) if (g.TestEngineHookItems) ImGuiTestEngineHook_ItemInfo(&g, _ID, _LABEL, _FLAGS) // Register item label and status flags (optional)
+#define IMGUI_TEST_ENGINE_LOG(_FMT,...) if (g.TestEngineHookItems) ImGuiTestEngineHook_Log(&g, _FMT, __VA_ARGS__) // Custom log entry from user land into test log
+#define IMGUI_TEST_ENGINE_ID_INFO(_ID,_TYPE,_DATA) if (g.TestEngineHookIdInfo == id) ImGuiTestEngineHook_IdInfo(&g, _TYPE, _ID, (const void*)(_DATA));
+#define IMGUI_TEST_ENGINE_ID_INFO2(_ID,_TYPE,_DATA,_DATA2) if (g.TestEngineHookIdInfo == id) ImGuiTestEngineHook_IdInfo(&g, _TYPE, _ID, (const void*)(_DATA), (const void*)(_DATA2));
#else
-#define IMGUI_TEST_ENGINE_ITEM_ADD(_BB, _ID) do { } while (0)
-#define IMGUI_TEST_ENGINE_ITEM_INFO(_ID, _LABEL, _FLAGS) do { } while (0)
-#define IMGUI_TEST_ENGINE_LOG(_FMT, ...) do { } while (0)
+#define IMGUI_TEST_ENGINE_ITEM_ADD(_BB,_ID) do { } while (0)
+#define IMGUI_TEST_ENGINE_ITEM_INFO(_ID,_LABEL,_FLAGS) do { } while (0)
+#define IMGUI_TEST_ENGINE_LOG(_FMT,...) do { } while (0)
+#define IMGUI_TEST_ENGINE_ID_INFO(_ID,_TYPE,_DATA) do { } while (0)
+#define IMGUI_TEST_ENGINE_ID_INFO2(_ID,_TYPE,_DATA,_DATA2) do { } while (0)
#endif
+//-----------------------------------------------------------------------------
+
#if defined(__clang__)
#pragma clang diagnostic pop
#elif defined(__GNUC__)
@@ -2006,3 +2547,5 @@ extern void ImGuiTestEngineHook_Log(ImGuiContext* ctx, const cha
#ifdef _MSC_VER
#pragma warning (pop)
#endif
+
+#endif // #ifndef IMGUI_DISABLE
diff --git a/dep/imgui/include/imgui_stdlib.h b/dep/imgui/include/imgui_stdlib.h
index 5bccb0323..f860b0c78 100644
--- a/dep/imgui/include/imgui_stdlib.h
+++ b/dep/imgui/include/imgui_stdlib.h
@@ -1,5 +1,4 @@
-// imgui_stdlib.h
-// Wrappers for C++ standard library (STL) types (std::string, etc.)
+// dear imgui: wrappers for C++ standard library (STL) types (std::string, etc.)
// This is also an example of how you may wrap your own similar types.
// Compatibility:
diff --git a/dep/imgui/include/imstb_textedit.h b/dep/imgui/include/imstb_textedit.h
index 2077d02ae..764467097 100644
--- a/dep/imgui/include/imstb_textedit.h
+++ b/dep/imgui/include/imstb_textedit.h
@@ -148,6 +148,8 @@
// STB_TEXTEDIT_K_RIGHT keyboard input to move cursor right
// STB_TEXTEDIT_K_UP keyboard input to move cursor up
// STB_TEXTEDIT_K_DOWN keyboard input to move cursor down
+// STB_TEXTEDIT_K_PGUP keyboard input to move cursor up a page
+// STB_TEXTEDIT_K_PGDOWN keyboard input to move cursor down a page
// STB_TEXTEDIT_K_LINESTART keyboard input to move cursor to start of line // e.g. HOME
// STB_TEXTEDIT_K_LINEEND keyboard input to move cursor to end of line // e.g. END
// STB_TEXTEDIT_K_TEXTSTART keyboard input to move cursor to start of text // e.g. ctrl-HOME
@@ -170,14 +172,10 @@
// STB_TEXTEDIT_K_TEXTSTART2 secondary keyboard input to move cursor to start of text
// STB_TEXTEDIT_K_TEXTEND2 secondary keyboard input to move cursor to end of text
//
-// Todo:
-// STB_TEXTEDIT_K_PGUP keyboard input to move cursor up a page
-// STB_TEXTEDIT_K_PGDOWN keyboard input to move cursor down a page
-//
// Keyboard input must be encoded as a single integer value; e.g. a character code
// and some bitflags that represent shift states. to simplify the interface, SHIFT must
// be a bitflag, so we can test the shifted state of cursor movements to allow selection,
-// i.e. (STB_TEXTED_K_RIGHT|STB_TEXTEDIT_K_SHIFT) should be shifted right-arrow.
+// i.e. (STB_TEXTEDIT_K_RIGHT|STB_TEXTEDIT_K_SHIFT) should be shifted right-arrow.
//
// You can encode other things, such as CONTROL or ALT, in additional bits, and
// then test for their presence in e.g. STB_TEXTEDIT_K_WORDLEFT. For example,
@@ -337,6 +335,10 @@ typedef struct
// each textfield keeps its own insert mode state. to keep an app-wide
// insert mode, copy this value in/out of the app state
+ int row_count_per_page;
+ // page size in number of row.
+ // this value MUST be set to >0 for pageup or pagedown in multilines documents.
+
/////////////////////
//
// private data
@@ -855,12 +857,16 @@ retry:
break;
case STB_TEXTEDIT_K_DOWN:
- case STB_TEXTEDIT_K_DOWN | STB_TEXTEDIT_K_SHIFT: {
+ case STB_TEXTEDIT_K_DOWN | STB_TEXTEDIT_K_SHIFT:
+ case STB_TEXTEDIT_K_PGDOWN:
+ case STB_TEXTEDIT_K_PGDOWN | STB_TEXTEDIT_K_SHIFT: {
StbFindState find;
StbTexteditRow row;
- int i, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0;
+ int i, j, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0;
+ int is_page = (key & ~STB_TEXTEDIT_K_SHIFT) == STB_TEXTEDIT_K_PGDOWN;
+ int row_count = is_page ? state->row_count_per_page : 1;
- if (state->single_line) {
+ if (!is_page && state->single_line) {
// on windows, up&down in single-line behave like left&right
key = STB_TEXTEDIT_K_RIGHT | (key & STB_TEXTEDIT_K_SHIFT);
goto retry;
@@ -869,17 +875,25 @@ retry:
if (sel)
stb_textedit_prep_selection_at_cursor(state);
else if (STB_TEXT_HAS_SELECTION(state))
- stb_textedit_move_to_last(str,state);
+ stb_textedit_move_to_last(str, state);
// compute current position of cursor point
stb_textedit_clamp(str, state);
stb_textedit_find_charpos(&find, str, state->cursor, state->single_line);
- // now find character position down a row
- if (find.length) {
- float goal_x = state->has_preferred_x ? state->preferred_x : find.x;
- float x;
+ for (j = 0; j < row_count; ++j) {
+ float x, goal_x = state->has_preferred_x ? state->preferred_x : find.x;
int start = find.first_char + find.length;
+
+ if (find.length == 0)
+ break;
+
+ // [DEAR IMGUI]
+ // going down while being on the last line shouldn't bring us to that line end
+ if (STB_TEXTEDIT_GETCHAR(str, find.first_char + find.length - 1) != STB_TEXTEDIT_NEWLINE)
+ break;
+
+ // now find character position down a row
state->cursor = start;
STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor);
x = row.x0;
@@ -901,17 +915,25 @@ retry:
if (sel)
state->select_end = state->cursor;
+
+ // go to next line
+ find.first_char = find.first_char + find.length;
+ find.length = row.num_chars;
}
break;
}
case STB_TEXTEDIT_K_UP:
- case STB_TEXTEDIT_K_UP | STB_TEXTEDIT_K_SHIFT: {
+ case STB_TEXTEDIT_K_UP | STB_TEXTEDIT_K_SHIFT:
+ case STB_TEXTEDIT_K_PGUP:
+ case STB_TEXTEDIT_K_PGUP | STB_TEXTEDIT_K_SHIFT: {
StbFindState find;
StbTexteditRow row;
- int i, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0;
+ int i, j, prev_scan, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0;
+ int is_page = (key & ~STB_TEXTEDIT_K_SHIFT) == STB_TEXTEDIT_K_PGUP;
+ int row_count = is_page ? state->row_count_per_page : 1;
- if (state->single_line) {
+ if (!is_page && state->single_line) {
// on windows, up&down become left&right
key = STB_TEXTEDIT_K_LEFT | (key & STB_TEXTEDIT_K_SHIFT);
goto retry;
@@ -926,11 +948,14 @@ retry:
stb_textedit_clamp(str, state);
stb_textedit_find_charpos(&find, str, state->cursor, state->single_line);
- // can only go up if there's a previous row
- if (find.prev_first != find.first_char) {
+ for (j = 0; j < row_count; ++j) {
+ float x, goal_x = state->has_preferred_x ? state->preferred_x : find.x;
+
+ // can only go up if there's a previous row
+ if (find.prev_first == find.first_char)
+ break;
+
// now find character position up a row
- float goal_x = state->has_preferred_x ? state->preferred_x : find.x;
- float x;
state->cursor = find.prev_first;
STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor);
x = row.x0;
@@ -952,6 +977,14 @@ retry:
if (sel)
state->select_end = state->cursor;
+
+ // go to previous line
+ // (we need to scan previous line the hard way. maybe we could expose this as a new API function?)
+ prev_scan = find.prev_first > 0 ? find.prev_first - 1 : 0;
+ while (prev_scan > 0 && STB_TEXTEDIT_GETCHAR(str, prev_scan - 1) != STB_TEXTEDIT_NEWLINE)
+ --prev_scan;
+ find.first_char = find.prev_first;
+ find.prev_first = prev_scan;
}
break;
}
@@ -1075,10 +1108,6 @@ retry:
state->has_preferred_x = 0;
break;
}
-
-// @TODO:
-// STB_TEXTEDIT_K_PGUP - move cursor up a page
-// STB_TEXTEDIT_K_PGDOWN - move cursor down a page
}
}
@@ -1134,7 +1163,7 @@ static void stb_textedit_discard_redo(StbUndoState *state)
state->undo_rec[i].char_storage += n;
}
// now move all the redo records towards the end of the buffer; the first one is at 'redo_point'
- // {DEAR IMGUI]
+ // [DEAR IMGUI]
size_t move_size = (size_t)((STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point - 1) * sizeof(state->undo_rec[0]));
const char* buf_begin = (char*)state->undo_rec; (void)buf_begin;
const char* buf_end = (char*)state->undo_rec + sizeof(state->undo_rec); (void)buf_end;
@@ -1350,6 +1379,7 @@ static void stb_textedit_clear_state(STB_TexteditState *state, int is_single_lin
state->initialized = 1;
state->single_line = (unsigned char) is_single_line;
state->insert_mode = 0;
+ state->row_count_per_page = 0;
}
// API initialize
diff --git a/dep/imgui/src/imgui.cpp b/dep/imgui/src/imgui.cpp
index 731bb0bdd..380df5702 100644
--- a/dep/imgui/src/imgui.cpp
+++ b/dep/imgui/src/imgui.cpp
@@ -1,18 +1,26 @@
-// dear imgui, v1.74 WIP
+// dear imgui, v1.81 WIP
// (main code and documentation)
-// Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code.
-// Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.
-// Get latest version at https://github.com/ocornut/imgui
-// Releases change-log at https://github.com/ocornut/imgui/releases
-// Technical Support for Getting Started https://discourse.dearimgui.org/c/getting-started
-// Gallery (please post your screenshots/video there!): https://github.com/ocornut/imgui/issues/2847
+// Help:
+// - Read FAQ at http://dearimgui.org/faq
+// - Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.
+// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
+// Read imgui.cpp for details, links and comments.
+
+// Resources:
+// - FAQ http://dearimgui.org/faq
+// - Homepage & latest https://github.com/ocornut/imgui
+// - Releases & changelog https://github.com/ocornut/imgui/releases
+// - Gallery https://github.com/ocornut/imgui/issues/3488 (please post your screenshots/video there!)
+// - Glossary https://github.com/ocornut/imgui/wiki/Glossary
+// - Wiki https://github.com/ocornut/imgui/wiki
+// - Issues & support https://github.com/ocornut/imgui/issues
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
// See LICENSE.txt for copyright and licensing details (standard MIT License).
-// This library is free but I need your support to sustain development and maintenance.
-// Businesses: you can support continued maintenance and development via support contracts or sponsoring, see docs/README.
-// Individuals: you can support continued maintenance and development via donations or Patreon https://www.patreon.com/imgui.
+// This library is free but needs your support to sustain development and maintenance.
+// Businesses: you can support continued development via invoiced technical support, maintenance and sponsoring contracts. Please reach out to "contact AT dearimgui.org".
+// Individuals: you can support continued development via donations. See docs/README or web page.
// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
@@ -29,12 +37,12 @@ DOCUMENTATION
- MISSION STATEMENT
- END-USER GUIDE
- PROGRAMMER GUIDE
- - Read first.
- - How to update to a newer version of Dear ImGui.
- - Getting started with integrating Dear ImGui in your code/engine.
- - This is how a simple application may look like (2 variations).
- - This is how a simple rendering function may look like.
- - Using gamepad/keyboard navigation controls.
+ - READ FIRST
+ - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
+ - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
+ - HOW A SIMPLE APPLICATION MAY LOOK LIKE
+ - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
+ - USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
- API BREAKING CHANGES (read me when you update!)
- FREQUENTLY ASKED QUESTIONS (FAQ)
- Read all answers online: https://www.dearimgui.org/faq, or in docs/FAQ.md (with a Markdown viewer)
@@ -42,18 +50,24 @@ DOCUMENTATION
CODE
(search for "[SECTION]" in the code to find them)
+// [SECTION] INCLUDES
// [SECTION] FORWARD DECLARATIONS
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
-// [SECTION] MAIN USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
-// [SECTION] MISC HELPERS/UTILITIES (Maths, String, Format, Hash, File functions)
+// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
+// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
+// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
+// [SECTION] MISC HELPERS/UTILITIES (File functions)
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
// [SECTION] ImGuiStorage
// [SECTION] ImGuiTextFilter
// [SECTION] ImGuiTextBuffer
// [SECTION] ImGuiListClipper
+// [SECTION] STYLING
// [SECTION] RENDER HELPERS
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
+// [SECTION] ERROR CHECKING
+// [SECTION] LAYOUT
// [SECTION] SCROLLING
// [SECTION] TOOLTIPS
// [SECTION] POPUPS
@@ -61,10 +75,8 @@ CODE
// [SECTION] DRAG AND DROP
// [SECTION] LOGGING/CAPTURING
// [SECTION] SETTINGS
-// [SECTION] VIEWPORTS, PLATFORM WINDOWS
-// [SECTION] DOCKING
// [SECTION] PLATFORM DEPENDENT HELPERS
-// [SECTION] METRICS/DEBUG WINDOW
+// [SECTION] METRICS/DEBUGGER WINDOW
*/
@@ -80,14 +92,13 @@ CODE
- Easy to use to create code-driven and data-driven tools.
- Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
- Easy to hack and improve.
- - Minimize screen real-estate usage.
- Minimize setup and maintenance.
- Minimize state storage on user side.
- Portable, minimize dependencies, run on target (consoles, phones, etc.).
- - Efficient runtime and memory consumption (NB- we do allocate when "growing" content e.g. creating a window,.
- opening a tree node for the first time, etc. but a typical frame should not allocate anything).
+ - Efficient runtime and memory consumption.
+
+ Designed for developers and content-creators, not the typical end-user! Some of the current weaknesses includes:
- Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes:
- Doesn't look fancy, doesn't animate.
- Limited layout features, intricate layouts are typically crafted in code.
@@ -113,21 +124,21 @@ CODE
- 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
+ - General Gamepad controls: enable with ImGuiConfigFlags_NavEnableGamepad. See suggested mappings in imgui.h ImGuiNavInput_ + download PNG/PSD at http://dearimgui.org/controls_sheets
PROGRAMMER GUIDE
================
- READ FIRST:
-
+ READ FIRST
+ ----------
- Remember to read the FAQ (https://www.dearimgui.org/faq)
- Your code creates the UI, if your code doesn't run the UI is gone! The UI can be highly dynamic, there are no construction
or destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, less bugs.
- Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
- The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
- Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
- You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links docs/README.md.
+ You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in the FAQ.
- Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
For every application frame your UI code will be called only once. This is in contrast to e.g. Unity's own implementation of an IMGUI,
where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
@@ -141,31 +152,39 @@ CODE
However, imgui_internal.h can optionally export math operators for ImVec2/ImVec4, which we use in this codebase.
- C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (avoid using it in your code!).
- HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI:
+ HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
+ ----------------------------------------------
- Overwrite all the sources files except for imconfig.h (if you have made modification to your copy of imconfig.h)
- - Or maintain your own branch where you have imconfig.h modified.
+ - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over master.
+ - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
- Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
likely be a comment about it. Please report any issue to the GitHub page!
- - Try to keep your copy of dear imgui reasonably up to date.
+ - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
+ - Try to keep your copy of Dear ImGui reasonably up to date.
- GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE:
+ GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
+ ---------------------------------------------------------------
- Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
- - Add the Dear ImGui source files to your projects or using your preferred build system.
- It is recommended you build and statically link the .cpp files as part of your project and not as shared library (DLL).
+ - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
+ - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
+ It is recommended you build and statically link the .cpp files as part of your project and NOT as shared library (DLL).
- You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
- When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
- Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
phases of your own application. All rendering information are stored into command-lists that you will retrieve after calling ImGui::Render().
- - Refer to the bindings and demo applications in the examples/ folder for instruction on how to setup your code.
+ - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
- If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
- HOW A SIMPLE APPLICATION MAY LOOK LIKE:
- EXHIBIT 1: USING THE EXAMPLE BINDINGS (imgui_impl_XXX.cpp files from the examples/ folder).
+
+ HOW A SIMPLE APPLICATION MAY LOOK LIKE
+ --------------------------------------
+ EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
+ The sub-folders in examples/ contains examples applications following this structure.
// Application init: create a dear imgui context, setup some options, load fonts
ImGui::CreateContext();
@@ -174,7 +193,7 @@ CODE
// TODO: Fill optional fields of the io structure later.
// TODO: Load TTF/OTF fonts if you don't want to use the default font.
- // Initialize helper Platform and Renderer bindings (here we are using imgui_impl_win32 and imgui_impl_dx11)
+ // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
ImGui_ImplWin32_Init(hwnd);
ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
@@ -200,8 +219,7 @@ CODE
ImGui_ImplWin32_Shutdown();
ImGui::DestroyContext();
- HOW A SIMPLE APPLICATION MAY LOOK LIKE:
- EXHIBIT 2: IMPLEMENTING CUSTOM BINDING / CUSTOM ENGINE.
+ EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
// Application init: create a dear imgui context, setup some options, load fonts
ImGui::CreateContext();
@@ -226,7 +244,7 @@ CODE
while (true)
{
// Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
- // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform bindings)
+ // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
io.DeltaTime = 1.0f/60.0f; // set the time elapsed since the previous frame (in seconds)
io.DisplaySize.x = 1920.0f; // set the current display width
io.DisplaySize.y = 1280.0f; // set the current display height here
@@ -255,7 +273,14 @@ CODE
// Shutdown
ImGui::DestroyContext();
- HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE:
+ To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest your application,
+ you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
+ Please read the FAQ and example applications for details about this!
+
+
+ HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
+ ---------------------------------------------
+ The backends in impl_impl_XXX.cpp files contains many working implementations of a rendering function.
void void MyImGuiRenderFunction(ImDrawData* draw_data)
{
@@ -293,7 +318,7 @@ CODE
MyEngineScissor((int)(pcmd->ClipRect.x - pos.x), (int)(pcmd->ClipRect.y - pos.y), (int)(pcmd->ClipRect.z - pos.x), (int)(pcmd->ClipRect.w - pos.y));
// Render 'pcmd->ElemCount/3' indexed triangles.
- // By default the indices ImDrawIdx are 16-bits, you can change them to 32-bits in imconfig.h if your engine doesn't support 16-bits indices.
+ // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer, vtx_buffer);
}
idx_buffer += pcmd->ElemCount;
@@ -301,29 +326,13 @@ CODE
}
}
- - The examples/ folders contains many actual implementation of the pseudo-codes above.
- - When calling NewFrame(), the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags are updated.
- They tell you if Dear ImGui intends to use your inputs. When a flag is set you want to hide the corresponding inputs from the
- rest of your application. In every cases you need to pass on the inputs to Dear ImGui.
- - Refer to the FAQ for more information. Amusingly, it is called a FAQ because people frequently run into the same issues!
USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
-
+ ------------------------------------------
- The gamepad/keyboard navigation is fairly functional and keeps being improved.
- - Gamepad support is particularly useful to use dear imgui on a console system (e.g. PS4, Switch, XB1) without a mouse!
+ - Gamepad support is particularly useful to use Dear ImGui on a console system (e.g. PS4, Switch, XB1) without a mouse!
- You can ask questions and report issues at https://github.com/ocornut/imgui/issues/787
- The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable.
- - Gamepad:
- - 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: http://goo.gl/9LgVZW.
- - If you need to share inputs between your game and the imgui parts, the easiest approach is to go all-or-nothing, with a buttons combo
- to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
- Keyboard:
- Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable.
NewFrame() will automatically fill io.NavInputs[] based on your io.KeysDown[] + io.KeyMap[] arrays.
@@ -333,13 +342,24 @@ CODE
- io.NavVisible: true when the navigation cursor is visible (and usually goes false when mouse is used).
- or query focus information with e.g. IsWindowFocused(ImGuiFocusedFlags_AnyWindow), IsItemFocused() etc. functions.
Please reach out if you think the game vs navigation input sharing could be improved.
+ - Gamepad:
+ - Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable.
+ - Backend: Set io.BackendFlags |= ImGuiBackendFlags_HasGamepad + fill the io.NavInputs[] fields before calling NewFrame().
+ 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: http://dearimgui.org/controls_sheets
+ - 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.
- 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.
+ When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that.
(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.)
@@ -353,16 +373,72 @@ CODE
When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
You can read releases logs https://github.com/ocornut/imgui/releases for more details.
- (Docking/Viewport Branch)
- - 2019/XX/XX (1.XX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
- - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore.
- you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos)
- - likewise io.MousePos and GetMousePos() will use OS coordinates.
- If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos.
- - 2019/XX/XX (1.XX) - Moved IME support functions from io.ImeSetInputScreenPosFn, io.ImeWindowHandle to the PlatformIO api.
-
-
- - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017): Begin() (5 arguments signature), IsRootWindowOrAnyChildHovered(), AlignFirstTextHeightToWidgets(), SetNextWindowPosCenter(), ImFont::Glyph. Grep this log for details and new names, or see how they were implemented until 1.73.
+ - 2021/01/26 (1.81) - imgui_freetype: removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags.
+ - imgui_freetype: renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
+ - imgui_freetype: renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
+ - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
+ - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
+ - ImGuiCol_ModalWindowDarkening -> use ImGuiCol_ModalWindowDimBg
+ - ImGuiInputTextCallback -> use ImGuiTextEditCallback
+ - ImGuiInputTextCallbackData -> use ImGuiTextEditCallbackData
+ - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
+ - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
+ - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
+ - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
+ - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
+ - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
+ - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your backend
+ - ImGui::IsAnyWindowFocused() -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
+ - ImGui::IsAnyWindowHovered() -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
+ - ImGuiStyleVar_Count_ -> use ImGuiStyleVar_COUNT
+ - ImGuiMouseCursor_Count_ -> use ImGuiMouseCursor_COUNT
+ - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
+ - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
+ - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
+ - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed).
+ - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
+ - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
+ - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory.
+ - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result.
+ - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now!
+ - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar().
+ replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
+ worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
+ - if you omitted the 'power' parameter (likely!), you are not affected.
+ - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct.
+ - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f.
+ see https://github.com/ocornut/imgui/issues/3361 for all details.
+ kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version were removed directly as they were most unlikely ever used.
+ for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
+ - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime.
+ - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.
+ - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
+ - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
+ - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
+ - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
+ - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
+ - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
+ - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
+ - ShowTestWindow() -> use ShowDemoWindow()
+ - IsRootWindowFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
+ - IsRootWindowOrAnyChildFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
+ - SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
+ - GetItemsLineHeightWithSpacing() -> use GetFrameHeightWithSpacing()
+ - ImGuiCol_ChildWindowBg -> use ImGuiCol_ChildBg
+ - ImGuiStyleVar_ChildWindowRounding -> use ImGuiStyleVar_ChildRounding
+ - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
+ - IMGUI_DISABLE_TEST_WINDOWS -> use IMGUI_DISABLE_DEMO_WINDOWS
+ - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was the vaguely documented and rarely if ever used). Instead we added an explicit PrimUnreserve() API.
+ - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
+ - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
+ - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
+ - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
+ - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
+ - Begin() [old 5 args version] -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
+ - IsRootWindowOrAnyChildHovered() -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
+ - AlignFirstTextHeightToWidgets() -> use AlignTextToFramePadding()
+ - SetNextWindowPosCenter() -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
+ - ImFont::Glyph -> use ImFontGlyph
- 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
@@ -380,7 +456,7 @@ CODE
- 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
- 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
- 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
- - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with a dummy small value!
+ - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrary small value!
- 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
- 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
- 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
@@ -401,10 +477,10 @@ CODE
- 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
- 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
- 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
- - 2018/06/08 (1.62) - examples: the imgui_impl_xxx files have been split to separate platform (Win32, Glfw, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan, etc.).
- old bindings will still work as is, however prefer using the separated bindings as they will be updated to support multi-viewports.
- when adopting new bindings follow the main.cpp code of your preferred examples/ folder to know which functions to call.
- in particular, note that old bindings called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
+ - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan, etc.).
+ old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
+ when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
+ in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
- 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
- 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
- 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
@@ -414,7 +490,7 @@ CODE
- 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
consistent with other functions. Kept redirection functions (will obsolete).
- 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
- - 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/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch).
- 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.
@@ -458,7 +534,7 @@ CODE
- 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
- 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
- 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
- - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your binding if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
+ - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
- 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
- renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
- renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
@@ -471,7 +547,7 @@ CODE
- 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
- 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
- changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
- - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0,0))'
+ - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))'
- 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
- 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
- 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
@@ -480,14 +556,9 @@ CODE
- 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
- 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully breakage should be minimal.
- 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
- If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you.
- If your TitleBg/TitleBgActive alpha was <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
- This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color.
- ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col)
- {
- float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a;
- return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a);
- }
+ If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
+ This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color:
+ ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
- 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
- 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
@@ -510,7 +581,7 @@ CODE
you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
- 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
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.
+ - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
- the signature of the io.RenderDrawListsFn handler has changed!
old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
@@ -546,14 +617,13 @@ CODE
- 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
- 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
- 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
- (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
- font init: { const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); <..Upload texture to GPU..>; }
- became: { unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); <..Upload texture to GPU>; io.Fonts->TexId = YourTextureIdentifier; }
- you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs.
- it is now recommended that you sample the font texture with bilinear interpolation.
- (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID.
- (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
- (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
+ - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
+ - old: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
+ - new: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->TexId = YourTexIdentifier;
+ you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
+ - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID.
+ - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
+ - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
- 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
- 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
- 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
@@ -570,7 +640,10 @@ CODE
FREQUENTLY ASKED QUESTIONS (FAQ)
================================
- Read all answers online: https://www.dearimgui.org/faq, or in docs/FAQ.md (with a Markdown viewer)
+ Read all answers online:
+ https://www.dearimgui.org/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
+ Read all answers locally (with a text editor or ideally a Markdown viewer):
+ docs/FAQ.md
Some answers are copied down here to facilitate searching in code.
Q&A: Basics
@@ -582,15 +655,57 @@ CODE
- See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
- The demo covers most features of Dear ImGui, so you can read the code and see its output.
- See documentation and comments at the top of imgui.cpp + effectively imgui.h.
- - Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the examples/
- folder to explain how to integrate Dear ImGui with your own engine/application.
+ - Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the
+ examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
+ - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
+ - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
- Your programming IDE is your friend, find the type or function declaration to find comments
associated to it.
+ Q: What is this library called?
Q: Which version should I get?
- Q: Why the names "Dear ImGui" vs "ImGui"?
+ >> This library is called "Dear ImGui", please don't call it "ImGui" :)
+ >> See https://www.dearimgui.org/faq for details.
+
+ Q&A: Integration
+ ================
+
+ Q: How to get started?
+ A: Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
+
+ Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or to my application?
+ A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
+ >> See https://www.dearimgui.org/faq for fully detailed answer. You really want to read this.
+
+ Q. How can I enable keyboard controls?
+ Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display)
+ Q: I integrated Dear ImGui in my engine and little squares are showing instead of text..
+ Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
+ Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries..
>> See https://www.dearimgui.org/faq
+ Q&A: Usage
+ ----------
+
+ Q: Why is my widget not reacting when I click on it?
+ Q: How can I have widgets with an empty label?
+ Q: How can I have multiple widgets with the same label?
+ Q: How can I display an image? What is ImTextureID, how does it works?
+ Q: How can I use my own math types instead of ImVec2/ImVec4?
+ Q: How can I interact with standard C++ types (such as std::string and std::vector)?
+ Q: How can I display custom shapes? (using low-level ImDrawList API)
+ >> See https://www.dearimgui.org/faq
+
+ Q&A: Fonts, Text
+ ================
+
+ Q: How should I handle DPI in my application?
+ Q: How can I load a different font than the default?
+ Q: How can I easily use icons in my application?
+ Q: How can I load multiple fonts?
+ Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
+ >> See https://www.dearimgui.org/faq and https://github.com/ocornut/imgui/edit/master/docs/FONTS.md
+
Q&A: Concerns
=============
@@ -600,190 +715,40 @@ CODE
Q: Why using C++ (as opposed to C)?
>> See https://www.dearimgui.org/faq
- Q&A: Integration
- ================
-
- Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or to my application?
- A: You can read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags from the ImGuiIO structure (e.g. if (ImGui::GetIO().WantCaptureMouse) { ... } )
- - When 'io.WantCaptureMouse' is set, imgui wants to use your mouse state, and you may want to discard/hide the inputs from the rest of your application.
- - When 'io.WantCaptureKeyboard' is set, imgui wants to use your keyboard state, and you may want to discard/hide the inputs from the rest of your application.
- - When 'io.WantTextInput' is set to may want to notify your OS to popup an on-screen keyboard, if available (e.g. on a mobile phone, or console OS).
- Note: you should always pass your mouse/keyboard inputs to imgui, even when the io.WantCaptureXXX flag are set false.
- This is because imgui needs to detect that you clicked in the void to unfocus its own windows.
- Note: The 'io.WantCaptureMouse' is more accurate that any attempt to "check if the mouse is hovering a window" (don't do that!).
- It handle mouse dragging correctly (both dragging that started over your application or over an imgui window) and handle e.g. modal windows blocking inputs.
- Those flags are updated by ImGui::NewFrame(). Preferably read the flags after calling NewFrame() if you can afford it, but reading them before is also
- perfectly fine, as the bool toggle fairly rarely. If you have on a touch device, you might find use for an early call to UpdateHoveredWindowAndCaptureFlags().
- Note: Text input widget releases focus on "Return KeyDown", so the subsequent "Return KeyUp" event that your application receive will typically
- have 'io.WantCaptureKeyboard=false'. Depending on your application logic it may or not be inconvenient. You might want to track which key-downs
- were targeted for Dear ImGui, e.g. with an array of bool, and filter out the corresponding key-ups.)
-
- Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display)
- Q: I integrated Dear ImGui in my engine and the text or lines are blurry..
- Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
- >> See https://www.dearimgui.org/faq
-
- Q&A: Usage
- ----------
-
- Q: Why are multiple widgets reacting when I interact with a single one?
- Q: How can I have multiple widgets with the same label or with an empty label?
- A: A primer on labels and the ID Stack...
-
- Dear ImGui internally need to uniquely identify UI elements.
- Elements that are typically not clickable (such as calls to the Text functions) don't need an ID.
- Interactive widgets (such as calls to Button buttons) need a unique ID.
- Unique ID are used internally to track active widgets and occasionally associate state to widgets.
- Unique ID are implicitly built from the hash of multiple elements that identify the "path" to the UI element.
-
- - Unique ID are often derived from a string label:
-
- 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. which all pushes to the ID stack. Having
- two buttons labeled "OK" in different windows or different tree locations is fine.
- We used "..." above to signify whatever was already pushed to the ID stack previously:
-
- Begin("MyWindow");
- Button("OK"); // Label = "OK", ID = hash of ("MyWindow", "OK")
- End();
- Begin("MyOtherWindow");
- Button("OK"); // Label = "OK", ID = hash of ("MyOtherWindow", "OK")
- End();
-
- - If you have a same ID twice in the same location, you'll have a conflict:
-
- Button("OK");
- 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!
-
- - 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:
-
- Begin("MyWindow");
- Button("Play"); // Label = "Play", ID = hash of ("MyWindow", "Play")
- Button("Play##foo1"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo1") // Different from above
- Button("Play##foo2"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo2") // Different from above
- End();
-
- - If you want to completely hide the label, but still need an ID:
-
- Checkbox("##On", &b); // Label = "", ID = hash of (..., "##On") // No visible label, just a checkbox!
-
- - Occasionally/rarely you might want change a label while preserving a constant ID. This allows
- you to animate labels. For example you may want to include varying information in a window title bar,
- but windows are uniquely identified by their ID. Use "###" to pass a label that isn't part of ID:
-
- Button("Hello###ID"); // Label = "Hello", ID = hash of (..., "###ID")
- Button("World###ID"); // Label = "World", ID = hash of (..., "###ID") // Same as above, even though the label looks different
-
- sprintf(buf, "My game (%f FPS)###MyGame", fps);
- Begin(buf); // Variable title, ID = hash of "MyGame"
-
- - Solving ID conflict in a more general manner:
- Use PushID() / PopID() to create scopes and manipulate the ID stack, as to avoid ID conflicts
- within the same window. This is the most convenient way of distinguishing ID when iterating and
- creating many UI elements programmatically.
- You can push a pointer, a string or an integer value into the ID stack.
- Remember that ID are formed from the concatenation of _everything_ pushed into the ID stack.
- At each level of the stack we store the seed used for items at this level of the ID stack.
-
- Begin("Window");
- for (int i = 0; i < 100; i++)
- {
- PushID(i); // Push i to the id tack
- Button("Click"); // Label = "Click", ID = hash of ("Window", i, "Click")
- PopID();
- }
- for (int i = 0; i < 100; i++)
- {
- MyObject* obj = Objects[i];
- PushID(obj);
- Button("Click"); // Label = "Click", ID = hash of ("Window", obj pointer, "Click")
- PopID();
- }
- for (int i = 0; i < 100; i++)
- {
- MyObject* obj = Objects[i];
- PushID(obj->Name);
- Button("Click"); // Label = "Click", ID = hash of ("Window", obj->Name, "Click")
- PopID();
- }
- End();
-
- - You can stack multiple prefixes into the ID stack:
-
- Button("Click"); // Label = "Click", ID = hash of (..., "Click")
- PushID("node");
- Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click")
- PushID(my_ptr);
- Button("Click"); // Label = "Click", ID = hash of (..., "node", my_ptr, "Click")
- PopID();
- PopID();
-
- - Tree nodes implicitly creates a scope for you by calling PushID().
-
- Button("Click"); // Label = "Click", ID = hash of (..., "Click")
- if (TreeNode("node")) // <-- this function call will do a PushID() for you (unless instructed not to, with a special flag)
- {
- Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click")
- 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 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 display an image? What is ImTextureID, how does it works?
- >> See https://www.dearimgui.org/faq and https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples
-
- Q: How can I use my own math types instead of ImVec2/ImVec4?
- Q: How can I interact with standard C++ types (such as std::string and std::vector)?
- Q: How can I display custom shapes? (using low-level ImDrawList API)
- >> See https://www.dearimgui.org/faq
-
- Q&A: Fonts, Text
- ================
-
- Q: How can I load a different font than the default?
- Q: How can I easily use icons in my application?
- Q: How can I load multiple fonts?
- Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
- >> See https://www.dearimgui.org/faq and misc/fonts/README.txt
-
Q&A: Community
==============
Q: How can I help?
- A: - If you are experienced with Dear ImGui and C++, look at the github issues, look at the Wiki, read docs/TODO.txt
+ A: - Businesses: please reach out to "contact AT dearimgui.org" if you work in a place using Dear ImGui!
+ We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
+ This is among the most useful thing you can do for Dear ImGui. With increased funding we can hire more people working on this project.
+ - Individuals: you can support continued development via PayPal donations. See README.
+ - If you are experienced with Dear ImGui and C++, look at the github issues, look at the Wiki, read docs/TODO.txt
and see how you want to help and can help!
- - Businesses: convince your company to fund development via support contracts/sponsoring! This is among the most useful thing you can do for dear imgui.
- - Individuals: you can also become a Patron (http://www.patreon.com/imgui) or donate on PayPal! See README.
- - Disclose your usage of dear imgui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
- You may post screenshot or links in the gallery threads (github.com/ocornut/imgui/issues/2847). Visuals are ideal as they inspire other programmers.
+ - 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/3488). 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).
*/
+//-------------------------------------------------------------------------
+// [SECTION] INCLUDES
+//-------------------------------------------------------------------------
+
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "imgui.h"
+#ifndef IMGUI_DISABLE
+
#ifndef IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_MATH_OPERATORS
#endif
#include "imgui_internal.h"
+// System includes
#include // toupper
#include // vsnprintf, sscanf, printf
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
@@ -792,34 +757,59 @@ CODE
#include // intptr_t
#endif
-// Debug options
-#define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
-#define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window
-#define IMGUI_DEBUG_INI_SETTINGS 0 // Save additional comments in .ini file (particularly helps for Docking, but makes saving slower)
+// [Windows] OS specific includes (optional)
+#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
+#define IMGUI_DISABLE_WIN32_FUNCTIONS
+#endif
+#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN
+#endif
+#ifndef NOMINMAX
+#define NOMINMAX
+#endif
+#ifndef __MINGW32__
+#include // _wfopen, OpenClipboard
+#else
+#include
+#endif
+#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have all Win32 functions
+#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
+#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
+#endif
+#endif
+
+// [Apple] OS specific includes
+#if defined(__APPLE__)
+#include
+#endif
// Visual Studio warnings
#ifdef _MSC_VER
-#pragma warning (disable: 4127) // condition expression is constant
-#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
+#pragma warning (disable: 4127) // condition expression is constant
+#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
+#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later
+#pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types
+#endif
#endif
// Clang/GCC warnings with -Weverything
#if defined(__clang__)
-#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning : unknown warning group '-Wformat-pedantic *' // not all warnings are known by all clang versions.. so ignoring warnings triggers new warnings on some configuration. great!
-#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse.
-#pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
-#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning : format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
-#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
-#pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference is.
-#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness //
-#pragma clang diagnostic ignored "-Wformat-pedantic" // warning : format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
-#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int'
-#if __has_warning("-Wzero-as-null-pointer-constant")
-#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning : zero as null pointer constant // some standard header variations use #define NULL 0
-#endif
-#if __has_warning("-Wdouble-promotion")
-#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
+#if __has_warning("-Wunknown-warning-option")
+#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
#endif
+#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
+#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
+#pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
+#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning: format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
+#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning: declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
+#pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is.
+#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
+#pragma clang diagnostic ignored "-Wformat-pedantic" // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
+#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type 'int'
+#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
+#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
+#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
#elif defined(__GNUC__)
// We disable -Wpragmas because GCC doesn't provide an has_warning equivalent and some forks/patches may not following the warning/version association.
#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
@@ -833,82 +823,79 @@ CODE
#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
#endif
+// Debug options
+#define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
+#define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window
+#define IMGUI_DEBUG_INI_SETTINGS 0 // Save additional comments in .ini file (particularly helps for Docking, but makes saving slower)
+
// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in
static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear
-// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by back-end)
+// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
static const float WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS = 4.0f; // Extend outside and inside windows. Affect FindHoveredWindow().
static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time.
-static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 2.00f; // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certaint time, unless mouse moved.
-
-// Docking
-static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA = 0.50f; // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
+static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 2.00f; // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
//-------------------------------------------------------------------------
// [SECTION] FORWARD DECLARATIONS
//-------------------------------------------------------------------------
static void SetCurrentWindow(ImGuiWindow* window);
-static void SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size);
static void FindHoveredWindow();
-static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags);
-static void CheckStacksSize(ImGuiWindow* window, bool write);
-static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges);
+static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags);
+static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
static void AddDrawListToDrawData(ImVector* out_list, ImDrawList* draw_list);
static void AddWindowToSortBuffer(ImVector* out_sorted_windows, ImGuiWindow* window);
+static ImRect GetViewportRect();
+
// Settings
-static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
-static void SettingsHandlerWindow_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
-static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
+static void WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
+static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
+static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
+static void WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
+static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
// Platform Dependents default implementation for IO functions
static const char* GetClipboardTextFn_DefaultImpl(void* user_data);
static void SetClipboardTextFn_DefaultImpl(void* user_data, const char* text);
+static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y);
namespace ImGui
{
-static bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags);
-
// Navigation
static void NavUpdate();
static void NavUpdateWindowing();
static void NavUpdateWindowingOverlay();
static void NavUpdateMoveResult();
+static void NavUpdateInitResult();
static float NavUpdatePageUpPageDown();
static inline void NavUpdateAnyRequestFlag();
+static void NavEndFrame();
static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand);
+static void NavApplyItemToResult(ImGuiNavMoveResult* result, ImGuiWindow* window, ImGuiID id, const ImRect& nav_bb_rel);
static void NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, ImGuiID id);
static ImVec2 NavCalcPreferredRefPos();
static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window);
static int FindWindowFocusIndex(ImGuiWindow* window);
+// Error Checking
+static void ErrorCheckNewFrameSanityChecks();
+static void ErrorCheckEndFrameSanityChecks();
+
// Misc
+static void UpdateSettings();
static void UpdateMouseInputs();
static void UpdateMouseWheel();
-static bool UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]);
+static void UpdateTabFocus();
static void UpdateDebugToolItemPicker();
+static bool UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
static void RenderWindowOuterBorders(ImGuiWindow* window);
-static void RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
+static void RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
-static void EndFrameDrawDimmedBackgrounds();
-
-// Viewports
-const ImGuiID IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter.
-static ImGuiViewportP* AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
-static void UpdateViewportsNewFrame();
-static void UpdateViewportsEndFrame();
-static void UpdateSelectWindowViewport(ImGuiWindow* window);
-static bool UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
-static bool UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
-static void SetCurrentViewport(ImGuiWindow* window, ImGuiViewportP* viewport);
-static bool GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
-static int FindPlatformMonitorForPos(const ImVec2& pos);
-static int FindPlatformMonitorForRect(const ImRect& r);
-static void UpdateViewportPlatformMonitor(ImGuiViewportP* viewport);
}
@@ -950,14 +937,14 @@ static void (*GImAllocatorFreeFunc)(void* ptr, void* user_data) = FreeWrapper;
static void* GImAllocatorUserData = NULL;
//-----------------------------------------------------------------------------
-// [SECTION] MAIN USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
+// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
//-----------------------------------------------------------------------------
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
+ WindowRounding = 0.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
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
@@ -971,6 +958,7 @@ ImGuiStyle::ImGuiStyle()
FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
+ CellPadding = ImVec2(4,2); // Padding within a table cell
TouchExtraPadding = ImVec2(0,0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
@@ -978,17 +966,21 @@ ImGuiStyle::ImGuiStyle()
ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar
GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
+ LogSliderDeadzone = 4.0f; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
TabBorderSize = 0.0f; // Thickness of border around tabs.
+ TabMinWidthForCloseButton = 0.0f; // Minimum width for close button to appears on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
- SelectableTextAlign = ImVec2(0.0f,0.0f);// Alignment of selectable text when button is larger than text.
+ SelectableTextAlign = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
DisplayWindowPadding = ImVec2(19,19); // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
DisplaySafeAreaPadding = ImVec2(3,3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
- AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU.
- AntiAliasedFill = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.)
+ AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
+ AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering.
+ AntiAliasedFill = true; // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
CurveTessellationTol = 1.25f; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
+ CircleSegmentMaxError = 1.60f; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
// Default theme
ImGui::StyleColorsDark(this);
@@ -1007,6 +999,7 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor)
FrameRounding = ImFloor(FrameRounding * scale_factor);
ItemSpacing = ImFloor(ItemSpacing * scale_factor);
ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor);
+ CellPadding = ImFloor(CellPadding * scale_factor);
TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor);
IndentSpacing = ImFloor(IndentSpacing * scale_factor);
ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor);
@@ -1014,7 +1007,9 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor)
ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor);
GrabMinSize = ImFloor(GrabMinSize * scale_factor);
GrabRounding = ImFloor(GrabRounding * scale_factor);
+ LogSliderDeadzone = ImFloor(LogSliderDeadzone * scale_factor);
TabRounding = ImFloor(TabRounding * scale_factor);
+ TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImFloor(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);
DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);
MouseCursorScale = ImFloor(MouseCursorScale * scale_factor);
@@ -1024,12 +1019,13 @@ ImGuiIO::ImGuiIO()
{
// Most fields are initialized with zero
memset(this, 0, sizeof(*this));
+ IM_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT); // Our pre-C++11 IM_STATIC_ASSERT() macros triggers warning on modern compilers so we don't use it here.
// Settings
ConfigFlags = ImGuiConfigFlags_None;
BackendFlags = ImGuiBackendFlags_None;
DisplaySize = ImVec2(-1.0f, -1.0f);
- DeltaTime = 1.0f/60.0f;
+ DeltaTime = 1.0f / 60.0f;
IniSavingRate = 5.0f;
IniFilename = "imgui.ini";
LogFilename = "imgui_log.txt";
@@ -1047,18 +1043,6 @@ ImGuiIO::ImGuiIO()
FontAllowUserScaling = false;
DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
- // Docking options (when ImGuiConfigFlags_DockingEnable is set)
- ConfigDockingNoSplit = false;
- ConfigDockingWithShift = false;
- ConfigDockingAlwaysTabBar = false;
- ConfigDockingTransparentPayload = false;
-
- // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
- ConfigViewportsNoAutoMerge = false;
- ConfigViewportsNoTaskBarIcon = false;
- ConfigViewportsNoDecoration = true;
- ConfigViewportsNoDefaultParent = false;
-
// Miscellaneous options
MouseDrawCursor = false;
#ifdef __APPLE__
@@ -1069,7 +1053,7 @@ ImGuiIO::ImGuiIO()
ConfigInputTextCursorBlink = true;
ConfigWindowsResizeFromEdges = true;
ConfigWindowsMoveFromTitleBarOnly = false;
- ConfigWindowsMemoryCompactTimer = 60.0f;
+ ConfigMemoryCompactTimer = 60.0f;
// Platform Functions
BackendPlatformName = BackendRendererName = NULL;
@@ -1077,10 +1061,8 @@ ImGuiIO::ImGuiIO()
GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
ClipboardUserData = NULL;
-
-#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
- RenderDrawListsFn = NULL;
-#endif
+ ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl;
+ ImeWindowHandle = NULL;
// Input (NB: we already have memset zero the entire structure!)
MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
@@ -1096,8 +1078,37 @@ ImGuiIO::ImGuiIO()
// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
void ImGuiIO::AddInputCharacter(unsigned int c)
{
- if (c > 0 && c < 0x10000)
- InputQueueCharacters.push_back((ImWchar)c);
+ if (c != 0)
+ InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
+}
+
+// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
+// we should save the high surrogate.
+void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
+{
+ if (c == 0 && InputQueueSurrogate == 0)
+ return;
+
+ if ((c & 0xFC00) == 0xD800) // High surrogate, must save
+ {
+ if (InputQueueSurrogate != 0)
+ InputQueueCharacters.push_back(IM_UNICODE_CODEPOINT_INVALID);
+ InputQueueSurrogate = c;
+ return;
+ }
+
+ ImWchar cp = c;
+ if (InputQueueSurrogate != 0)
+ {
+ if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
+ InputQueueCharacters.push_back(IM_UNICODE_CODEPOINT_INVALID);
+ else if (IM_UNICODE_CODEPOINT_MAX == (0xFFFF)) // Codepoint will not fit in ImWchar (extra parenthesis around 0xFFFF somehow fixes -Wunreachable-code with Clang)
+ cp = IM_UNICODE_CODEPOINT_INVALID;
+ else
+ cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
+ InputQueueSurrogate = 0;
+ }
+ InputQueueCharacters.push_back(cp);
}
void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
@@ -1106,7 +1117,7 @@ void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
{
unsigned int c = 0;
utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
- if (c > 0 && c < 0x10000)
+ if (c != 0)
InputQueueCharacters.push_back((ImWchar)c);
}
}
@@ -1117,9 +1128,77 @@ void ImGuiIO::ClearInputCharacters()
}
//-----------------------------------------------------------------------------
-// [SECTION] MISC HELPERS/UTILITIES (Maths, String, Format, Hash, File functions)
+// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
//-----------------------------------------------------------------------------
+ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
+{
+ IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
+ ImVec2 p_last = p1;
+ ImVec2 p_closest;
+ float p_closest_dist2 = FLT_MAX;
+ float t_step = 1.0f / (float)num_segments;
+ for (int i_step = 1; i_step <= num_segments; i_step++)
+ {
+ ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
+ ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
+ float dist2 = ImLengthSqr(p - p_line);
+ if (dist2 < p_closest_dist2)
+ {
+ p_closest = p_line;
+ p_closest_dist2 = dist2;
+ }
+ p_last = p_current;
+ }
+ return p_closest;
+}
+
+// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
+static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
+{
+ float dx = x4 - x1;
+ float dy = y4 - y1;
+ float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
+ float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
+ d2 = (d2 >= 0) ? d2 : -d2;
+ d3 = (d3 >= 0) ? d3 : -d3;
+ if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
+ {
+ ImVec2 p_current(x4, y4);
+ ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
+ float dist2 = ImLengthSqr(p - p_line);
+ if (dist2 < p_closest_dist2)
+ {
+ p_closest = p_line;
+ p_closest_dist2 = dist2;
+ }
+ p_last = p_current;
+ }
+ else if (level < 10)
+ {
+ float x12 = (x1 + x2)*0.5f, y12 = (y1 + y2)*0.5f;
+ float x23 = (x2 + x3)*0.5f, y23 = (y2 + y3)*0.5f;
+ float x34 = (x3 + x4)*0.5f, y34 = (y3 + y4)*0.5f;
+ float x123 = (x12 + x23)*0.5f, y123 = (y12 + y23)*0.5f;
+ float x234 = (x23 + x34)*0.5f, y234 = (y23 + y34)*0.5f;
+ float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
+ ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
+ ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
+ }
+}
+
+// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
+// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
+ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
+{
+ IM_ASSERT(tess_tol > 0.0f);
+ ImVec2 p_last = p1;
+ ImVec2 p_closest;
+ float p_closest_dist2 = FLT_MAX;
+ ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
+ return p_closest;
+}
+
ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
{
ImVec2 ap = p - a;
@@ -1168,6 +1247,10 @@ ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c,
return proj_ca;
}
+//-----------------------------------------------------------------------------
+// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
+//-----------------------------------------------------------------------------
+
// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
int ImStricmp(const char* str1, const char* str2)
{
@@ -1221,7 +1304,7 @@ const char* ImStrchrRange(const char* str, const char* str_end, char c)
int ImStrlenW(const ImWchar* str)
{
- //return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bits
+ //return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bit
int n = 0;
while (*str++) n++;
return n;
@@ -1289,12 +1372,15 @@ const char* ImStrSkipBlank(const char* str)
// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
// B) When buf==NULL vsnprintf() will return the output size.
-#ifndef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS
+#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
-//#define IMGUI_USE_STB_SPRINTF
+// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
+// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
+// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
+// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
#ifdef IMGUI_USE_STB_SPRINTF
#define STB_SPRINTF_IMPLEMENTATION
-#include "imstb_sprintf.h"
+#include "stb_sprintf.h"
#endif
#if defined(_MSC_VER) && !defined(vsnprintf)
@@ -1333,7 +1419,7 @@ int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
buf[w] = 0;
return w;
}
-#endif // #ifdef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS
+#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
// CRC32 needs a 1KB lookup table (not cache friendly)
// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
@@ -1361,7 +1447,7 @@ static const ImU32 GCrc32LookupTable[256] =
// Known size hash
// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
-ImU32 ImHashData(const void* data_p, size_t data_size, ImU32 seed)
+ImGuiID ImHashData(const void* data_p, size_t data_size, ImU32 seed)
{
ImU32 crc = ~seed;
const unsigned char* data = (const unsigned char*)data_p;
@@ -1377,7 +1463,7 @@ ImU32 ImHashData(const void* data_p, size_t data_size, ImU32 seed)
// - If we reach ### in the string we discard the hash so far and reset to the seed.
// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
-ImU32 ImHashStr(const char* data_p, size_t data_size, ImU32 seed)
+ImGuiID ImHashStr(const char* data_p, size_t data_size, ImU32 seed)
{
seed = ~seed;
ImU32 crc = seed;
@@ -1405,58 +1491,73 @@ ImU32 ImHashStr(const char* data_p, size_t data_size, ImU32 seed)
return ~crc;
}
-FILE* ImFileOpen(const char* filename, const char* mode)
+//-----------------------------------------------------------------------------
+// [SECTION] MISC HELPERS/UTILITIES (File functions)
+//-----------------------------------------------------------------------------
+
+// Default file functions
+#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
+
+ImFileHandle ImFileOpen(const char* filename, const char* mode)
{
-#if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__GNUC__)
- // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames. Converting both strings from UTF-8 to wchar format (using a single allocation, because we can)
- const int filename_wsize = ImTextCountCharsFromUtf8(filename, NULL) + 1;
- const int mode_wsize = ImTextCountCharsFromUtf8(mode, NULL) + 1;
+#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
+ // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
+ // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
+ const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
+ const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
ImVector buf;
buf.resize(filename_wsize + mode_wsize);
- ImTextStrFromUtf8(&buf[0], filename_wsize, filename, NULL);
- ImTextStrFromUtf8(&buf[filename_wsize], mode_wsize, mode, NULL);
- return _wfopen((wchar_t*)&buf[0], (wchar_t*)&buf[filename_wsize]);
+ ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, (wchar_t*)&buf[0], filename_wsize);
+ ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, (wchar_t*)&buf[filename_wsize], mode_wsize);
+ return ::_wfopen((const wchar_t*)&buf[0], (const wchar_t*)&buf[filename_wsize]);
#else
return fopen(filename, mode);
#endif
}
-// Load file content into memory
+// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
+bool ImFileClose(ImFileHandle f) { return fclose(f) == 0; }
+ImU64 ImFileGetSize(ImFileHandle f) { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
+ImU64 ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fread(data, (size_t)sz, (size_t)count, f); }
+ImU64 ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fwrite(data, (size_t)sz, (size_t)count, f); }
+#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
+
+// Helper: Load file content into memory
// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
-void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, size_t* out_file_size, int padding_bytes)
+// This can't really be used with "rt" because fseek size won't match read size.
+void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
{
- IM_ASSERT(filename && file_open_mode);
+ IM_ASSERT(filename && mode);
if (out_file_size)
*out_file_size = 0;
- FILE* f;
- if ((f = ImFileOpen(filename, file_open_mode)) == NULL)
+ ImFileHandle f;
+ if ((f = ImFileOpen(filename, mode)) == NULL)
return NULL;
- long file_size_signed;
- if (fseek(f, 0, SEEK_END) || (file_size_signed = ftell(f)) == -1 || fseek(f, 0, SEEK_SET))
+ size_t file_size = (size_t)ImFileGetSize(f);
+ if (file_size == (size_t)-1)
{
- fclose(f);
+ ImFileClose(f);
return NULL;
}
- size_t file_size = (size_t)file_size_signed;
void* file_data = IM_ALLOC(file_size + padding_bytes);
if (file_data == NULL)
{
- fclose(f);
+ ImFileClose(f);
return NULL;
}
- if (fread(file_data, 1, file_size, f) != file_size)
+ if (ImFileRead(file_data, 1, file_size, f) != file_size)
{
- fclose(f);
+ ImFileClose(f);
IM_FREE(file_data);
return NULL;
}
if (padding_bytes > 0)
memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
- fclose(f);
+ ImFileClose(f);
if (out_file_size)
*out_file_size = file_size;
@@ -1467,79 +1568,72 @@ void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, size_
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
//-----------------------------------------------------------------------------
-// Convert UTF-8 to 32-bits character, process single character input.
-// Based on stb_from_utf8() from github.com/nothings/stb/
+// Convert UTF-8 to 32-bit character, process single character input.
+// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
// We handle UTF-8 decoding error by skipping forward.
int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
{
- unsigned int c = (unsigned int)-1;
- const unsigned char* str = (const unsigned char*)in_text;
- if (!(*str & 0x80))
+ static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 };
+ static const int masks[] = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
+ static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
+ static const int shiftc[] = { 0, 18, 12, 6, 0 };
+ static const int shifte[] = { 0, 6, 4, 2, 0 };
+ int len = lengths[*(const unsigned char*)in_text >> 3];
+ int wanted = len + !len;
+
+ if (in_text_end == NULL)
+ in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
+
+ // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
+ // so it is fast even with excessive branching.
+ unsigned char s[4];
+ s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
+ s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
+ s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
+ s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
+
+ // Assume a four-byte character and load four bytes. Unused bits are shifted out.
+ *out_char = (uint32_t)(s[0] & masks[len]) << 18;
+ *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
+ *out_char |= (uint32_t)(s[2] & 0x3f) << 6;
+ *out_char |= (uint32_t)(s[3] & 0x3f) << 0;
+ *out_char >>= shiftc[len];
+
+ // Accumulate the various error conditions.
+ int e = 0;
+ e = (*out_char < mins[len]) << 6; // non-canonical encoding
+ e |= ((*out_char >> 11) == 0x1b) << 7; // surrogate half?
+ e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8; // out of range?
+ e |= (s[1] & 0xc0) >> 2;
+ e |= (s[2] & 0xc0) >> 4;
+ e |= (s[3] ) >> 6;
+ e ^= 0x2a; // top two bits of each tail byte correct?
+ e >>= shifte[len];
+
+ if (e)
{
- c = (unsigned int)(*str++);
- *out_char = c;
- return 1;
+ // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
+ // One byte is consumed in case of invalid first byte of in_text.
+ // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
+ // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
+ wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
+ *out_char = IM_UNICODE_CODEPOINT_INVALID;
}
- if ((*str & 0xe0) == 0xc0)
- {
- *out_char = 0xFFFD; // will be invalid but not end of string
- if (in_text_end && in_text_end - (const char*)str < 2) return 1;
- if (*str < 0xc2) return 2;
- c = (unsigned int)((*str++ & 0x1f) << 6);
- if ((*str & 0xc0) != 0x80) return 2;
- c += (*str++ & 0x3f);
- *out_char = c;
- return 2;
- }
- if ((*str & 0xf0) == 0xe0)
- {
- *out_char = 0xFFFD; // will be invalid but not end of string
- if (in_text_end && in_text_end - (const char*)str < 3) return 1;
- if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 3;
- if (*str == 0xed && str[1] > 0x9f) return 3; // str[1] < 0x80 is checked below
- c = (unsigned int)((*str++ & 0x0f) << 12);
- if ((*str & 0xc0) != 0x80) return 3;
- c += (unsigned int)((*str++ & 0x3f) << 6);
- if ((*str & 0xc0) != 0x80) return 3;
- c += (*str++ & 0x3f);
- *out_char = c;
- return 3;
- }
- if ((*str & 0xf8) == 0xf0)
- {
- *out_char = 0xFFFD; // will be invalid but not end of string
- if (in_text_end && in_text_end - (const char*)str < 4) return 1;
- if (*str > 0xf4) return 4;
- if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 4;
- if (*str == 0xf4 && str[1] > 0x8f) return 4; // str[1] < 0x80 is checked below
- c = (unsigned int)((*str++ & 0x07) << 18);
- if ((*str & 0xc0) != 0x80) return 4;
- c += (unsigned int)((*str++ & 0x3f) << 12);
- if ((*str & 0xc0) != 0x80) return 4;
- c += (unsigned int)((*str++ & 0x3f) << 6);
- if ((*str & 0xc0) != 0x80) return 4;
- c += (*str++ & 0x3f);
- // utf-8 encodings of values used in surrogate pairs are invalid
- if ((c & 0xFFFFF800) == 0xD800) return 4;
- *out_char = c;
- return 4;
- }
- *out_char = 0;
- return 0;
+
+ return wanted;
}
int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
{
ImWchar* buf_out = buf;
ImWchar* buf_end = buf + buf_size;
- while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text)
+ while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
{
unsigned int c;
in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
if (c == 0)
break;
- if (c < 0x10000) // FIXME: Losing characters that don't fit in 2 bytes
- *buf_out++ = (ImWchar)c;
+ *buf_out++ = (ImWchar)c;
}
*buf_out = 0;
if (in_text_remaining)
@@ -1556,8 +1650,7 @@ int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
if (c == 0)
break;
- if (c < 0x10000)
- char_count++;
+ char_count++;
}
return char_count;
}
@@ -1577,11 +1670,15 @@ static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c)
buf[1] = (char)(0x80 + (c & 0x3f));
return 2;
}
- if (c >= 0xdc00 && c < 0xe000)
+ if (c < 0x10000)
{
- return 0;
+ if (buf_size < 3) return 0;
+ buf[0] = (char)(0xe0 + (c >> 12));
+ buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
+ buf[2] = (char)(0x80 + ((c ) & 0x3f));
+ return 3;
}
- if (c >= 0xd800 && c < 0xdc00)
+ if (c <= 0x10FFFF)
{
if (buf_size < 4) return 0;
buf[0] = (char)(0xf0 + (c >> 18));
@@ -1590,29 +1687,23 @@ static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c)
buf[3] = (char)(0x80 + ((c ) & 0x3f));
return 4;
}
- //else if (c < 0x10000)
- {
- if (buf_size < 3) return 0;
- buf[0] = (char)(0xe0 + (c >> 12));
- buf[1] = (char)(0x80 + ((c>> 6) & 0x3f));
- buf[2] = (char)(0x80 + ((c ) & 0x3f));
- return 3;
- }
+ // Invalid code point, the max unicode is 0x10FFFF
+ return 0;
}
// Not optimal but we very rarely use this function.
int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
{
- unsigned int dummy = 0;
- return ImTextCharFromUtf8(&dummy, in_text, in_text_end);
+ unsigned int unused = 0;
+ return ImTextCharFromUtf8(&unused, in_text, in_text_end);
}
static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
{
if (c < 0x80) return 1;
if (c < 0x800) return 2;
- if (c >= 0xdc00 && c < 0xe000) return 0;
- if (c >= 0xd800 && c < 0xdc00) return 4;
+ if (c < 0x10000) return 3;
+ if (c <= 0x10FFFF) return 4;
return 3;
}
@@ -1620,13 +1711,13 @@ int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWch
{
char* buf_out = buf;
const char* buf_end = buf + buf_size;
- while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text)
+ while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
{
unsigned int c = (unsigned int)(*in_text++);
if (c < 0x80)
*buf_out++ = (char)c;
else
- buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end-buf_out-1), c);
+ buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end - buf_out - 1), c);
}
*buf_out = 0;
return (int)(buf_out - buf);
@@ -1647,13 +1738,22 @@ int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_e
}
//-----------------------------------------------------------------------------
-// [SECTION] MISC HELPERS/UTILTIES (Color functions)
+// [SECTION] MISC HELPERS/UTILITIES (Color functions)
// Note: The Convert functions are early design which are not consistent with other API.
//-----------------------------------------------------------------------------
+IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
+{
+ float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
+ int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
+ int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
+ int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
+ return IM_COL32(r, g, b, 0xFF);
+}
+
ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
{
- float s = 1.0f/255.0f;
+ float s = 1.0f / 255.0f;
return ImVec4(
((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
@@ -1704,7 +1804,7 @@ void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float&
return;
}
- h = ImFmod(h, 1.0f) / (60.0f/360.0f);
+ h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
int i = (int)h;
float f = h - (float)i;
float p = v * (1.0f - s);
@@ -1722,38 +1822,6 @@ void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float&
}
}
-ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
-{
- ImGuiStyle& style = GImGui->Style;
- ImVec4 c = style.Colors[idx];
- c.w *= style.Alpha * alpha_mul;
- return ColorConvertFloat4ToU32(c);
-}
-
-ImU32 ImGui::GetColorU32(const ImVec4& col)
-{
- ImGuiStyle& style = GImGui->Style;
- ImVec4 c = col;
- c.w *= style.Alpha;
- return ColorConvertFloat4ToU32(c);
-}
-
-const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
-{
- ImGuiStyle& style = GImGui->Style;
- return style.Colors[idx];
-}
-
-ImU32 ImGui::GetColorU32(ImU32 col)
-{
- float style_alpha = GImGui->Style.Alpha;
- if (style_alpha >= 1.0f)
- return col;
- ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
- a = (ImU32)(a * style_alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
- return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
-}
-
//-----------------------------------------------------------------------------
// [SECTION] ImGuiStorage
// Helper: Key->value storage
@@ -1953,7 +2021,7 @@ void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVectorHostSkipItems : g.CurrentWindow->SkipItems);
+}
+
// Helper to calculate coarse clipping of large list of evenly sized items.
// NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern.
// NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX
@@ -2094,7 +2170,7 @@ void ImGui::CalcListClipping(int items_count, float items_height, int* out_items
*out_items_display_end = items_count;
return;
}
- if (window->SkipItems)
+ if (GetSkipItemForListClipping())
{
*out_items_display_start = *out_items_display_end = 0;
return;
@@ -2103,7 +2179,9 @@ void ImGui::CalcListClipping(int items_count, float items_height, int* out_items
// We create the union of the ClipRect and the NavScoringRect which at worst should be 1 page away from ClipRect
ImRect unclipped_rect = window->ClipRect;
if (g.NavMoveRequest)
- unclipped_rect.Add(g.NavScoringRectScreen);
+ unclipped_rect.Add(g.NavScoringRect);
+ if (g.NavJustMovedToId && window->NavLastIds[0] == g.NavJustMovedToId)
+ unclipped_rect.Add(ImRect(window->Pos + window->NavRectRel[0].Min, window->Pos + window->NavRectRel[0].Max));
const ImVec2 pos = window->DC.CursorPos;
int start = (int)((unclipped_rect.Min.y - pos.y) / items_height);
@@ -2121,50 +2199,71 @@ void ImGui::CalcListClipping(int items_count, float items_height, int* out_items
*out_items_display_end = end;
}
-static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height)
+static void SetCursorPosYAndSetupForPrevLine(float pos_y, float line_height)
{
// Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
// FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
// The clipper should probably have a 4th step to display the last item in a regular manner.
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
+ float off_y = pos_y - window->DC.CursorPos.y;
window->DC.CursorPos.y = pos_y;
window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y);
window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
- if (ImGuiColumns* columns = window->DC.CurrentColumns)
+ if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
+ if (ImGuiTable* table = g.CurrentTable)
+ {
+ if (table->IsInsideRow)
+ ImGui::TableEndRow(table);
+ table->RowPosY2 = window->DC.CursorPos.y;
+ const int row_increase = (int)((off_y / line_height) + 0.5f);
+ //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
+ table->RowBgColorCounter += row_increase;
+ }
}
-// Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1
+ImGuiListClipper::ImGuiListClipper()
+{
+ memset(this, 0, sizeof(*this));
+ ItemsCount = -1;
+}
+
+ImGuiListClipper::~ImGuiListClipper()
+{
+ IM_ASSERT(ItemsCount == -1 && "Forgot to call End(), or to Step() until false?");
+}
+
+// Use case A: Begin() called from constructor with items_height<0, then called again from Step() in StepNo 1
// Use case B: Begin() called from constructor with items_height>0
// FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style.
-void ImGuiListClipper::Begin(int count, float items_height)
+void ImGuiListClipper::Begin(int items_count, float items_height)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
+ if (ImGuiTable* table = g.CurrentTable)
+ if (table->IsInsideRow)
+ ImGui::TableEndRow(table);
+
StartPosY = window->DC.CursorPos.y;
ItemsHeight = items_height;
- ItemsCount = count;
+ ItemsCount = items_count;
+ ItemsFrozen = 0;
StepNo = 0;
- DisplayEnd = DisplayStart = -1;
- if (ItemsHeight > 0.0f)
- {
- ImGui::CalcListClipping(ItemsCount, ItemsHeight, &DisplayStart, &DisplayEnd); // calculate how many to clip/display
- if (DisplayStart > 0)
- SetCursorPosYAndSetupDummyPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor
- StepNo = 2;
- }
+ DisplayStart = -1;
+ DisplayEnd = 0;
}
void ImGuiListClipper::End()
{
- if (ItemsCount < 0)
+ if (ItemsCount < 0) // Already ended
return;
+
// In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user.
- if (ItemsCount < INT_MAX)
- SetCursorPosYAndSetupDummyPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor
+ if (ItemsCount < INT_MAX && DisplayStart >= 0)
+ SetCursorPosYAndSetupForPrevLine(StartPosY + (ItemsCount - ItemsFrozen) * ItemsHeight, ItemsHeight);
ItemsCount = -1;
StepNo = 3;
}
@@ -2174,45 +2273,335 @@ bool ImGuiListClipper::Step()
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
- if (ItemsCount == 0 || window->SkipItems)
+ ImGuiTable* table = g.CurrentTable;
+ if (table && table->IsInsideRow)
+ ImGui::TableEndRow(table);
+
+ // No items
+ if (ItemsCount == 0 || GetSkipItemForListClipping())
{
+ End();
+ return false;
+ }
+
+ // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
+ if (StepNo == 0)
+ {
+ // While we are in frozen row state, keep displaying items one by one, unclipped
+ // FIXME: Could be stored as a table-agnostic state.
+ if (table != NULL && !table->IsUnfrozenRows)
+ {
+ DisplayStart = ItemsFrozen;
+ DisplayEnd = ItemsFrozen + 1;
+ ItemsFrozen++;
+ return true;
+ }
+
+ StartPosY = window->DC.CursorPos.y;
+ if (ItemsHeight <= 0.0f)
+ {
+ // Submit the first item so we can measure its height (generally it is 0..1)
+ DisplayStart = ItemsFrozen;
+ DisplayEnd = ItemsFrozen + 1;
+ StepNo = 1;
+ return true;
+ }
+
+ // Already has item height (given by user in Begin): skip to calculating step
+ DisplayStart = DisplayEnd;
+ StepNo = 2;
+ }
+
+ // Step 1: the clipper infer height from first element
+ if (StepNo == 1)
+ {
+ IM_ASSERT(ItemsHeight <= 0.0f);
+ if (table)
+ {
+ const float pos_y1 = table->RowPosY1; // Using this instead of StartPosY to handle clipper straddling the frozen row
+ const float pos_y2 = table->RowPosY2; // Using this instead of CursorPos.y to take account of tallest cell.
+ ItemsHeight = pos_y2 - pos_y1;
+ window->DC.CursorPos.y = pos_y2;
+ }
+ else
+ {
+ ItemsHeight = window->DC.CursorPos.y - StartPosY;
+ }
+ IM_ASSERT(ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
+ StepNo = 2;
+ }
+
+ // Reached end of list
+ if (DisplayEnd >= ItemsCount)
+ {
+ End();
+ return false;
+ }
+
+ // Step 2: calculate the actual range of elements to display, and position the cursor before the first element
+ if (StepNo == 2)
+ {
+ IM_ASSERT(ItemsHeight > 0.0f);
+
+ int already_submitted = DisplayEnd;
+ ImGui::CalcListClipping(ItemsCount - already_submitted, ItemsHeight, &DisplayStart, &DisplayEnd);
+ DisplayStart += already_submitted;
+ DisplayEnd += already_submitted;
+
+ // Seek cursor
+ if (DisplayStart > already_submitted)
+ SetCursorPosYAndSetupForPrevLine(StartPosY + (DisplayStart - ItemsFrozen) * ItemsHeight, ItemsHeight);
+
+ StepNo = 3;
+ return true;
+ }
+
+ // Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
+ // Advance the cursor to the end of the list and then returns 'false' to end the loop.
+ if (StepNo == 3)
+ {
+ // Seek cursor
+ if (ItemsCount < INT_MAX)
+ SetCursorPosYAndSetupForPrevLine(StartPosY + (ItemsCount - ItemsFrozen) * ItemsHeight, ItemsHeight); // advance cursor
ItemsCount = -1;
return false;
}
- if (StepNo == 0) // Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height.
- {
- DisplayStart = 0;
- DisplayEnd = 1;
- StartPosY = window->DC.CursorPos.y;
- StepNo = 1;
- return true;
- }
- if (StepNo == 1) // Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element.
- {
- if (ItemsCount == 1) { ItemsCount = -1; return false; }
- float items_height = window->DC.CursorPos.y - StartPosY;
- IM_ASSERT(items_height > 0.0f); // If this triggers, it means Item 0 hasn't moved the cursor vertically
- Begin(ItemsCount - 1, items_height);
- DisplayStart++;
- DisplayEnd++;
- StepNo = 3;
- return true;
- }
- if (StepNo == 2) // Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user still call Step(). Does nothing and switch to Step 3.
- {
- IM_ASSERT(DisplayStart >= 0 && DisplayEnd >= 0);
- StepNo = 3;
- return true;
- }
- if (StepNo == 3) // Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop.
- End();
+
+ IM_ASSERT(0);
return false;
}
+//-----------------------------------------------------------------------------
+// [SECTION] STYLING
+//-----------------------------------------------------------------------------
+
+ImGuiStyle& ImGui::GetStyle()
+{
+ IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
+ return GImGui->Style;
+}
+
+ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
+{
+ ImGuiStyle& style = GImGui->Style;
+ ImVec4 c = style.Colors[idx];
+ c.w *= style.Alpha * alpha_mul;
+ return ColorConvertFloat4ToU32(c);
+}
+
+ImU32 ImGui::GetColorU32(const ImVec4& col)
+{
+ ImGuiStyle& style = GImGui->Style;
+ ImVec4 c = col;
+ c.w *= style.Alpha;
+ return ColorConvertFloat4ToU32(c);
+}
+
+const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
+{
+ ImGuiStyle& style = GImGui->Style;
+ return style.Colors[idx];
+}
+
+ImU32 ImGui::GetColorU32(ImU32 col)
+{
+ ImGuiStyle& style = GImGui->Style;
+ if (style.Alpha >= 1.0f)
+ return col;
+ ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
+ a = (ImU32)(a * style.Alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
+ return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
+}
+
+// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
+void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiColorMod backup;
+ backup.Col = idx;
+ backup.BackupValue = g.Style.Colors[idx];
+ g.ColorStack.push_back(backup);
+ g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
+}
+
+void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiColorMod backup;
+ backup.Col = idx;
+ backup.BackupValue = g.Style.Colors[idx];
+ g.ColorStack.push_back(backup);
+ g.Style.Colors[idx] = col;
+}
+
+void ImGui::PopStyleColor(int count)
+{
+ ImGuiContext& g = *GImGui;
+ while (count > 0)
+ {
+ ImGuiColorMod& backup = g.ColorStack.back();
+ g.Style.Colors[backup.Col] = backup.BackupValue;
+ g.ColorStack.pop_back();
+ count--;
+ }
+}
+
+struct ImGuiStyleVarInfo
+{
+ ImGuiDataType Type;
+ ImU32 Count;
+ ImU32 Offset;
+ void* GetVarPtr(ImGuiStyle* style) const { return (void*)((unsigned char*)style + Offset); }
+};
+
+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, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, CellPadding) }, // ImGuiStyleVar_CellPadding
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
+ { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding
+ { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
+ { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
+};
+
+static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx)
+{
+ 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 && var_info->Count == 1)
+ {
+ ImGuiContext& g = *GImGui;
+ float* pvar = (float*)var_info->GetVarPtr(&g.Style);
+ g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
+ *pvar = val;
+ return;
+ }
+ IM_ASSERT(0 && "Called PushStyleVar() float variant but variable is not a float!");
+}
+
+void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
+{
+ const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
+ if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
+ {
+ ImGuiContext& g = *GImGui;
+ ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
+ g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
+ *pvar = val;
+ return;
+ }
+ IM_ASSERT(0 && "Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!");
+}
+
+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.StyleVarStack.back();
+ const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx);
+ 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.StyleVarStack.pop_back();
+ count--;
+ }
+}
+
+const char* ImGui::GetStyleColorName(ImGuiCol idx)
+{
+ // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
+ switch (idx)
+ {
+ case ImGuiCol_Text: return "Text";
+ case ImGuiCol_TextDisabled: return "TextDisabled";
+ case ImGuiCol_WindowBg: return "WindowBg";
+ case ImGuiCol_ChildBg: return "ChildBg";
+ case ImGuiCol_PopupBg: return "PopupBg";
+ case ImGuiCol_Border: return "Border";
+ case ImGuiCol_BorderShadow: return "BorderShadow";
+ case ImGuiCol_FrameBg: return "FrameBg";
+ case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
+ case ImGuiCol_FrameBgActive: return "FrameBgActive";
+ case ImGuiCol_TitleBg: return "TitleBg";
+ case ImGuiCol_TitleBgActive: return "TitleBgActive";
+ case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
+ case ImGuiCol_MenuBarBg: return "MenuBarBg";
+ case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
+ case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
+ case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
+ case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
+ case ImGuiCol_CheckMark: return "CheckMark";
+ case ImGuiCol_SliderGrab: return "SliderGrab";
+ case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
+ case ImGuiCol_Button: return "Button";
+ case ImGuiCol_ButtonHovered: return "ButtonHovered";
+ case ImGuiCol_ButtonActive: return "ButtonActive";
+ case ImGuiCol_Header: return "Header";
+ case ImGuiCol_HeaderHovered: return "HeaderHovered";
+ case ImGuiCol_HeaderActive: return "HeaderActive";
+ case ImGuiCol_Separator: return "Separator";
+ case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
+ case ImGuiCol_SeparatorActive: return "SeparatorActive";
+ case ImGuiCol_ResizeGrip: return "ResizeGrip";
+ case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
+ case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
+ case ImGuiCol_Tab: return "Tab";
+ case ImGuiCol_TabHovered: return "TabHovered";
+ case ImGuiCol_TabActive: return "TabActive";
+ case ImGuiCol_TabUnfocused: return "TabUnfocused";
+ case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
+ case ImGuiCol_PlotLines: return "PlotLines";
+ case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
+ case ImGuiCol_PlotHistogram: return "PlotHistogram";
+ case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
+ case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
+ case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
+ case ImGuiCol_TableBorderLight: return "TableBorderLight";
+ case ImGuiCol_TableRowBg: return "TableRowBg";
+ case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
+ case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
+ case ImGuiCol_DragDropTarget: return "DragDropTarget";
+ case ImGuiCol_NavHighlight: return "NavHighlight";
+ case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
+ case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
+ case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
+ }
+ IM_ASSERT(0);
+ return "Unknown";
+}
+
+
//-----------------------------------------------------------------------------
// [SECTION] RENDER HELPERS
-// Those (internal) functions are currently quite a legacy mess - their signature and behavior will change.
-// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: state.
+// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
+// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
+// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
//-----------------------------------------------------------------------------
const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
@@ -2405,7 +2794,7 @@ void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border,
const float border_size = g.Style.FrameBorderSize;
if (border && border_size > 0.0f)
{
- window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
+ window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
}
}
@@ -2417,66 +2806,11 @@ void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
const float border_size = g.Style.FrameBorderSize;
if (border_size > 0.0f)
{
- window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
+ window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
}
}
-// Render an arrow aimed to be aligned with text (p_min is a position in the same space text would be positioned). To e.g. denote expanded/collapsed state
-void ImGui::RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImU32 col, ImGuiDir dir, float scale)
-{
- const float h = draw_list->_Data->FontSize * 1.00f;
- float r = h * 0.40f * scale;
- ImVec2 center = pos + ImVec2(h * 0.50f, h * 0.50f * scale);
-
- ImVec2 a, b, c;
- switch (dir)
- {
- case ImGuiDir_Up:
- case ImGuiDir_Down:
- if (dir == ImGuiDir_Up) r = -r;
- a = ImVec2(+0.000f,+0.750f) * r;
- b = ImVec2(-0.866f,-0.750f) * r;
- c = ImVec2(+0.866f,-0.750f) * r;
- break;
- case ImGuiDir_Left:
- case ImGuiDir_Right:
- if (dir == ImGuiDir_Left) r = -r;
- a = ImVec2(+0.750f,+0.000f) * r;
- b = ImVec2(-0.750f,+0.866f) * r;
- c = ImVec2(-0.750f,-0.866f) * r;
- break;
- case ImGuiDir_None:
- case ImGuiDir_COUNT:
- IM_ASSERT(0);
- break;
- }
- draw_list->AddTriangleFilled(center + a, center + b, center + c, col);
-}
-
-void ImGui::RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col)
-{
- draw_list->AddCircleFilled(pos, draw_list->_Data->FontSize * 0.20f, col, 8);
-}
-
-void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col, float sz)
-{
- ImGuiContext& g = *GImGui;
- ImGuiWindow* window = g.CurrentWindow;
-
- float thickness = ImMax(sz / 5.0f, 1.0f);
- sz -= thickness*0.5f;
- pos += ImVec2(thickness*0.25f, thickness*0.25f);
-
- float third = sz / 3.0f;
- float bx = pos.x + third;
- float by = pos.y + sz - third*0.5f;
- window->DrawList->PathLineTo(ImVec2(bx - third, by - third));
- window->DrawList->PathLineTo(ImVec2(bx, by));
- window->DrawList->PathLineTo(ImVec2(bx + third*2, by - third*2));
- window->DrawList->PathStroke(col, false, thickness);
-}
-
void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
{
ImGuiContext& g = *GImGui;
@@ -2495,11 +2829,11 @@ void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFl
{
const float THICKNESS = 2.0f;
const float DISTANCE = 3.0f + THICKNESS * 0.5f;
- display_rect.Expand(ImVec2(DISTANCE,DISTANCE));
+ 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);
+ 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();
}
@@ -2514,83 +2848,27 @@ void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFl
//-----------------------------------------------------------------------------
// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
-ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name)
- : DrawListInst(&context->DrawListSharedData)
+ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name) : DrawListInst(NULL)
{
+ memset(this, 0, sizeof(*this));
Name = ImStrdup(name);
+ NameBufLen = (int)strlen(name) + 1;
ID = ImHashStr(name);
IDStack.push_back(ID);
- Flags = FlagsPreviousFrame = ImGuiWindowFlags_None;
- Viewport = NULL;
- ViewportId = 0;
- ViewportAllowPlatformMonitorExtend = -1;
- ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
- Pos = ImVec2(0.0f, 0.0f);
- Size = SizeFull = ImVec2(0.0f, 0.0f);
- ContentSize = ContentSizeExplicit = ImVec2(0.0f, 0.0f);
- WindowPadding = ImVec2(0.0f, 0.0f);
- WindowRounding = 0.0f;
- WindowBorderSize = 0.0f;
- NameBufLen = (int)strlen(name) + 1;
MoveId = GetID("#MOVE");
- ChildId = 0;
- Scroll = ImVec2(0.0f, 0.0f);
ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
- ScrollbarSizes = ImVec2(0.0f, 0.0f);
- ScrollbarX = ScrollbarY = false;
- ViewportOwned = false;
- Active = WasActive = false;
- WriteAccessed = false;
- Collapsed = false;
- WantCollapseToggle = false;
- SkipItems = false;
- Appearing = false;
- Hidden = false;
- IsFallbackWindow = false;
- HasCloseButton = false;
- ResizeBorderHeld = -1;
- BeginCount = 0;
- BeginOrderWithinParent = -1;
- BeginOrderWithinContext = -1;
- PopupId = 0;
AutoFitFramesX = AutoFitFramesY = -1;
- AutoFitChildAxises = 0x00;
- AutoFitOnlyGrows = false;
AutoPosLastDirection = ImGuiDir_None;
- HiddenFramesCanSkipItems = HiddenFramesCannotSkipItems = 0;
- SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
+ SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
-
- InnerRect = ImRect(0.0f, 0.0f, 0.0f, 0.0f); // Clear so the InnerRect.GetSize() code in Begin() doesn't lead to overflow even if the result isn't used.
-
LastFrameActive = -1;
- LastFrameJustFocused = -1;
LastTimeActive = -1.0f;
- ItemWidthDefault = 0.0f;
- FontWindowScale = FontDpiScale = 1.0f;
- SettingsIdx = -1;
-
+ FontWindowScale = 1.0f;
+ SettingsOffset = -1;
DrawList = &DrawListInst;
+ DrawList->_Data = &context->DrawListSharedData;
DrawList->_OwnerName = Name;
- ParentWindow = NULL;
- RootWindow = NULL;
- RootWindowDockStop = NULL;
- RootWindowForTitleBarHighlight = NULL;
- RootWindowForNav = NULL;
-
- NavLastIds[0] = NavLastIds[1] = 0;
- NavRectRel[0] = NavRectRel[1] = ImRect();
- NavLastChildNavWindow = NULL;
-
- MemoryCompacted = false;
- MemoryDrawListIdxCapacity = MemoryDrawListVtxCapacity = 0;
-
- DockNode = DockNodeAsHost = NULL;
- DockId = 0;
- DockTabItemStatusFlags = ImGuiItemStatusFlags_None;
- DockOrder = -1;
- DockIsActive = DockTabIsVisible = DockTabWantClose = false;
}
ImGuiWindow::~ImGuiWindow()
@@ -2598,7 +2876,7 @@ ImGuiWindow::~ImGuiWindow()
IM_ASSERT(DrawList == &DrawListInst);
IM_DELETE(Name);
for (int i = 0; i != ColumnsStorage.Size; i++)
- ColumnsStorage[i].~ImGuiColumns();
+ ColumnsStorage[i].~ImGuiOldColumns();
}
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
@@ -2606,6 +2884,10 @@ ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
ImGuiID seed = IDStack.back();
ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
ImGui::KeepAliveID(id);
+#ifdef IMGUI_ENABLE_TEST_ENGINE
+ ImGuiContext& g = *GImGui;
+ IMGUI_TEST_ENGINE_ID_INFO2(id, ImGuiDataType_String, str, str_end);
+#endif
return id;
}
@@ -2614,6 +2896,10 @@ ImGuiID ImGuiWindow::GetID(const void* ptr)
ImGuiID seed = IDStack.back();
ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
ImGui::KeepAliveID(id);
+#ifdef IMGUI_ENABLE_TEST_ENGINE
+ ImGuiContext& g = *GImGui;
+ IMGUI_TEST_ENGINE_ID_INFO(id, ImGuiDataType_Pointer, ptr);
+#endif
return id;
}
@@ -2622,25 +2908,44 @@ ImGuiID ImGuiWindow::GetID(int n)
ImGuiID seed = IDStack.back();
ImGuiID id = ImHashData(&n, sizeof(n), seed);
ImGui::KeepAliveID(id);
+#ifdef IMGUI_ENABLE_TEST_ENGINE
+ ImGuiContext& g = *GImGui;
+ IMGUI_TEST_ENGINE_ID_INFO(id, ImGuiDataType_S32, (intptr_t)n);
+#endif
return id;
}
ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end)
{
ImGuiID seed = IDStack.back();
- return ImHashStr(str, str_end ? (str_end - str) : 0, seed);
+ ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
+#ifdef IMGUI_ENABLE_TEST_ENGINE
+ ImGuiContext& g = *GImGui;
+ IMGUI_TEST_ENGINE_ID_INFO2(id, ImGuiDataType_String, str, str_end);
+#endif
+ return id;
}
ImGuiID ImGuiWindow::GetIDNoKeepAlive(const void* ptr)
{
ImGuiID seed = IDStack.back();
- return ImHashData(&ptr, sizeof(void*), seed);
+ ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
+#ifdef IMGUI_ENABLE_TEST_ENGINE
+ ImGuiContext& g = *GImGui;
+ IMGUI_TEST_ENGINE_ID_INFO(id, ImGuiDataType_Pointer, ptr);
+#endif
+ return id;
}
ImGuiID ImGuiWindow::GetIDNoKeepAlive(int n)
{
ImGuiID seed = IDStack.back();
- return ImHashData(&n, sizeof(n), seed);
+ ImGuiID id = ImHashData(&n, sizeof(n), seed);
+#ifdef IMGUI_ENABLE_TEST_ENGINE
+ ImGuiContext& g = *GImGui;
+ IMGUI_TEST_ENGINE_ID_INFO(id, ImGuiDataType_S32, (intptr_t)n);
+#endif
+ return id;
}
// This is only used in rare/specific situations to manufacture an ID out of nowhere.
@@ -2657,15 +2962,22 @@ static void SetCurrentWindow(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
g.CurrentWindow = window;
+ g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
if (window)
g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
}
+void ImGui::GcCompactTransientMiscBuffers()
+{
+ ImGuiContext& g = *GImGui;
+ g.ItemFlagsStack.clear();
+ g.GroupStack.clear();
+ TableGcCompactSettings();
+}
+
// Free up/compact internal window buffers, we can use this when a window becomes unused.
-// This is currently unused by the library, but you may call this yourself for easy GC.
// Not freed:
-// - ImGuiWindow, ImGuiWindowSettings, Name
-// - StateStorage, ColumnsStorage (may hold useful data)
+// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
{
@@ -2673,12 +2985,10 @@ void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
window->IDStack.clear();
- window->DrawList->ClearFreeMemory();
+ window->DrawList->_ClearFreeMemory();
window->DC.ChildWindows.clear();
- window->DC.ItemFlagsStack.clear();
window->DC.ItemWidthStack.clear();
window->DC.TextWrapPosStack.clear();
- window->DC.GroupStack.clear();
}
void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
@@ -2691,25 +3001,6 @@ void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
}
-void ImGui::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;
-}
-
-void ImGui::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;
@@ -2727,6 +3018,7 @@ void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
}
g.ActiveId = id;
g.ActiveIdAllowOverlap = false;
+ g.ActiveIdNoClearOnFocusLoss = false;
g.ActiveIdWindow = window;
g.ActiveIdHasBeenEditedThisFrame = false;
if (id)
@@ -2737,37 +3029,15 @@ void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
// Clear declaration of inputs claimed by the widget
// (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
+ g.ActiveIdUsingMouseWheel = false;
g.ActiveIdUsingNavDirMask = 0x00;
g.ActiveIdUsingNavInputMask = 0x00;
g.ActiveIdUsingKeyInputMask = 0x00;
}
-// FIXME-NAV: The existence of SetNavID/SetNavIDWithRectRel/SetFocusID is incredibly messy and confusing and needs some explanation or refactoring.
-void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
-{
- ImGuiContext& g = *GImGui;
- IM_ASSERT(id != 0);
-
- // Assume that SetFocusID() is called in the context where its NavLayer is the current layer, which is the case everywhere we call it.
- const ImGuiNavLayer 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()
{
- SetActiveID(0, NULL);
+ SetActiveID(0, NULL); // g.ActiveId = 0;
}
void ImGui::SetHoveredID(ImGuiID id)
@@ -2775,6 +3045,7 @@ void ImGui::SetHoveredID(ImGuiID id)
ImGuiContext& g = *GImGui;
g.HoveredId = id;
g.HoveredIdAllowOverlap = false;
+ g.HoveredIdUsingMouseWheel = false;
if (id != 0 && g.HoveredIdPreviousFrame != id)
g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
}
@@ -2823,108 +3094,6 @@ static inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFla
if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
return false;
}
-
- // Filter by viewport
- if (window->Viewport != g.MouseViewport)
- if (g.MovingWindow == NULL || window->RootWindow != g.MovingWindow->RootWindow)
- return false;
-
- return true;
-}
-
-// Advance cursor given item size for layout.
-void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
-{
- ImGuiContext& g = *GImGui;
- ImGuiWindow* window = g.CurrentWindow;
- if (window->SkipItems)
- return;
-
- // We increase the height in this function to accommodate for baseline offset.
- // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
- // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
- const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
- const float line_height = ImMax(window->DC.CurrLineSize.y, size.y + offset_to_match_baseline_y);
-
- // Always align ourselves on pixel boundaries
- //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
- window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
- window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y;
- window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); // Next line
- window->DC.CursorPos.y = IM_FLOOR(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y); // Next line
- window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
- window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
- //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
-
- window->DC.PrevLineSize.y = line_height;
- window->DC.CurrLineSize.y = 0.0f;
- window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
- window->DC.CurrLineTextBaseOffset = 0.0f;
-
- // Horizontal layout mode
- if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
- SameLine();
-}
-
-void ImGui::ItemSize(const ImRect& bb, float text_baseline_y)
-{
- ItemSize(bb.GetSize(), text_baseline_y);
-}
-
-// 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
-// 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;
-
- 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).
- // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
- // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
- window->DC.NavLayerActiveMaskNext |= window->DC.NavLayerCurrentMask;
- if (g.NavId == id || g.NavAnyRequest)
- if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
- if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
- NavProcessItem(window, nav_bb_arg ? *nav_bb_arg : bb, id);
-
- // [DEBUG] Item Picker tool, when enabling the "extended" version we perform the check in ItemAdd()
-#ifdef IMGUI_DEBUG_TOOL_ITEM_PICKER_EX
- if (id == g.DebugItemPickerBreakID)
- {
- IM_DEBUG_BREAK();
- g.DebugItemPickerBreakID = 0;
- }
-#endif
- }
-
- window->DC.LastItemId = id;
- window->DC.LastItemRect = bb;
- window->DC.LastItemStatusFlags = ImGuiItemStatusFlags_None;
- g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
-
-#ifdef IMGUI_ENABLE_TEST_ENGINE
- if (id != 0)
- IMGUI_TEST_ENGINE_ITEM_ADD(nav_bb_arg ? *nav_bb_arg : bb, id);
-#endif
-
- // Clipping test
- const bool is_clipped = IsClippedEx(bb, id, false);
- 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)
- if (IsMouseHoveringRect(bb.Min, bb.Max))
- window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HoveredRect;
return true;
}
@@ -2965,9 +3134,9 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
if ((window->DC.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
return false;
- // Special handling for the dummy item after Begin() which represent the title bar or tab.
+ // Special handling for calling after Begin() which represent the title bar or tab.
// When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
- if ((window->DC.LastItemId == window->ID || window->DC.LastItemId == window->MoveId) && window->WriteAccessed)
+ if (window->DC.LastItemId == window->MoveId && window->WriteAccessed)
return false;
return true;
}
@@ -2986,22 +3155,30 @@ bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id)
return false;
if (!IsMouseHoveringRect(bb.Min, bb.Max))
return false;
- if (g.NavDisableMouseHover || !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
+ if (g.NavDisableMouseHover)
return false;
- if (window->DC.ItemFlags & ImGuiItemFlags_Disabled)
+ if (!IsWindowContentHoverable(window, ImGuiHoveredFlags_None) || (window->DC.ItemFlags & ImGuiItemFlags_Disabled))
+ {
+ g.HoveredIdDisabled = true;
return false;
+ }
- SetHoveredID(id);
+ // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
+ // hover test in widgets code. We could also decide to split this function is two.
+ if (id != 0)
+ {
+ SetHoveredID(id);
- // [DEBUG] Item Picker tool!
- // We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making
- // the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered
- // items if we perform the test in ItemAdd(), but that would incur a small runtime cost.
- // #define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX in imconfig.h if you want this check to also be performed in ItemAdd().
- if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
- GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
- if (g.DebugItemPickerBreakID == id)
- IM_DEBUG_BREAK();
+ // [DEBUG] Item Picker tool!
+ // We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making
+ // the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered
+ // items if we perform the test in ItemAdd(), but that would incur a small runtime cost.
+ // #define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX in imconfig.h if you want this check to also be performed in ItemAdd().
+ if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
+ GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
+ if (g.DebugItemPickerBreakId == id)
+ IM_DEBUG_BREAK();
+ }
return true;
}
@@ -3011,12 +3188,21 @@ bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (!bb.Overlaps(window->ClipRect))
- if (id == 0 || id != g.ActiveId)
+ if (id == 0 || (id != g.ActiveId && id != g.NavId))
if (clip_even_when_logged || !g.LogEnabled)
return true;
return false;
}
+// This is also inlined in ItemAdd()
+// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set window->DC.LastItemDisplayRect!
+void ImGui::SetLastItemData(ImGuiWindow* window, ImGuiID item_id, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
+{
+ window->DC.LastItemId = item_id;
+ window->DC.LastItemStatusFlags = item_flags;
+ window->DC.LastItemRect = item_rect;
+}
+
// Process TAB/Shift+TAB. Be mindful that this function may _clear_ the ActiveID when tabbing out.
bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id)
{
@@ -3024,24 +3210,24 @@ bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id)
// Increment counters
const bool is_tab_stop = (window->DC.ItemFlags & (ImGuiItemFlags_NoTabStop | ImGuiItemFlags_Disabled)) == 0;
- window->DC.FocusCounterAll++;
+ window->DC.FocusCounterRegular++;
if (is_tab_stop)
- window->DC.FocusCounterTab++;
+ window->DC.FocusCounterTabStop++;
// Process TAB/Shift-TAB to tab *OUT* of the currently focused item.
// (Note that we can always TAB out of a widget that doesn't allow tabbing in)
if (g.ActiveId == id && g.FocusTabPressed && !IsActiveIdUsingKey(ImGuiKey_Tab) && g.FocusRequestNextWindow == NULL)
{
g.FocusRequestNextWindow = window;
- g.FocusRequestNextCounterTab = window->DC.FocusCounterTab + (g.IO.KeyShift ? (is_tab_stop ? -1 : 0) : +1); // Modulo on index will be applied at the end of frame once we've got the total counter of items.
+ g.FocusRequestNextCounterTabStop = window->DC.FocusCounterTabStop + (g.IO.KeyShift ? (is_tab_stop ? -1 : 0) : +1); // Modulo on index will be applied at the end of frame once we've got the total counter of items.
}
// Handle focus requests
if (g.FocusRequestCurrWindow == window)
{
- if (window->DC.FocusCounterAll == g.FocusRequestCurrCounterAll)
+ if (window->DC.FocusCounterRegular == g.FocusRequestCurrCounterRegular)
return true;
- if (is_tab_stop && window->DC.FocusCounterTab == g.FocusRequestCurrCounterTab)
+ if (is_tab_stop && window->DC.FocusCounterTabStop == g.FocusRequestCurrCounterTabStop)
{
g.NavJustTabbedId = id;
return true;
@@ -3057,8 +3243,8 @@ bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id)
void ImGui::FocusableItemUnregister(ImGuiWindow* window)
{
- window->DC.FocusCounterAll--;
- window->DC.FocusCounterTab--;
+ window->DC.FocusCounterRegular--;
+ window->DC.FocusCounterTabStop--;
}
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
@@ -3066,11 +3252,21 @@ float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
if (wrap_pos_x < 0.0f)
return 0.0f;
- ImGuiWindow* window = GImGui->CurrentWindow;
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
if (wrap_pos_x == 0.0f)
+ {
+ // We could decide to setup a default wrapping max point for auto-resizing windows,
+ // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
+ //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
+ // wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
+ //else
wrap_pos_x = window->WorkRect.Max.x;
+ }
else if (wrap_pos_x > 0.0f)
+ {
wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
+ }
return ImMax(wrap_pos_x - pos.x, 1.0f);
}
@@ -3126,24 +3322,6 @@ void ImGui::SetCurrentContext(ImGuiContext* ctx)
#endif
}
-// Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
-// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
-// If the user has inconsistent compilation settings, imgui configuration #define, packing pragma, etc. your user code
-// may see different structures than what imgui.cpp sees, which is problematic.
-// We usually require settings to be in imconfig.h to make sure that they are accessible to all compilation units involved with Dear ImGui.
-bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
-{
- bool error = false;
- if (strcmp(version, IMGUI_VERSION)!=0) { error = true; IM_ASSERT(strcmp(version,IMGUI_VERSION)==0 && "Mismatched version string!"); }
- if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
- if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
- if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
- if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
- if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
- if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
- return !error;
-}
-
void ImGui::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data)
{
GImAllocatorAllocFunc = alloc_func;
@@ -3170,29 +3348,47 @@ void ImGui::DestroyContext(ImGuiContext* ctx)
IM_DELETE(ctx);
}
+// No specific ordering/dependency support, will see as needed
+ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
+{
+ ImGuiContext& g = *ctx;
+ IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
+ g.Hooks.push_back(*hook);
+ g.Hooks.back().HookId = ++g.HookIdNext;
+ return g.HookIdNext;
+}
+
+// Deferred removal, avoiding issue with changing vector while iterating it
+void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
+{
+ ImGuiContext& g = *ctx;
+ IM_ASSERT(hook_id != 0);
+ for (int n = 0; n < g.Hooks.Size; n++)
+ if (g.Hooks[n].HookId == hook_id)
+ g.Hooks[n].Type = ImGuiContextHookType_PendingRemoval_;
+}
+
+// Call context hooks (used by e.g. test engine)
+// We assume a small number of hooks so all stored in same array
+void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
+{
+ ImGuiContext& g = *ctx;
+ for (int n = 0; n < g.Hooks.Size; n++)
+ if (g.Hooks[n].Type == hook_type)
+ g.Hooks[n].Callback(&g, &g.Hooks[n]);
+}
+
ImGuiIO& ImGui::GetIO()
{
IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
return GImGui->IO;
}
-ImGuiPlatformIO& ImGui::GetPlatformIO()
-{
- IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
- return GImGui->PlatformIO;
-}
-
-ImGuiStyle& ImGui::GetStyle()
-{
- IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
- return GImGui->Style;
-}
-
-// Same value as passed to the old io.RenderDrawListsFn function. Valid after Render() and until the next call to NewFrame()
+// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
ImDrawData* ImGui::GetDrawData()
{
ImGuiContext& g = *GImGui;
- return g.Viewports[0]->DrawDataP.Valid ? &g.Viewports[0]->DrawDataP : NULL;
+ return g.DrawData.Valid ? &g.DrawData : NULL;
}
double ImGui::GetTime()
@@ -3205,50 +3401,14 @@ int ImGui::GetFrameCount()
return GImGui->FrameCount;
}
-static ImDrawList* GetViewportDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
-{
- // Create the draw list on demand, because they are not frequently used for all viewports
- ImGuiContext& g = *GImGui;
- IM_ASSERT(drawlist_no >= 0 && drawlist_no < IM_ARRAYSIZE(viewport->DrawLists));
- ImDrawList* draw_list = viewport->DrawLists[drawlist_no];
- if (draw_list == NULL)
- {
- draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
- draw_list->_OwnerName = drawlist_name;
- viewport->DrawLists[drawlist_no] = draw_list;
- }
-
- // Our ImDrawList system requires that there is always a command
- if (viewport->LastFrameDrawLists[drawlist_no] != g.FrameCount)
- {
- draw_list->Clear();
- draw_list->PushTextureID(g.IO.Fonts->TexID);
- draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
- viewport->LastFrameDrawLists[drawlist_no] = g.FrameCount;
- }
- return draw_list;
-}
-
-ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
-{
- return GetViewportDrawList((ImGuiViewportP*)viewport, 0, "##Background");
-}
-
ImDrawList* ImGui::GetBackgroundDrawList()
{
- ImGuiWindow* window = GImGui->CurrentWindow;
- return GetBackgroundDrawList(window->Viewport);
-}
-
-ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
-{
- return GetViewportDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
+ return &GImGui->BackgroundDrawList;
}
ImDrawList* ImGui::GetForegroundDrawList()
{
- ImGuiWindow* window = GImGui->CurrentWindow;
- return GetForegroundDrawList(window->Viewport);
+ return &GImGui->ForegroundDrawList;
}
ImDrawListSharedData* ImGui::GetDrawListSharedData()
@@ -3265,46 +3425,21 @@ void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
FocusWindow(window);
SetActiveID(window->MoveId, window);
g.NavDisableHighlight = true;
+ g.ActiveIdNoClearOnFocusLoss = true;
g.ActiveIdClickOffset = g.IO.MousePos - window->RootWindow->Pos;
bool can_move_window = true;
if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindow->Flags & ImGuiWindowFlags_NoMove))
can_move_window = false;
- if (ImGuiDockNode* node = window->DockNodeAsHost)
- if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
- can_move_window = false;
if (can_move_window)
g.MovingWindow = window;
}
-void ImGui::StartMouseDragFromTitleBar(ImGuiWindow* window, ImGuiDockNode* node, bool from_collapse_button)
-{
- ImGuiContext& g = *GImGui;
- bool can_extract_dock_node = false;
- if (node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0)
- {
- ImGuiDockNode* root_node = DockNodeGetRootNode(node);
- if (root_node->OnlyNodeWithWindows != node || (root_node->CentralNode != NULL))
- if (from_collapse_button || root_node->IsDockSpace())
- can_extract_dock_node = true;
- }
-
- const bool clicked = IsMouseClicked(0);
- const bool dragging = IsMouseDragging(0, g.IO.MouseDragThreshold * 1.70f);
- if (can_extract_dock_node && dragging)
- {
- DockContextQueueUndockNode(&g, node);
- g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos;
- }
- else if (!can_extract_dock_node && (clicked || dragging) && g.MovingWindow != window)
- {
- StartMouseMovingWindow(window);
- g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindow->Pos;
- }
-}
-
// Handle mouse moving window
// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
+// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
+// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
+// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
void ImGui::UpdateMouseMovingWindowNewFrame()
{
ImGuiContext& g = *GImGui;
@@ -3322,25 +3457,11 @@ void ImGui::UpdateMouseMovingWindowNewFrame()
{
MarkIniSettingsDirty(moving_window);
SetWindowPos(moving_window, pos, ImGuiCond_Always);
- if (moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
- moving_window->Viewport->Pos = pos;
}
FocusWindow(g.MovingWindow);
}
else
{
- // Try to merge the window back into the main viewport.
- // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
- if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
- UpdateTryMergeWindowIntoHostViewport(moving_window, g.MouseViewport);
-
- // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
- if (!IsDragDropPayloadBeingAccepted())
- g.MouseViewport = moving_window->Viewport;
-
- // Clear the NoInput window flag set by the Viewport system
- moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs;
-
ClearActiveID();
g.MovingWindow = NULL;
}
@@ -3357,10 +3478,10 @@ void ImGui::UpdateMouseMovingWindowNewFrame()
}
}
-// Initiate moving window, handle left-click and right-click focus
+// Initiate moving window when clicking on empty space or title bar.
+// Handle left-click and right-click focus.
void ImGui::UpdateMouseMovingWindowEndFrame()
{
- // Initiate moving window
ImGuiContext& g = *GImGui;
if (g.ActiveId != 0 || g.HoveredId != 0)
return;
@@ -3369,17 +3490,28 @@ void ImGui::UpdateMouseMovingWindowEndFrame()
if (g.NavWindow && g.NavWindow->Appearing)
return;
- // Click to focus window and start moving (after we're done with all our widgets)
+ // Click on empty space to focus window and start moving (after we're done with all our widgets)
if (g.IO.MouseClicked[0])
{
- if (g.HoveredRootWindow != NULL)
+ // Handle the edge case of a popup being closed while clicking in its empty space.
+ // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
+ ImGuiWindow* root_window = g.HoveredRootWindow;
+ const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
+
+ if (root_window != NULL && !is_closed_popup)
{
- StartMouseMovingWindow(g.HoveredWindow);
- if (g.IO.ConfigWindowsMoveFromTitleBarOnly && (!(g.HoveredRootWindow->Flags & ImGuiWindowFlags_NoTitleBar) || g.HoveredWindow->RootWindowDockStop->DockIsActive))
- if (!g.HoveredRootWindow->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
+ StartMouseMovingWindow(g.HoveredWindow); //-V595
+
+ // Cancel moving if clicked outside of title bar
+ if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(root_window->Flags & ImGuiWindowFlags_NoTitleBar))
+ if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
g.MovingWindow = NULL;
+
+ // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
+ if (g.HoveredIdDisabled)
+ g.MovingWindow = NULL;
}
- else if (g.NavWindow != NULL && GetTopMostPopupModal() == NULL)
+ else if (root_window == NULL && g.NavWindow != NULL && GetTopMostPopupModal() == NULL)
{
// Clicking on void disable focus
FocusWindow(NULL);
@@ -3394,43 +3526,11 @@ void ImGui::UpdateMouseMovingWindowEndFrame()
// Find the top-most window between HoveredWindow and the top-most Modal Window.
// This is where we can trim the popup stack.
ImGuiWindow* modal = GetTopMostPopupModal();
- bool hovered_window_above_modal = false;
- if (modal == NULL)
- hovered_window_above_modal = true;
- for (int i = g.Windows.Size - 1; i >= 0 && hovered_window_above_modal == false; i--)
- {
- ImGuiWindow* window = g.Windows[i];
- if (window == modal)
- break;
- if (window == g.HoveredWindow)
- hovered_window_above_modal = true;
- }
+ bool hovered_window_above_modal = g.HoveredWindow && IsWindowAbove(g.HoveredWindow, modal);
ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
}
}
-static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
-{
- window->Pos += delta;
- window->ClipRect.Translate(delta);
- window->OuterRectClipped.Translate(delta);
- window->InnerRect.Translate(delta);
- window->DC.CursorPos += delta;
- window->DC.CursorStartPos += delta;
- window->DC.CursorMaxPos += delta;
- window->DC.LastItemRect.Translate(delta);
- window->DC.LastItemDisplayRect.Translate(delta);
-}
-
-static void ScaleWindow(ImGuiWindow* window, float scale)
-{
- ImVec2 origin = window->Viewport->Pos;
- window->Pos = ImFloor((window->Pos - origin) * scale + origin);
- window->Size = ImFloor(window->Size * scale);
- window->SizeFull = ImFloor(window->SizeFull * scale);
- window->ContentSize = ImFloor(window->ContentSize * scale);
-}
-
static bool IsWindowActiveAndVisible(ImGuiWindow* window)
{
return (window->Active) && (!window->Hidden);
@@ -3467,7 +3567,7 @@ static void ImGui::UpdateMouseInputs()
ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
if (ImLengthSqr(delta_from_click_pos) < g.IO.MouseDoubleClickMaxDist * g.IO.MouseDoubleClickMaxDist)
g.IO.MouseDoubleClicked[i] = true;
- g.IO.MouseClickedTime[i] = -FLT_MAX; // so the third click isn't turned into a double-click
+ g.IO.MouseClickedTime[i] = -g.IO.MouseDoubleClickTime * 2.0f; // Mark as "old enough" so the third click isn't turned into a double-click
}
else
{
@@ -3523,6 +3623,9 @@ void ImGui::UpdateMouseWheel()
if (g.IO.MouseWheel == 0.0f && g.IO.MouseWheelH == 0.0f)
return;
+ if ((g.ActiveId != 0 && g.ActiveIdUsingMouseWheel) || (g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrameUsingMouseWheel))
+ return;
+
ImGuiWindow* window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
if (!window || window->Collapsed)
return;
@@ -3579,6 +3682,42 @@ void ImGui::UpdateMouseWheel()
}
}
+void ImGui::UpdateTabFocus()
+{
+ ImGuiContext& g = *GImGui;
+
+ // Pressing TAB activate widget focus
+ g.FocusTabPressed = (g.NavWindow && g.NavWindow->Active && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab));
+ if (g.ActiveId == 0 && g.FocusTabPressed)
+ {
+ // Note that SetKeyboardFocusHere() sets the Next fields mid-frame. To be consistent we also
+ // manipulate the Next fields even, even though they will be turned into Curr fields by the code below.
+ g.FocusRequestNextWindow = g.NavWindow;
+ g.FocusRequestNextCounterRegular = INT_MAX;
+ if (g.NavId != 0 && g.NavIdTabCounter != INT_MAX)
+ g.FocusRequestNextCounterTabStop = g.NavIdTabCounter + 1 + (g.IO.KeyShift ? -1 : 1);
+ else
+ g.FocusRequestNextCounterTabStop = g.IO.KeyShift ? -1 : 0;
+ }
+
+ // Turn queued focus request into current one
+ g.FocusRequestCurrWindow = NULL;
+ g.FocusRequestCurrCounterRegular = g.FocusRequestCurrCounterTabStop = INT_MAX;
+ if (g.FocusRequestNextWindow != NULL)
+ {
+ ImGuiWindow* window = g.FocusRequestNextWindow;
+ g.FocusRequestCurrWindow = window;
+ if (g.FocusRequestNextCounterRegular != INT_MAX && window->DC.FocusCounterRegular != -1)
+ g.FocusRequestCurrCounterRegular = ImModPositive(g.FocusRequestNextCounterRegular, window->DC.FocusCounterRegular + 1);
+ if (g.FocusRequestNextCounterTabStop != INT_MAX && window->DC.FocusCounterTabStop != -1)
+ g.FocusRequestCurrCounterTabStop = ImModPositive(g.FocusRequestNextCounterTabStop, window->DC.FocusCounterTabStop + 1);
+ g.FocusRequestNextWindow = NULL;
+ g.FocusRequestNextCounterRegular = g.FocusRequestNextCounterTabStop = INT_MAX;
+ }
+
+ g.NavIdTabCounter = INT_MAX;
+}
+
// 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::UpdateHoveredWindowAndCaptureFlags()
{
@@ -3588,18 +3727,17 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags()
// - 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 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.
+ bool clear_hovered_windows = false;
FindHoveredWindow();
- IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
- // Modal windows prevents cursor from hovering behind them.
+ // Modal windows prevents mouse from hovering behind them.
ImGuiWindow* modal_window = GetTopMostPopupModal();
- if (modal_window)
- if (g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, modal_window))
- g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL;
+ if (modal_window && g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, modal_window))
+ clear_hovered_windows = true;
// Disabled mouse?
if (g.IO.ConfigFlags & ImGuiConfigFlags_NoMouse)
- g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL;
+ clear_hovered_windows = true;
// 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;
@@ -3607,7 +3745,7 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags()
for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
{
if (g.IO.MouseClicked[i])
- g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (!g.OpenPopupStack.empty());
+ g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (g.OpenPopupStack.Size > 0);
mouse_any_down |= g.IO.MouseDown[i];
if (g.IO.MouseDown[i])
if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[i] < g.IO.MouseClickedTime[mouse_earliest_button_down])
@@ -3619,13 +3757,16 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags()
// 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)
+ clear_hovered_windows = true;
+
+ if (clear_hovered_windows)
g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL;
// Update io.WantCaptureMouse for the user application (true = dispatch mouse info to imgui, false = dispatch mouse info to Dear ImGui + app)
if (g.WantCaptureMouseNextFrame != -1)
g.IO.WantCaptureMouse = (g.WantCaptureMouseNextFrame != 0);
else
- g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (!g.OpenPopupStack.empty());
+ g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (g.OpenPopupStack.Size > 0);
// Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to imgui, false = dispatch keyboard info to Dear ImGui + app)
if (g.WantCaptureKeyboardNextFrame != -1)
@@ -3639,153 +3780,82 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags()
g.IO.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
}
-static void NewFrameSanityChecks()
+ImGuiKeyModFlags ImGui::GetMergedKeyModFlags()
{
ImGuiContext& g = *GImGui;
-
- // Check user data
- // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
- IM_ASSERT(g.Initialized);
- IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!");
- IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
- IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!");
- IM_ASSERT(g.IO.Fonts->Fonts.Size > 0 && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
- IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded() && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
- IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!");
- IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting. Alpha cannot be negative (allows us to avoid a few clamps in color computations)!");
- IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
- IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
- for (int n = 0; n < ImGuiKey_COUNT; n++)
- IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < IM_ARRAYSIZE(g.IO.KeysDown) && "io.KeyMap[] contains an out of bound value (need to be 0..512, or -1 for unmapped key)");
-
- // Perform simple check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only 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.");
-
- // Perform simple check: the beta io.ConfigWindowsResizeFromEdges option requires back-end to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
- if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
- g.IO.ConfigWindowsResizeFromEdges = false;
+ ImGuiKeyModFlags key_mod_flags = ImGuiKeyModFlags_None;
+ if (g.IO.KeyCtrl) { key_mod_flags |= ImGuiKeyModFlags_Ctrl; }
+ if (g.IO.KeyShift) { key_mod_flags |= ImGuiKeyModFlags_Shift; }
+ if (g.IO.KeyAlt) { key_mod_flags |= ImGuiKeyModFlags_Alt; }
+ if (g.IO.KeySuper) { key_mod_flags |= ImGuiKeyModFlags_Super; }
+ return key_mod_flags;
}
void ImGui::NewFrame()
{
IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
ImGuiContext& g = *GImGui;
+
+ // Remove pending delete hooks before frame start.
+ // This deferred removal avoid issues of removal while iterating the hook vector
+ for (int n = g.Hooks.Size - 1; n >= 0; n--)
+ if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
+ g.Hooks.erase(&g.Hooks[n]);
-#ifdef IMGUI_ENABLE_TEST_ENGINE
- ImGuiTestEngineHook_PreNewFrame(&g);
-#endif
+ CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
// Check and assert for various common IO and Configuration mistakes
- NewFrameSanityChecks();
+ ErrorCheckNewFrameSanityChecks();
- // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data.
- g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame;
- if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0)
- IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
- if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0)
- IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
-
- // Perform simple checks: multi-viewport and platform windows support
- if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
- {
- if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports))
- {
- IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference.");
- IM_ASSERT(g.PlatformIO.Platform_CreateWindow != NULL && "Platform init didn't install handlers?");
- IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
- IM_ASSERT(g.PlatformIO.Platform_GetWindowPos != NULL && "Platform init didn't install handlers?");
- IM_ASSERT(g.PlatformIO.Platform_SetWindowPos != NULL && "Platform init didn't install handlers?");
- IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?");
- IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?");
- IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?");
- IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport.");
- if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
- IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!");
-#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
- IM_ASSERT(g.IO.RenderDrawListsFn == NULL); // Call ImGui::Render() then pass ImGui::GetDrawData() yourself to your render function!
-#endif
- }
- else
- {
- // Disable feature, our back-ends do not support it
- g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
- }
-
- // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs
- for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
- {
- ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[monitor_n];
- IM_UNUSED(mon);
- IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor bounds not setup properly.");
- IM_ASSERT(mon.WorkSize.x > 0.0f && mon.WorkSize.y > 0.0f && "Monitor bounds not setup properly. If you don't have work area information, just copy Min/Max into them.");
- IM_ASSERT(mon.DpiScale != 0.0f);
- }
- }
- g.ConfigFlagsCurrFrame = g.IO.ConfigFlags;
-
- // Load settings on first frame (if not explicitly loaded manually before)
- if (!g.SettingsLoaded)
- {
- IM_ASSERT(g.SettingsWindows.empty());
- if (g.IO.IniFilename)
- LoadIniSettingsFromDisk(g.IO.IniFilename);
- g.SettingsLoaded = true;
- }
-
- // Save settings (with a delay after the last modification, so we don't spam disk too much)
- if (g.SettingsDirtyTimer > 0.0f)
- {
- g.SettingsDirtyTimer -= g.IO.DeltaTime;
- if (g.SettingsDirtyTimer <= 0.0f)
- {
- if (g.IO.IniFilename != NULL)
- SaveIniSettingsToDisk(g.IO.IniFilename);
- else
- g.IO.WantSaveIniSettings = true; // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
- g.SettingsDirtyTimer = 0.0f;
- }
- }
+ // Load settings on first frame, save settings when modified (after a delay)
+ UpdateSettings();
g.Time += g.IO.DeltaTime;
- g.FrameScopeActive = true;
+ g.WithinFrameScope = true;
g.FrameCount += 1;
g.TooltipOverrideCount = 0;
g.WindowsActiveCount = 0;
+ g.MenusIdSubmittedThisFrame.resize(0);
- UpdateViewportsNewFrame();
+ // 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 = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame))) : FLT_MAX;
// Setup current font and draw list shared data
- // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
g.IO.Fonts->Locked = true;
SetCurrentFont(GetDefaultFont());
IM_ASSERT(g.Font->IsLoaded());
- ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
- for (int n = 0; n < g.Viewports.Size; n++)
- virtual_space.Add(g.Viewports[n]->GetRect());
- g.DrawListSharedData.ClipRectFullscreen = ImVec4(virtual_space.Min.x, virtual_space.Min.y, virtual_space.Max.x, virtual_space.Max.y);
+ g.DrawListSharedData.ClipRectFullscreen = ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y);
g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
+ g.DrawListSharedData.SetCircleSegmentMaxError(g.Style.CircleSegmentMaxError);
g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
if (g.Style.AntiAliasedLines)
g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
+ if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines))
+ g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
if (g.Style.AntiAliasedFill)
g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
+ g.BackgroundDrawList._ResetForNewFrame();
+ g.BackgroundDrawList.PushTextureID(g.IO.Fonts->TexID);
+ g.BackgroundDrawList.PushClipRectFullScreen();
+
+ g.ForegroundDrawList._ResetForNewFrame();
+ g.ForegroundDrawList.PushTextureID(g.IO.Fonts->TexID);
+ g.ForegroundDrawList.PushClipRectFullScreen();
+
// Mark rendering data as invalid to prevent user who may have a handle on it to use it.
- for (int n = 0; n < g.Viewports.Size; n++)
- {
- ImGuiViewportP* viewport = g.Viewports[n];
- viewport->DrawData = NULL;
- viewport->DrawDataP.Clear();
- }
+ g.DrawData.Clear();
// Drag and drop keep the source ID alive so even if the source disappear our state is consistent
if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
KeepAliveID(g.DragDropPayload.SourceId);
- // Clear reference to active widget if the widget isn't alive anymore
+ // Update HoveredId data
if (!g.HoveredIdPreviousFrame)
g.HoveredIdTimer = 0.0f;
if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
@@ -3795,8 +3865,13 @@ void ImGui::NewFrame()
if (g.HoveredId && g.ActiveId != g.HoveredId)
g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
g.HoveredIdPreviousFrame = g.HoveredId;
+ g.HoveredIdPreviousFrameUsingMouseWheel = g.HoveredIdUsingMouseWheel;
g.HoveredId = 0;
g.HoveredIdAllowOverlap = false;
+ g.HoveredIdUsingMouseWheel = false;
+ g.HoveredIdDisabled = false;
+
+ // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
if (g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0)
ClearActiveID();
if (g.ActiveId)
@@ -3809,41 +3884,36 @@ void ImGui::NewFrame()
g.ActiveIdHasBeenEditedThisFrame = false;
g.ActiveIdPreviousFrameIsAlive = false;
g.ActiveIdIsJustActivated = false;
- if (g.TempInputTextId != 0 && g.ActiveId != g.TempInputTextId)
- g.TempInputTextId = 0;
+ if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
+ g.TempInputId = 0;
if (g.ActiveId == 0)
{
- g.ActiveIdUsingNavDirMask = g.ActiveIdUsingNavInputMask = 0;
- g.ActiveIdUsingKeyInputMask = 0;
+ g.ActiveIdUsingNavDirMask = 0x00;
+ g.ActiveIdUsingNavInputMask = 0x00;
+ g.ActiveIdUsingKeyInputMask = 0x00;
}
// Drag and drop
g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
g.DragDropAcceptIdCurr = 0;
g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
- g.DragDropWithinSourceOrTarget = false;
+ g.DragDropWithinSource = false;
+ g.DragDropWithinTarget = false;
+ g.DragDropHoldJustPressedId = 0;
// Update keyboard input state
+ // Synchronize io.KeyMods with individual modifiers io.KeyXXX bools
+ g.IO.KeyMods = GetMergedKeyModFlags();
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
+ // Update gamepad/keyboard navigation
NavUpdate();
// Update mouse input state
UpdateMouseInputs();
- // 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 = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame))) : FLT_MAX;
-
- // Undocking
- // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
- DockContextUpdateUndocking(&g);
-
// Find hovered window
// (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
UpdateHoveredWindowAndCaptureFlags();
@@ -3860,45 +3930,16 @@ void ImGui::NewFrame()
g.MouseCursor = ImGuiMouseCursor_Arrow;
g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
g.PlatformImePos = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default
- g.PlatformImePosViewport = NULL;
// Mouse wheel scrolling, scale
UpdateMouseWheel();
- // Pressing TAB activate widget focus
- g.FocusTabPressed = (g.NavWindow && g.NavWindow->Active && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab));
- if (g.ActiveId == 0 && g.FocusTabPressed)
- {
- // Note that SetKeyboardFocusHere() sets the Next fields mid-frame. To be consistent we also
- // manipulate the Next fields even, even though they will be turned into Curr fields by the code below.
- g.FocusRequestNextWindow = g.NavWindow;
- g.FocusRequestNextCounterAll = INT_MAX;
- if (g.NavId != 0 && g.NavIdTabCounter != INT_MAX)
- g.FocusRequestNextCounterTab = g.NavIdTabCounter + 1 + (g.IO.KeyShift ? -1 : 1);
- else
- g.FocusRequestNextCounterTab = g.IO.KeyShift ? -1 : 0;
- }
-
- // Turn queued focus request into current one
- g.FocusRequestCurrWindow = NULL;
- g.FocusRequestCurrCounterAll = g.FocusRequestCurrCounterTab = INT_MAX;
- if (g.FocusRequestNextWindow != NULL)
- {
- ImGuiWindow* window = g.FocusRequestNextWindow;
- g.FocusRequestCurrWindow = window;
- if (g.FocusRequestNextCounterAll != INT_MAX && window->DC.FocusCounterAll != -1)
- g.FocusRequestCurrCounterAll = ImModPositive(g.FocusRequestNextCounterAll, window->DC.FocusCounterAll + 1);
- if (g.FocusRequestNextCounterTab != INT_MAX && window->DC.FocusCounterTab != -1)
- g.FocusRequestCurrCounterTab = ImModPositive(g.FocusRequestNextCounterTab, window->DC.FocusCounterTab + 1);
- g.FocusRequestNextWindow = NULL;
- g.FocusRequestNextCounterAll = g.FocusRequestNextCounterTab = INT_MAX;
- }
-
- g.NavIdTabCounter = INT_MAX;
+ // Update legacy TAB focus
+ UpdateTabFocus();
// Mark all windows as not visible and compact unused memory.
IM_ASSERT(g.WindowsFocusOrder.Size == g.Windows.Size);
- const float memory_compact_start_time = (g.IO.ConfigWindowsMemoryCompactTimer >= 0.0f) ? (float)g.Time - g.IO.ConfigWindowsMemoryCompactTimer : FLT_MAX;
+ const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
@@ -3907,11 +3948,19 @@ void ImGui::NewFrame()
window->Active = false;
window->WriteAccessed = false;
- // Garbage collect (this is totally functional but we may need decide if the side-effects are desirable)
+ // Garbage collect transient buffers of recently unused windows
if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
GcCompactTransientWindowBuffers(window);
}
+ // Garbage collect transient buffers of recently unused tables
+ for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
+ if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
+ TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
+ if (g.GcCompactAll)
+ GcCompactTransientMiscBuffers();
+ g.GcCompactAll = false;
+
// Closing the focused window restore focus to the first active root window in descending z-order
if (g.NavWindow && !g.NavWindow->WasActive)
FocusTopMostWindowUnderOne(NULL, NULL);
@@ -3920,32 +3969,30 @@ void ImGui::NewFrame()
// 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.BeginPopupStack.resize(0);
+ g.ItemFlagsStack.resize(0);
+ g.ItemFlagsStack.push_back(ImGuiItemFlags_Default_);
+ g.GroupStack.resize(0);
ClosePopupsOverWindow(g.NavWindow, false);
- // Docking
- DockContextUpdateDocking(&g);
-
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
UpdateDebugToolItemPicker();
// Create implicit/fallback window - which we will only render it if the user has added something to it.
// We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
// This fallback is particularly important as it avoid ImGui:: calls from crashing.
- g.FrameScopePushedFallbackWindow = true;
- SetNextWindowSize(ImVec2(400,400), ImGuiCond_FirstUseEver);
+ g.WithinFrameScopeWithImplicitWindow = true;
+ SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
Begin("Debug##Default");
IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
-#ifdef IMGUI_ENABLE_TEST_ENGINE
- ImGuiTestEngineHook_PostNewFrame(&g);
-#endif
+ CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
}
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
void ImGui::UpdateDebugToolItemPicker()
{
ImGuiContext& g = *GImGui;
- g.DebugItemPickerBreakID = 0;
+ g.DebugItemPickerBreakId = 0;
if (g.DebugItemPickerActive)
{
const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
@@ -3954,7 +4001,7 @@ void ImGui::UpdateDebugToolItemPicker()
g.DebugItemPickerActive = false;
if (ImGui::IsMouseClicked(0) && hovered_id)
{
- g.DebugItemPickerBreakID = hovered_id;
+ g.DebugItemPickerBreakId = hovered_id;
g.DebugItemPickerActive = false;
}
ImGui::SetNextWindowBgAlpha(0.60f);
@@ -3972,26 +4019,25 @@ void ImGui::Initialize(ImGuiContext* context)
IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
// Add .ini handle for ImGuiWindow type
- ImGuiSettingsHandler ini_handler;
- ini_handler.TypeName = "Window";
- ini_handler.TypeHash = ImHashStr("Window");
- ini_handler.ReadOpenFn = SettingsHandlerWindow_ReadOpen;
- ini_handler.ReadLineFn = SettingsHandlerWindow_ReadLine;
- ini_handler.WriteAllFn = SettingsHandlerWindow_WriteAll;
- g.SettingsHandlers.push_back(ini_handler);
+ {
+ ImGuiSettingsHandler ini_handler;
+ ini_handler.TypeName = "Window";
+ ini_handler.TypeHash = ImHashStr("Window");
+ ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
+ ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
+ ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
+ ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
+ ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
+ g.SettingsHandlers.push_back(ini_handler);
+ }
- // Create default viewport
- ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
- viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
- viewport->Idx = 0;
- viewport->PlatformWindowCreated = true;
- g.Viewports.push_back(viewport);
- g.PlatformIO.MainViewport = g.Viewports[0]; // Make it accessible in public-facing GetPlatformIO() immediately (before the first call to EndFrame)
- g.PlatformIO.Viewports.push_back(g.Viewports[0]);
+#ifdef IMGUI_HAS_TABLE
+ // Add .ini handle for ImGuiTable type
+ TableSettingsInstallHandler(context);
+#endif // #ifdef IMGUI_HAS_TABLE
- // Extensions
- IM_ASSERT(g.DockContext == NULL);
- DockContextInitialize(&g);
+#ifdef IMGUI_HAS_DOCK
+#endif // #ifdef IMGUI_HAS_DOCK
g.Initialized = true;
}
@@ -4016,27 +4062,19 @@ void ImGui::Shutdown(ImGuiContext* context)
if (g.SettingsLoaded && g.IO.IniFilename != NULL)
{
ImGuiContext* backup_context = GImGui;
- SetCurrentContext(context);
+ SetCurrentContext(&g);
SaveIniSettingsToDisk(g.IO.IniFilename);
SetCurrentContext(backup_context);
}
- // Destroy platform windows
- ImGuiContext* backup_context = ImGui::GetCurrentContext();
- SetCurrentContext(context);
- DestroyPlatformWindows();
- SetCurrentContext(backup_context);
-
- // Shutdown extensions
- IM_ASSERT(g.DockContext != NULL);
- DockContextShutdown(&g);
+ CallContextHooks(&g, ImGuiContextHookType_Shutdown);
// Clear everything else
for (int i = 0; i < g.Windows.Size; i++)
IM_DELETE(g.Windows[i]);
g.Windows.clear();
g.WindowsFocusOrder.clear();
- g.WindowsSortBuffer.clear();
+ g.WindowsTempSortBuffer.clear();
g.CurrentWindow = NULL;
g.CurrentWindowStack.clear();
g.WindowsById.Clear();
@@ -4044,32 +4082,36 @@ void ImGui::Shutdown(ImGuiContext* context)
g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL;
g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
g.MovingWindow = NULL;
- g.ColorModifiers.clear();
- g.StyleModifiers.clear();
+ g.ColorStack.clear();
+ g.StyleVarStack.clear();
g.FontStack.clear();
g.OpenPopupStack.clear();
g.BeginPopupStack.clear();
-
- g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
- for (int i = 0; i < g.Viewports.Size; i++)
- IM_DELETE(g.Viewports[i]);
- g.Viewports.clear();
+ g.DrawDataBuilder.ClearFreeMemory();
+ g.BackgroundDrawList._ClearFreeMemory();
+ g.ForegroundDrawList._ClearFreeMemory();
g.TabBars.Clear();
g.CurrentTabBarStack.clear();
g.ShrinkWidthBuffer.clear();
- g.PrivateClipboard.clear();
+ g.Tables.Clear();
+ g.CurrentTableStack.clear();
+ g.DrawChannelsTempMergeBuffer.clear();
+
+ g.ClipboardHandlerData.clear();
+ g.MenusIdSubmittedThisFrame.clear();
g.InputTextState.ClearFreeMemory();
- for (int i = 0; i < g.SettingsWindows.Size; i++)
- IM_DELETE(g.SettingsWindows[i].Name);
g.SettingsWindows.clear();
g.SettingsHandlers.clear();
- if (g.LogFile && g.LogFile != stdout)
+ if (g.LogFile)
{
- fclose(g.LogFile);
+#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
+ if (g.LogFile != stdout)
+#endif
+ ImFileClose(g.LogFile);
g.LogFile = NULL;
}
g.LogBuffer.clear();
@@ -4108,18 +4150,12 @@ static void AddWindowToSortBuffer(ImVector* out_sorted_windows, Im
static void AddDrawListToDrawData(ImVector* out_list, ImDrawList* draw_list)
{
- if (draw_list->CmdBuffer.empty())
+ // Remove trailing command if unused.
+ // Technically we could return directly instead of popping, but this make things looks neat in Metrics/Debugger window as well.
+ draw_list->_PopUnusedDrawCmd();
+ if (draw_list->CmdBuffer.Size == 0)
return;
- // Remove trailing command if unused
- ImDrawCmd& last_cmd = draw_list->CmdBuffer.back();
- if (last_cmd.ElemCount == 0 && last_cmd.UserCallback == NULL)
- {
- draw_list->CmdBuffer.pop_back();
- if (draw_list->CmdBuffer.empty())
- return;
- }
-
// Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc.
// May trigger for you if you are using PrimXXX functions incorrectly.
IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
@@ -4130,13 +4166,13 @@ static void AddDrawListToDrawData(ImVector* out_list, ImDrawList* d
// 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:
// - First, make sure you are coarse clipping yourself and not trying to draw many things outside visible bounds.
- // Be mindful that the ImDrawList API doesn't filter vertices. Use the Metrics window to inspect draw list contents.
+ // Be mindful that the ImDrawList API doesn't filter vertices. Use the Metrics/Debugger window to inspect draw list contents.
// - If you want large meshes with more than 64K vertices, you can either:
- // (A) Handle the ImDrawCmd::VtxOffset value in your renderer back-end, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'.
- // Most example back-ends already support this from 1.71. Pre-1.71 back-ends won't.
+ // (A) Handle the ImDrawCmd::VtxOffset value in your renderer backend, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'.
+ // Most example backends already support this from 1.71. Pre-1.71 backends won't.
// Some graphics API such as GL ES 1/2 don't have a way to offset the starting vertex so it is not supported for them.
- // (B) Or handle 32-bits indices in your renderer back-end, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h.
- // Most example back-ends already support this. For example, the OpenGL example code detect index size at compile-time:
+ // (B) Or handle 32-bit indices in your renderer backend, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h.
+ // Most example backends already support this. For example, the OpenGL example code detect index size at compile-time:
// glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
// Your own engine or render API may use different parameters or function calls to specify index sizes.
// 2 and 4 bytes indices are generally supported by most graphics API.
@@ -4148,24 +4184,25 @@ static void AddDrawListToDrawData(ImVector* out_list, ImDrawList* d
out_list->push_back(draw_list);
}
-static void AddWindowToDrawData(ImGuiWindow* window, int layer)
+static void AddWindowToDrawData(ImVector* out_render_list, ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
g.IO.MetricsRenderWindows++;
- AddDrawListToDrawData(&window->Viewport->DrawDataBuilder.Layers[layer], 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 (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
- AddWindowToDrawData(child, layer);
+ if (IsWindowActiveAndVisible(child)) // clipped children may have been marked not active
+ AddWindowToDrawData(out_render_list, child);
}
}
// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
static void AddRootWindowToDrawData(ImGuiWindow* window)
{
+ ImGuiContext& g = *GImGui;
int layer = (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
- AddWindowToDrawData(window, layer);
+ AddWindowToDrawData(&g.DrawDataBuilder.Layers[layer], window);
}
void ImDrawDataBuilder::FlattenIntoSingleLayer()
@@ -4186,18 +4223,16 @@ void ImDrawDataBuilder::FlattenIntoSingleLayer()
}
}
-static void SetupViewportDrawData(ImGuiViewportP* viewport, ImVector* draw_lists)
+static void SetupDrawData(ImVector* draw_lists, ImDrawData* draw_data)
{
- ImDrawData* draw_data = &viewport->DrawDataP;
- viewport->DrawData = draw_data; // Make publicly accessible
+ ImGuiIO& io = ImGui::GetIO();
draw_data->Valid = true;
draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL;
draw_data->CmdListsCount = draw_lists->Size;
draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
- draw_data->DisplayPos = viewport->Pos;
- draw_data->DisplaySize = viewport->Size;
- draw_data->FramebufferScale = ImGui::GetIO().DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis?
- draw_data->OwnerViewport = viewport;
+ draw_data->DisplayPos = ImVec2(0.0f, 0.0f);
+ draw_data->DisplaySize = io.DisplaySize;
+ draw_data->FramebufferScale = io.DisplayFramebufferScale;
for (int n = 0; n < draw_lists->Size; n++)
{
draw_data->TotalVtxCount += draw_lists->Data[n]->VtxBuffer.Size;
@@ -4205,7 +4240,12 @@ static void SetupViewportDrawData(ImGuiViewportP* viewport, ImVectorClipRect = window->DrawList->_ClipRectStack.back();
}
-static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
-{
- for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
- if (IsWindowActiveAndVisible(window->DC.ChildWindows[n]))
- return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]);
- return window;
-}
-
-static void ImGui::EndFrameDrawDimmedBackgrounds()
-{
- ImGuiContext& g = *GImGui;
-
- // Draw modal whitening background on _other_ viewports than the one the modal is one
- ImGuiWindow* modal_window = GetTopMostPopupModal();
- const bool dim_bg_for_modal = (modal_window != NULL);
- const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL);
- if (dim_bg_for_modal || dim_bg_for_window_list)
- for (int viewport_n = 0; viewport_n < g.Viewports.Size; viewport_n++)
- {
- ImGuiViewportP* viewport = g.Viewports[viewport_n];
- if (modal_window && viewport == modal_window->Viewport)
- continue;
- if (g.NavWindowingList && viewport == g.NavWindowingList->Viewport)
- continue;
- if (g.NavWindowingTargetAnim && viewport == g.NavWindowingTargetAnim->Viewport)
- continue;
- ImDrawList* draw_list = GetForegroundDrawList(viewport);
- const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
- draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col);
- }
-
- // Draw modal whitening background between CTRL-TAB list
- if (dim_bg_for_window_list)
- {
- // Choose a draw list that will be front-most across all our children
- ImGuiWindow* window = g.NavWindowingTargetAnim;
- ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindow)->DrawList;
- draw_list->PushClipRectFullScreen();
-
- // Docking: draw modal whitening background on other nodes of a same dock tree
- if (window->RootWindowDockStop->DockIsActive)
- if (window->RootWindow != window->RootWindowDockStop)
- RenderRectFilledWithHole(draw_list, window->RootWindow->Rect(), window->RootWindowDockStop->Rect(), GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio), g.Style.WindowRounding);
-
- // Draw navigation selection/windowing rectangle border
- float rounding = ImMax(window->WindowRounding, g.Style.WindowRounding);
- ImRect bb = window->Rect();
- bb.Expand(g.FontSize);
- if (bb.Contains(window->Viewport->GetRect())) // If a window fits the entire viewport, adjust its highlight inward
- {
- bb.Expand(-g.FontSize - 1.0f);
- rounding = window->WindowRounding;
- }
- draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), rounding, ~0, 3.0f);
- draw_list->PopClipRect();
- }
-}
-
// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
void ImGui::EndFrame()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.Initialized);
- if (g.FrameCountEnded == g.FrameCount) // Don't process EndFrame() multiple times.
+
+ // Don't process EndFrame() multiple times.
+ if (g.FrameCountEnded == g.FrameCount)
return;
- IM_ASSERT(g.FrameScopeActive && "Forgot to call ImGui::NewFrame()?");
+ IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
+
+ CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
+
+ ErrorCheckEndFrameSanityChecks();
// Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
- if (g.PlatformIO.Platform_SetImeInputPos && (g.PlatformImeLastPos.x == FLT_MAX || ImLengthSqr(g.PlatformImePos - g.PlatformImeLastPos) > 0.0001f))
- if (g.PlatformImePosViewport && g.PlatformImePosViewport->PlatformWindowCreated)
- {
- g.PlatformIO.Platform_SetImeInputPos(g.PlatformImePosViewport, g.PlatformImePos);
- g.PlatformImeLastPos = g.PlatformImePos;
- g.PlatformImePosViewport = NULL;
- }
-
- // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
- // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
- if (g.CurrentWindowStack.Size != 1)
+ if (g.IO.ImeSetInputScreenPosFn && (g.PlatformImeLastPos.x == FLT_MAX || ImLengthSqr(g.PlatformImeLastPos - g.PlatformImePos) > 0.0001f))
{
- if (g.CurrentWindowStack.Size > 1)
- {
- IM_ASSERT(g.CurrentWindowStack.Size == 1 && "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
- while (g.CurrentWindowStack.Size > 1) // FIXME-ERRORHANDLING
- End();
- }
- else
- {
- IM_ASSERT(g.CurrentWindowStack.Size == 1 && "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
- }
+ g.IO.ImeSetInputScreenPosFn((int)g.PlatformImePos.x, (int)g.PlatformImePos.y);
+ g.PlatformImeLastPos = g.PlatformImePos;
}
// Hide implicit/fallback "Debug" window if it hasn't been used
- g.FrameScopePushedFallbackWindow = false;
+ g.WithinFrameScopeWithImplicitWindow = false;
if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
g.CurrentWindow->Active = false;
End();
- // Draw modal whitening background on _other_ viewports than the one the modal is one
- EndFrameDrawDimmedBackgrounds();
-
- // Show CTRL+TAB list window
- if (g.NavWindowingTarget != NULL)
- NavUpdateWindowingOverlay();
-
- SetCurrentViewport(NULL, NULL);
+ // Update navigation: CTRL+Tab, wrap-around requests
+ NavEndFrame();
// Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
if (g.DragDropActive)
@@ -4337,38 +4301,35 @@ void ImGui::EndFrame()
}
// Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
- if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount)
+ if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
{
- g.DragDropWithinSourceOrTarget = true;
+ g.DragDropWithinSource = true;
SetTooltip("...");
- g.DragDropWithinSourceOrTarget = false;
+ g.DragDropWithinSource = false;
}
// End frame
- g.FrameScopeActive = false;
+ g.WithinFrameScope = false;
g.FrameCountEnded = g.FrameCount;
// Initiate moving window + handle left-click and right-click focus
UpdateMouseMovingWindowEndFrame();
- // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
- UpdateViewportsEndFrame();
-
// Sort the window list so that all child windows are after their parent
- // We cannot do that on FocusWindow() because childs may not exist yet
- g.WindowsSortBuffer.resize(0);
- g.WindowsSortBuffer.reserve(g.Windows.Size);
+ // We cannot do that on FocusWindow() because children may not exist yet
+ g.WindowsTempSortBuffer.resize(0);
+ g.WindowsTempSortBuffer.reserve(g.Windows.Size);
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
continue;
- AddWindowToSortBuffer(&g.WindowsSortBuffer, window);
+ AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
}
// This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
- IM_ASSERT(g.Windows.Size == g.WindowsSortBuffer.Size);
- g.Windows.swap(g.WindowsSortBuffer);
+ IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
+ g.Windows.swap(g.WindowsTempSortBuffer);
g.IO.MetricsActiveWindows = g.WindowsActiveCount;
// Unlock font atlas
@@ -4378,6 +4339,8 @@ void ImGui::EndFrame()
g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
g.IO.InputQueueCharacters.resize(0);
memset(g.IO.NavInputs, 0, sizeof(g.IO.NavInputs));
+
+ CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
}
void ImGui::Render()
@@ -4388,21 +4351,19 @@ void ImGui::Render()
if (g.FrameCountEnded != g.FrameCount)
EndFrame();
g.FrameCountRendered = g.FrameCount;
- g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = g.IO.MetricsRenderWindows = 0;
+ g.IO.MetricsRenderWindows = 0;
+ g.DrawDataBuilder.Clear();
- // Add background ImDrawList (for each active viewport)
- for (int n = 0; n != g.Viewports.Size; n++)
- {
- ImGuiViewportP* viewport = g.Viewports[n];
- viewport->DrawDataBuilder.Clear();
- if (viewport->DrawLists[0] != NULL)
- AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
- }
+ CallContextHooks(&g, ImGuiContextHookType_RenderPre);
- // Add ImDrawList to render (for each active window)
+ // Add background ImDrawList
+ if (!g.BackgroundDrawList.VtxBuffer.empty())
+ AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.BackgroundDrawList);
+
+ // Add ImDrawList to render
ImGuiWindow* windows_to_render_top_most[2];
windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindow : NULL;
- windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingList : NULL);
+ windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
for (int n = 0; n != g.Windows.Size; n++)
{
ImGuiWindow* window = g.Windows[n];
@@ -4410,42 +4371,24 @@ void ImGui::Render()
AddRootWindowToDrawData(window);
}
for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
- if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the tp-most window
+ if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
AddRootWindowToDrawData(windows_to_render_top_most[n]);
+ g.DrawDataBuilder.FlattenIntoSingleLayer();
// Draw software mouse cursor if requested
- ImRect mouse_cursor_rect;
- if (g.IO.MouseDrawCursor && g.MouseCursor != ImGuiMouseCursor_None)
- {
- ImVec2 offset, size, uv[4];
- if (g.IO.Fonts->GetMouseCursorTexData(g.MouseCursor, &offset, &size, &uv[0], &uv[2]))
- mouse_cursor_rect = ImRect(g.IO.MousePos, g.IO.MousePos + ImVec2(size.x + 2, size.y + 2) * g.Style.MouseCursorScale);
- }
+ if (g.IO.MouseDrawCursor)
+ RenderMouseCursor(&g.ForegroundDrawList, g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
- // Setup ImDrawData structures for end-user
- g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
- for (int n = 0; n < g.Viewports.Size; n++)
- {
- ImGuiViewportP* viewport = g.Viewports[n];
- viewport->DrawDataBuilder.FlattenIntoSingleLayer();
+ // Add foreground ImDrawList
+ if (!g.ForegroundDrawList.VtxBuffer.empty())
+ AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.ForegroundDrawList);
- if (viewport->GetRect().Overlaps(mouse_cursor_rect))
- RenderMouseCursor(GetForegroundDrawList(viewport), g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
+ // 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;
- // Add foreground ImDrawList (for each active viewport)
- if (viewport->DrawLists[1] != NULL)
- AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
-
- SetupViewportDrawData(viewport, &viewport->DrawDataBuilder.Layers[0]);
- g.IO.MetricsRenderVertices += viewport->DrawData->TotalVtxCount;
- g.IO.MetricsRenderIndices += viewport->DrawData->TotalIdxCount;
- }
-
- // (Legacy) Call the Render callback function. The current prefer way is to let the user retrieve GetDrawData() and call the render function themselves.
-#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
- if (g.Viewports[0]->DrawData->CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL)
- g.IO.RenderDrawListsFn(g.Viewports[0]->DrawData);
-#endif
+ CallContextHooks(&g, ImGuiContextHookType_RenderPost);
}
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
@@ -4473,18 +4416,13 @@ ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_tex
}
// Find window given position, search front-to-back
-// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programatically
+// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
// called, aka before the next Begin(). Moving window isn't affected.
static void FindHoveredWindow()
{
ImGuiContext& g = *GImGui;
- // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
- ImGuiViewportP* moving_window_viewport = g.MovingWindow ? g.MovingWindow->Viewport : NULL;
- if (g.MovingWindow)
- g.MovingWindow->Viewport = g.MouseViewport;
-
ImGuiWindow* hovered_window = NULL;
ImGuiWindow* hovered_window_ignoring_moving_window = NULL;
if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
@@ -4499,9 +4437,6 @@ static void FindHoveredWindow()
continue;
if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
continue;
- IM_ASSERT(window->Viewport);
- if (window->Viewport != g.MouseViewport)
- continue;
// Using the clipped AABB, a child window will typically be clipped by its parent (not always)
ImRect bb(window->OuterRectClipped);
@@ -4512,12 +4447,13 @@ static void FindHoveredWindow()
if (!bb.Contains(g.IO.MousePos))
continue;
+ // Support for one rectangular hole in any given window
+ // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
if (window->HitTestHoleSize.x != 0)
{
- // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
- ImRect hole_bb((float)(window->HitTestHoleOffset.x), (float)(window->HitTestHoleOffset.y),
- (float)(window->HitTestHoleOffset.x + window->HitTestHoleSize.x), (float)(window->HitTestHoleOffset.y + window->HitTestHoleSize.y));
- if (hole_bb.Contains(g.IO.MousePos - window->Pos))
+ ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
+ ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
+ if (ImRect(hole_pos, hole_pos + hole_size).Contains(g.IO.MousePos))
continue;
}
@@ -4532,9 +4468,6 @@ static void FindHoveredWindow()
g.HoveredWindow = hovered_window;
g.HoveredRootWindow = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window;
-
- if (g.MovingWindow)
- g.MovingWindow->Viewport = moving_window_viewport;
}
// Test if mouse cursor is hovering given rectangle
@@ -4553,8 +4486,6 @@ bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool c
const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
if (!rect_for_touch.Contains(g.IO.MousePos))
return false;
- if (!g.MouseViewport->GetRect().Overlaps(rect_clipped))
- return false;
return true;
}
@@ -4565,7 +4496,8 @@ int ImGui::GetKeyIndex(ImGuiKey imgui_key)
return g.IO.KeyMap[imgui_key];
}
-// Note that imgui doesn't know the semantic of each entry of io.KeysDown[]. Use your own indices/enums according to how your back-end/engine stored them into io.KeysDown[]!
+// Note that dear imgui doesn't know the semantic of each entry of io.KeysDown[]!
+// Use your own indices/enums according to how your backend/engine stored them into io.KeysDown[]!
bool ImGui::IsKeyDown(int user_key_index)
{
if (user_key_index < 0)
@@ -4625,23 +4557,14 @@ bool ImGui::IsKeyReleased(int user_key_index)
return g.IO.KeysDownDurationPrev[user_key_index] >= 0.0f && !g.IO.KeysDown[user_key_index];
}
-bool ImGui::IsMouseDown(int button)
+bool ImGui::IsMouseDown(ImGuiMouseButton button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseDown[button];
}
-bool ImGui::IsAnyMouseDown()
-{
- ImGuiContext& g = *GImGui;
- for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
- if (g.IO.MouseDown[n])
- return true;
- return false;
-}
-
-bool ImGui::IsMouseClicked(int button, bool repeat)
+bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
@@ -4656,26 +4579,26 @@ bool ImGui::IsMouseClicked(int button, bool repeat)
if (amount > 0)
return true;
}
-
return false;
}
-bool ImGui::IsMouseReleased(int button)
+bool ImGui::IsMouseReleased(ImGuiMouseButton button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseReleased[button];
}
-bool ImGui::IsMouseDoubleClicked(int button)
+bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseDoubleClicked[button];
}
+// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
// [Internal] This doesn't test if the button is pressed
-bool ImGui::IsMouseDragPastThreshold(int button, float lock_threshold)
+bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
@@ -4684,7 +4607,7 @@ bool ImGui::IsMouseDragPastThreshold(int button, float lock_threshold)
return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
}
-bool ImGui::IsMouseDragging(int button, float lock_threshold)
+bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
@@ -4695,7 +4618,8 @@ bool ImGui::IsMouseDragging(int button, float lock_threshold)
ImVec2 ImGui::GetMousePos()
{
- return GImGui->IO.MousePos;
+ ImGuiContext& g = *GImGui;
+ return g.IO.MousePos;
}
// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
@@ -4703,7 +4627,7 @@ ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
{
ImGuiContext& g = *GImGui;
if (g.BeginPopupStack.Size > 0)
- return g.OpenPopupStack[g.BeginPopupStack.Size-1].OpenMousePos;
+ return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
return g.IO.MousePos;
}
@@ -4718,10 +4642,19 @@ bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
}
+bool ImGui::IsAnyMouseDown()
+{
+ ImGuiContext& g = *GImGui;
+ for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
+ if (g.IO.MouseDown[n])
+ return true;
+ return false;
+}
+
// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
-// NB: This is only valid if IsMousePosValid(). Back-ends in theory should always keep mouse position valid when dragging even outside the client window.
-ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold)
+// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
+ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
@@ -4734,7 +4667,7 @@ ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold)
return ImVec2(0.0f, 0.0f);
}
-void ImGui::ResetMouseDragDelta(int button)
+void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
@@ -4800,27 +4733,28 @@ bool ImGui::IsItemDeactivatedAfterEdit()
return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
}
+// == GetItemID() == GetFocusID()
bool ImGui::IsItemFocused()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
- if (g.NavId == 0 || g.NavDisableHighlight || g.NavId != window->DC.LastItemId)
+ if (g.NavId != window->DC.LastItemId || g.NavId == 0)
return false;
-
- // Special handling for the dummy item after Begin() which represent the title bar or tab.
- // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
- if (window->DC.LastItemId == window->ID && window->WriteAccessed)
- return false;
-
return true;
}
-bool ImGui::IsItemClicked(int mouse_button)
+bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
{
return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
}
+bool ImGui::IsItemToggledOpen()
+{
+ ImGuiContext& g = *GImGui;
+ return (g.CurrentWindow->DC.LastItemStatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
+}
+
bool ImGui::IsItemToggledSelection()
{
ImGuiContext& g = *GImGui;
@@ -4858,15 +4792,27 @@ bool ImGui::IsItemEdited()
}
// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
+// FIXME: Although this is exposed, its interaction and ideal idiom with using ImGuiButtonFlags_AllowItemOverlap flag are extremely confusing, need rework.
void ImGui::SetItemAllowOverlap()
{
ImGuiContext& g = *GImGui;
- if (g.HoveredId == g.CurrentWindow->DC.LastItemId)
+ ImGuiID id = g.CurrentWindow->DC.LastItemId;
+ if (g.HoveredId == id)
g.HoveredIdAllowOverlap = true;
- if (g.ActiveId == g.CurrentWindow->DC.LastItemId)
+ if (g.ActiveId == id)
g.ActiveIdAllowOverlap = true;
}
+void ImGui::SetItemUsingMouseWheel()
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiID id = g.CurrentWindow->DC.LastItemId;
+ if (g.HoveredId == id)
+ g.HoveredIdUsingMouseWheel = true;
+ if (g.ActiveId == id)
+ g.ActiveIdUsingMouseWheel = true;
+}
+
ImVec2 ImGui::GetItemRectMin()
{
ImGuiWindow* window = GetCurrentWindowRead();
@@ -4885,12 +4831,18 @@ ImVec2 ImGui::GetItemRectSize()
return window->DC.LastItemRect.GetSize();
}
-static bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags)
+static ImRect GetViewportRect()
+{
+ ImGuiContext& g = *GImGui;
+ return ImRect(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y);
+}
+
+bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* parent_window = g.CurrentWindow;
- flags |= ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow|ImGuiWindowFlags_NoDocking;
+ flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_ChildWindow;
flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
// Size
@@ -4904,16 +4856,15 @@ static bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size
SetNextWindowSize(size);
// Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
- char title[256];
if (name)
- ImFormatString(title, IM_ARRAYSIZE(title), "%s/%s_%08X", parent_window->Name, name, id);
+ ImFormatString(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), "%s/%s_%08X", parent_window->Name, name, id);
else
- ImFormatString(title, IM_ARRAYSIZE(title), "%s/%08X", parent_window->Name, id);
+ ImFormatString(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), "%s/%08X", parent_window->Name, id);
const float backup_border_size = g.Style.ChildBorderSize;
if (!border)
g.Style.ChildBorderSize = 0.0f;
- bool ret = Begin(title, NULL, flags);
+ bool ret = Begin(g.TempBuffer, NULL, flags);
g.Style.ChildBorderSize = backup_border_size;
ImGuiWindow* child_window = g.CurrentWindow;
@@ -4930,7 +4881,7 @@ static bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size
{
FocusWindow(child_window);
NavInitWindow(child_window, false);
- SetActiveID(id+1, child_window); // Steal ActiveId with a dummy id so that key-press won't activate child item
+ SetActiveID(id + 1, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
g.ActiveIdSource = ImGuiInputSource_Nav;
}
return ret;
@@ -4953,7 +4904,10 @@ void ImGui::EndChild()
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
- IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() callss
+ IM_ASSERT(g.WithinEndChild == false);
+ IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() calls
+
+ g.WithinEndChild = true;
if (window->BeginCount > 1)
{
End();
@@ -4977,7 +4931,7 @@ void ImGui::EndChild()
// 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);
+ RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_TypeThin);
}
else
{
@@ -4985,6 +4939,7 @@ void ImGui::EndChild()
ItemAdd(bb, 0);
}
}
+ g.WithinEndChild = false;
}
// Helper to create a child window / scrolling region that looks like a normal widget frame.
@@ -5007,28 +4962,11 @@ void ImGui::EndChildFrame()
EndChild();
}
-// Save and compare stack sizes on Begin()/End() to detect usage errors
-static void CheckStacksSize(ImGuiWindow* window, bool write)
-{
- // NOT checking: DC.ItemWidth, DC.AllowKeyboardFocus, DC.ButtonRepeat, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
- ImGuiContext& g = *GImGui;
- short* p_backup = &window->DC.StackSizesBackup[0];
- { int current = window->IDStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup == current && "PushID/PopID or TreeNode/TreePop Mismatch!"); p_backup++; } // Too few or too many PopID()/TreePop()
- { int current = window->DC.GroupStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup == current && "BeginGroup/EndGroup Mismatch!"); p_backup++; } // Too few or too many EndGroup()
- { int current = g.BeginPopupStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup == current && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch"); p_backup++;}// Too few or too many EndMenu()/EndPopup()
- // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
- { int current = g.ColorModifiers.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup >= current && "PushStyleColor/PopStyleColor Mismatch!"); p_backup++; } // Too few or too many PopStyleColor()
- { int current = g.StyleModifiers.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup >= current && "PushStyleVar/PopStyleVar Mismatch!"); p_backup++; } // Too few or too many PopStyleVar()
- { int current = g.FontStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup >= current && "PushFont/PopFont Mismatch!"); p_backup++; } // Too few or too many PopFont()
- IM_ASSERT(p_backup == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup));
-}
-
static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
{
window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags);
window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags);
window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
- window->SetWindowDockAllowFlags = enabled ? (window->SetWindowDockAllowFlags | flags) : (window->SetWindowDockAllowFlags & ~flags);
}
ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
@@ -5043,7 +4981,15 @@ ImGuiWindow* ImGui::FindWindowByName(const char* name)
return FindWindowByID(id);
}
-static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags)
+static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
+{
+ window->Pos = ImFloor(ImVec2(settings->Pos.x, settings->Pos.y));
+ if (settings->Size.x > 0 && settings->Size.y > 0)
+ window->Size = window->SizeFull = ImFloor(ImVec2(settings->Size.x, settings->Size.y));
+ window->Collapsed = settings->Collapsed;
+}
+
+static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
//IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
@@ -5054,33 +5000,17 @@ static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFl
g.WindowsById.SetVoidPtr(window->ID, window);
// Default/arbitrary window position. Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
- ImGuiViewport* main_viewport = ImGui::GetMainViewport();
- window->Pos = main_viewport->Pos + ImVec2(60, 60);
+ window->Pos = ImVec2(60, 60);
// User can disable loading and saving of settings. Tooltip and child windows also don't store settings.
if (!(flags & ImGuiWindowFlags_NoSavedSettings))
if (ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID))
{
// Retrieve settings from .ini file
- window->SettingsIdx = g.SettingsWindows.index_from_ptr(settings);
+ window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
- if (settings->ViewportId)
- {
- window->ViewportId = settings->ViewportId;
- window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
- }
- else
- {
- window->ViewportPos = main_viewport->Pos;
- }
- window->Pos = ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y);
- window->Collapsed = settings->Collapsed;
- if (settings->Size.x > 0 && settings->Size.y > 0)
- size = ImVec2(settings->Size.x, settings->Size.y);
- window->DockId = settings->DockId;
- window->DockOrder = settings->DockOrder;
+ ApplyWindowSettings(window, settings);
}
- window->Size = window->SizeFull = ImFloor(size);
window->DC.CursorStartPos = window->DC.CursorMaxPos = window->Pos; // So first call to CalcContentSize() doesn't return crazy values
if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
@@ -5105,16 +5035,6 @@ static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFl
return window;
}
-static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window)
-{
- return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window;
-}
-
-static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window)
-{
- return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window;
-}
-
static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size)
{
ImGuiContext& g = *GImGui;
@@ -5134,32 +5054,38 @@ static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size
g.NextWindowData.SizeCallback(&data);
new_size = data.DesiredSize;
}
- new_size.x = ImFloor(new_size.x);
- new_size.y = ImFloor(new_size.y);
+ new_size.x = IM_FLOOR(new_size.x);
+ new_size.y = IM_FLOOR(new_size.y);
}
// Minimum size
if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
{
- ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window);
+ ImGuiWindow* window_for_height = window;
new_size = ImMax(new_size, g.Style.WindowMinSize);
new_size.y = ImMax(new_size.y, window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows
}
return new_size;
}
-static ImVec2 CalcWindowContentSize(ImGuiWindow* window)
+static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
{
- if (window->Collapsed)
- if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
- return window->ContentSize;
- if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
- return window->ContentSize;
+ bool preserve_old_content_sizes = false;
+ if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
+ preserve_old_content_sizes = true;
+ else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
+ preserve_old_content_sizes = true;
+ if (preserve_old_content_sizes)
+ {
+ *content_size_current = window->ContentSize;
+ *content_size_ideal = window->ContentSizeIdeal;
+ return;
+ }
- ImVec2 sz;
- sz.x = IM_FLOOR((window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
- sz.y = IM_FLOOR((window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
- return sz;
+ content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
+ content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
+ content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
+ content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
}
static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
@@ -5182,14 +5108,7 @@ static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_cont
ImVec2 size_min = style.WindowMinSize;
if (is_popup || is_menu) // Popups and menus bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
size_min = ImMin(size_min, ImVec2(4.0f, 4.0f));
-
- ImVec2 avail_size = window->Viewport->Size;
- if (window->ViewportOwned)
- avail_size = ImVec2(FLT_MAX, FLT_MAX);
- const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
- if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
- avail_size = g.PlatformIO.Monitors[monitor_idx].WorkSize;
- ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, avail_size - g.Style.DisplaySafeAreaPadding * 2.0f));
+ ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, g.IO.DisplaySize - style.DisplaySafeAreaPadding * 2.0f));
// When the window cannot fit all contents (either because of constraints, either because screen is too small),
// we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
@@ -5204,10 +5123,12 @@ static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_cont
}
}
-ImVec2 ImGui::CalcWindowExpectedSize(ImGuiWindow* window)
+ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
{
- ImVec2 size_contents = CalcWindowContentSize(window);
- ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents);
+ ImVec2 size_contents_current;
+ ImVec2 size_contents_ideal;
+ CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
+ ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);
ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
return size_final;
}
@@ -5244,27 +5165,53 @@ struct ImGuiResizeGripDef
static const ImGuiResizeGripDef resize_grip_def[4] =
{
- { ImVec2(1,1), ImVec2(-1,-1), 0, 3 }, // Lower right
- { ImVec2(0,1), ImVec2(+1,-1), 3, 6 }, // Lower left
- { ImVec2(0,0), ImVec2(+1,+1), 6, 9 }, // Upper left
- { ImVec2(1,0), ImVec2(-1,+1), 9,12 }, // Upper right
+ { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 }, // Lower-right
+ { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 }, // Lower-left
+ { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 }, // Upper-left (Unused)
+ { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 }, // Upper-right (Unused)
+};
+
+struct ImGuiResizeBorderDef
+{
+ ImVec2 InnerDir;
+ ImVec2 CornerPosN1, CornerPosN2;
+ float OuterAngle;
+};
+
+static const ImGuiResizeBorderDef resize_border_def[4] =
+{
+ { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Top
+ { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
+ { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f }, // Bottom
+ { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f } // Left
};
static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
{
ImRect rect = window->Rect();
- if (thickness == 0.0f) rect.Max -= ImVec2(1,1);
- if (border_n == 0) return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness); // Top
- if (border_n == 1) return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding); // Right
- if (border_n == 2) return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness); // Bottom
- if (border_n == 3) return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding); // Left
+ if (thickness == 0.0f) rect.Max -= ImVec2(1, 1);
+ if (border_n == 0) { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness); } // Top
+ if (border_n == 1) { return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding); } // Right
+ if (border_n == 2) { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness); } // Bottom
+ if (border_n == 3) { return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding); } // Left
IM_ASSERT(0);
return ImRect();
}
+// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
+// 4..7: borders (Top, Right, Bottom, Left)
+ImGuiID ImGui::GetWindowResizeID(ImGuiWindow* window, int n)
+{
+ IM_ASSERT(n >= 0 && n <= 7);
+ ImGuiID id = window->ID;
+ id = ImHashStr("#RESIZE", 0, id);
+ id = ImHashData(&n, sizeof(int), id);
+ return id;
+}
+
// Handle resize for: Resize Grips, Borders, Gamepad
// Return true when using auto-fit (double click on resize grip)
-static bool ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4])
+static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
{
ImGuiContext& g = *GImGui;
ImGuiWindowFlags flags = window->Flags;
@@ -5283,18 +5230,8 @@ static bool ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au
ImVec2 pos_target(FLT_MAX, FLT_MAX);
ImVec2 size_target(FLT_MAX, FLT_MAX);
- // Clip mouse interaction rectangles within the viewport (in practice the narrowing is going to happen most of the time).
- // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
- // This is however not the case with current back-ends under Win32, but a custom borderless window implementation would benefit from it.
- // - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow.
- // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold).
- ImRect clip_viewport_rect(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
- if (!(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
- clip_viewport_rect = window->Viewport->GetRect();
-
// Resize grips and borders are on layer 1
window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
- window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu);
// Manual resize grips
PushID("#RESIZE");
@@ -5307,9 +5244,8 @@ static bool ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au
ImRect resize_rect(corner - grip.InnerDir * grip_hover_outer_size, corner + grip.InnerDir * grip_hover_inner_size);
if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
- resize_rect.ClipWith(clip_viewport_rect);
bool hovered, held;
- ButtonBehavior(resize_rect, window->GetID((void*)(intptr_t)resize_grip_n), &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
+ ButtonBehavior(resize_rect, window->GetID(resize_grip_n), &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
//GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
if (hovered || held)
g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
@@ -5326,6 +5262,9 @@ static bool ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au
// Resize from any of the four corners
// We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(grip.InnerDir * grip_hover_outer_size, grip.InnerDir * -grip_hover_inner_size, grip.CornerPosN); // Corner of the window corresponding to our corner grip
+ ImVec2 clamp_min = ImVec2(grip.CornerPosN.x == 1.0f ? visibility_rect.Min.x : -FLT_MAX, grip.CornerPosN.y == 1.0f ? visibility_rect.Min.y : -FLT_MAX);
+ ImVec2 clamp_max = ImVec2(grip.CornerPosN.x == 0.0f ? visibility_rect.Max.x : +FLT_MAX, grip.CornerPosN.y == 0.0f ? visibility_rect.Max.y : +FLT_MAX);
+ corner_target = ImClamp(corner_target, clamp_min, clamp_max);
CalcResizePosSizeFromAnyCorner(window, corner_target, grip.CornerPosN, &pos_target, &size_target);
}
if (resize_grip_n == 0 || held || hovered)
@@ -5335,9 +5274,8 @@ static bool ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au
{
bool hovered, held;
ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS);
- border_rect.ClipWith(clip_viewport_rect);
- ButtonBehavior(border_rect, window->GetID((void*)(intptr_t)(border_n + 4)), &hovered, &held, ImGuiButtonFlags_FlattenChildren);
- //GetForegroundDrawList(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
+ ButtonBehavior(border_rect, window->GetID(border_n + 4), &hovered, &held, ImGuiButtonFlags_FlattenChildren);
+ //GetForegroundDrawLists(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held)
{
g.MouseCursor = (border_n & 1) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
@@ -5352,14 +5290,16 @@ static bool ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au
if (border_n == 1) { border_posn = ImVec2(1, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Right
if (border_n == 2) { border_posn = ImVec2(0, 1); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Bottom
if (border_n == 3) { border_posn = ImVec2(0, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Left
+ ImVec2 clamp_min = ImVec2(border_n == 1 ? visibility_rect.Min.x : -FLT_MAX, border_n == 2 ? visibility_rect.Min.y : -FLT_MAX);
+ ImVec2 clamp_max = ImVec2(border_n == 3 ? visibility_rect.Max.x : +FLT_MAX, border_n == 0 ? visibility_rect.Max.y : +FLT_MAX);
+ border_target = ImClamp(border_target, clamp_min, clamp_max);
CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target);
}
}
PopID();
- // Resize nav layer
+ // Restore nav layer
window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
- window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
// Navigation resize (keyboard/gamepad)
if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindow == window)
@@ -5373,6 +5313,7 @@ static bool ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au
{
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));
+ nav_resize_delta = ImMax(nav_resize_delta, visibility_rect.Min - window->Pos - window->Size);
g.NavWindowingToggleLayer = false;
g.NavDisableMouseHover = true;
resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
@@ -5397,11 +5338,13 @@ static bool ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au
return ret_auto_fit;
}
-static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& rect, const ImVec2& padding)
+static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& visibility_rect)
{
ImGuiContext& g = *GImGui;
- ImVec2 size_for_clamping = (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) ? ImVec2(window->Size.x, window->TitleBarHeight()) : window->Size;
- window->Pos = ImMin(rect.Max - padding, ImMax(window->Pos + size_for_clamping, rect.Min + padding) - size_for_clamping);
+ ImVec2 size_for_clamping = window->Size;
+ if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
+ size_for_clamping.y = window->TitleBarHeight();
+ window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
}
static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
@@ -5415,26 +5358,13 @@ static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
int border_held = window->ResizeBorderHeld;
if (border_held != -1)
{
- struct ImGuiResizeBorderDef
- {
- ImVec2 InnerDir;
- ImVec2 CornerPosN1, CornerPosN2;
- float OuterAngle;
- };
- static const ImGuiResizeBorderDef resize_border_def[4] =
- {
- { ImVec2(0,+1), ImVec2(0,0), ImVec2(1,0), IM_PI*1.50f }, // Top
- { ImVec2(-1,0), ImVec2(1,0), ImVec2(1,1), IM_PI*0.00f }, // Right
- { ImVec2(0,-1), ImVec2(1,1), ImVec2(0,1), IM_PI*0.50f }, // Bottom
- { ImVec2(+1,0), ImVec2(0,1), ImVec2(0,0), IM_PI*1.00f } // Left
- };
const ImGuiResizeBorderDef& def = resize_border_def[border_held];
ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f);
- window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI*0.25f, def.OuterAngle);
- window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI*0.25f);
+ window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle);
+ window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f);
window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), false, ImMax(2.0f, border_size)); // Thicker than usual
}
- if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
+ if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
{
float y = window->Pos.y + window->TitleBarHeight() - 1;
window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), GetColorU32(ImGuiCol_Border), g.Style.FrameBorderSize);
@@ -5443,12 +5373,16 @@ static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
// Draw background and borders
// Draw and handle scrollbars
-void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
+void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
{
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
ImGuiWindowFlags flags = window->Flags;
+ // Ensure that ScrollBar doesn't read last frame's SkipItems
+ IM_ASSERT(window->BeginCount == 0);
+ window->SkipItems = false;
+
// Draw window + handle manual resize
// As we highlight the title bar when want_focus is set, multiple reappearing windows will have have their title bar highlighted on their reappearing frame.
const float window_rounding = window->WindowRounding;
@@ -5467,37 +5401,21 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar
// Window background
if (!(flags & ImGuiWindowFlags_NoBackground))
{
- bool is_docking_transparent_payload = false;
- if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload)
- if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window)
- is_docking_transparent_payload = true;
-
ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags));
- if (window->ViewportOwned)
+ bool override_alpha = false;
+ float alpha = 1.0f;
+ if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
{
- // No alpha
- bg_col = (bg_col | IM_COL32_A_MASK);
- if (is_docking_transparent_payload)
- window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
- }
- else
- {
- // Adjust alpha. For docking
- float alpha = 1.0f;
- if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
- alpha = g.NextWindowData.BgAlphaVal;
- if (is_docking_transparent_payload)
- alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
- if (alpha != 1.0f)
- bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
+ alpha = g.NextWindowData.BgAlphaVal;
+ override_alpha = true;
}
+ if (override_alpha)
+ bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
window->DrawList->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Bot);
}
// Title bar
- // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag,
- // in order for their pos/size to be matching their undocking state.)
- if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
+ if (!(flags & ImGuiWindowFlags_NoTitleBar))
{
ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawCornerFlags_Top);
@@ -5513,21 +5431,6 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar
window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
}
- // Docking: Unhide tab bar (small triangle in the corner)
- if (window->DockNode && window->DockNode->IsHiddenTabBar() && !window->DockNode->IsNoTabBar())
- {
- float unhide_sz_draw = ImFloor(g.FontSize * 0.70f);
- float unhide_sz_hit = ImFloor(g.FontSize * 0.55f);
- ImVec2 p = window->DockNode->Pos;
- ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit));
- bool hovered, held;
- if (ButtonBehavior(r, window->GetID("#UNHIDE"), &hovered, &held, ImGuiButtonFlags_FlattenChildren))
- window->DockNode->WantHiddenTabBarToggle = true;
- // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size..
- ImU32 col = GetColorU32(((held && hovered) || (window->DockNode->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
- window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col);
- }
-
// Scrollbars
if (window->ScrollbarX)
Scrollbar(ImGuiAxis_X);
@@ -5535,7 +5438,7 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar
Scrollbar(ImGuiAxis_Y);
// Render resize grips (after their input handling so we don't have a frame of latency)
- if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
+ if (!(flags & ImGuiWindowFlags_NoResize))
{
for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
{
@@ -5548,14 +5451,12 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar
}
}
- // Borders (for dock node host they will be rendered over after the tab bar)
- if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
- RenderWindowOuterBorders(window);
+ // Borders
+ RenderWindowOuterBorders(window);
}
}
// Render title text, collapse button, close button
-// When inside a dock node, this is handled in DockNodeUpdateTabBar() instead.
void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
{
ImGuiContext& g = *GImGui;
@@ -5569,7 +5470,6 @@ void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& titl
const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags;
window->DC.ItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
- window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu);
// Layout buttons
// FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
@@ -5596,7 +5496,7 @@ void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& titl
// Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
if (has_collapse_button)
- if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos, NULL))
+ if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos))
window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
// Close button
@@ -5605,7 +5505,6 @@ void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& titl
*p_open = false;
window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
- window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
window->DC.ItemFlags = item_flags_backup;
// Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
@@ -5615,7 +5514,7 @@ void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& titl
const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
// As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
- // while uncentered title text will still reach edges correct.
+ // while uncentered title text will still reach edges correctly.
if (pad_l > style.FramePadding.x)
pad_l += g.Style.ItemInnerSpacing.x;
if (pad_r > style.FramePadding.x)
@@ -5629,8 +5528,9 @@ void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& titl
}
ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);
- ImRect clip_r(layout_r.Min.x, layout_r.Min.y, layout_r.Max.x + g.Style.ItemInnerSpacing.x, layout_r.Max.y);
- //if (g.IO.KeyCtrl) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
+ ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y);
+ //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
+ //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
if (flags & ImGuiWindowFlags_UnsavedDocument)
{
@@ -5643,13 +5543,9 @@ void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& titl
void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
{
window->ParentWindow = parent_window;
- window->RootWindow = window->RootWindowDockStop = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
+ window->RootWindow = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
- {
window->RootWindow = parent_window->RootWindow;
- if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost))
- window->RootWindowDockStop = parent_window->RootWindowDockStop;
- }
if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)))
window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
@@ -5671,17 +5567,14 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
IM_ASSERT(name != NULL && name[0] != '\0'); // Window name required
- IM_ASSERT(g.FrameScopeActive); // Forgot to call ImGui::NewFrame()
+ IM_ASSERT(g.WithinFrameScope); // Forgot to call ImGui::NewFrame()
IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
// Find or create
ImGuiWindow* window = FindWindowByName(name);
const bool window_just_created = (window == NULL);
if (window_just_created)
- {
- ImVec2 size_on_first_use = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) ? g.NextWindowData.SizeVal : ImVec2(0.0f, 0.0f); // Any condition flag will do since we are creating a new window here.
- window = CreateNewWindow(name, size_on_first_use, flags);
- }
+ window = CreateNewWindow(name, flags);
// Automatically disable manual moving/resizing when NoInputs is set
if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
@@ -5692,7 +5585,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
const int current_frame = g.FrameCount;
const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
- window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.FrameScopePushedFallbackWindow);
+ window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
// Update the Appearing flag
bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
@@ -5710,7 +5603,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
// Update Flags, LastFrameActive, BeginOrderXXX fields
if (first_begin_of_the_frame)
{
- window->FlagsPreviousFrame = window->Flags;
window->Flags = (ImGuiWindowFlags)flags;
window->LastFrameActive = current_frame;
window->LastTimeActive = (float)g.Time;
@@ -5722,27 +5614,8 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
flags = window->Flags;
}
- // Docking
- // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1)
- IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both
- if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasDock)
- SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond);
- if (first_begin_of_the_frame)
- {
- bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL);
- bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window);
- if (has_dock_node || new_auto_dock_node)
- {
- BeginDocked(window, p_open);
- flags = window->Flags;
-
- // Docking currently override constraints
- g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint;
- }
- }
-
// Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
- ImGuiWindow* parent_window_in_stack = window->DockIsActive ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back();
+ ImGuiWindow* parent_window_in_stack = g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back();
ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
@@ -5753,8 +5626,10 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
// Add to stack
// We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
g.CurrentWindowStack.push_back(window);
+ g.CurrentWindow = window;
+ window->DC.StackSizesOnBegin.SetToCurrentState();
g.CurrentWindow = NULL;
- CheckStacksSize(window, true);
+
if (flags & ImGuiWindowFlags_Popup)
{
ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
@@ -5766,7 +5641,12 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
if (window_just_appearing_after_hidden_for_resize && !(flags & ImGuiWindowFlags_ChildWindow))
window->NavLastIds[0] = 0;
+ // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
+ if (first_begin_of_the_frame)
+ UpdateWindowParentAndRootLinks(window, flags, parent_window);
+
// Process SetNextWindow***() calls
+ // (FIXME: Consider splitting the HasXXX flags into X/Y components
bool window_pos_set_by_api = false;
bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
@@ -5791,12 +5671,23 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
}
+ if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
+ {
+ if (g.NextWindowData.ScrollVal.x >= 0.0f)
+ {
+ window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
+ window->ScrollTargetCenterRatio.x = 0.0f;
+ }
+ if (g.NextWindowData.ScrollVal.y >= 0.0f)
+ {
+ window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
+ window->ScrollTargetCenterRatio.y = 0.0f;
+ }
+ }
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
else if (first_begin_of_the_frame)
window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
- if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasWindowClass)
- window->WindowClass = g.NextWindowData.WindowClass;
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
@@ -5809,12 +5700,12 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
{
// Initialize
const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
- UpdateWindowParentAndRootLinks(window, flags, parent_window);
-
window->Active = true;
window->HasCloseButton = (p_open != NULL);
- window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX);
+ window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
window->IDStack.resize(1);
+ window->DrawList->_ResetForNewFrame();
+ window->DC.CurrentTableIdx = -1;
// Restore buffer capacity when woken from a compacted state, to avoid
if (window->MemoryCompacted)
@@ -5823,9 +5714,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
// Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
// The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
bool window_title_visible_elsewhere = false;
- if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
- window_title_visible_elsewhere = true;
- else if (g.NavWindowingList != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB
+ if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB
window_title_visible_elsewhere = true;
if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
{
@@ -5837,11 +5726,13 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
// UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
// Update contents size from last frame for auto-fitting (or use explicit size)
- window->ContentSize = CalcWindowContentSize(window);
+ CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
if (window->HiddenFramesCanSkipItems > 0)
window->HiddenFramesCanSkipItems--;
if (window->HiddenFramesCannotSkipItems > 0)
window->HiddenFramesCannotSkipItems--;
+ if (window->HiddenFramesForRenderOnly > 0)
+ window->HiddenFramesForRenderOnly--;
// 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))
@@ -5858,36 +5749,31 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
window->Size.x = window->SizeFull.x = 0.f;
if (!window_size_y_set_by_api)
window->Size.y = window->SizeFull.y = 0.f;
- window->ContentSize = ImVec2(0.f, 0.f);
+ window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
}
}
// SELECT VIEWPORT
- // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes.
-
- UpdateSelectWindowViewport(window);
- SetCurrentViewport(window, window->Viewport);
- window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
+ // FIXME-VIEWPORT: In the docking/viewport branch, this is the point where we select the current viewport (which may affect the style)
SetCurrentWindow(window);
- flags = window->Flags;
// LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
- // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style.
if (flags & ImGuiWindowFlags_ChildWindow)
window->WindowBorderSize = style.ChildBorderSize;
else
window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
- if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)
+ 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);
- else
- window->WindowPadding = style.WindowPadding;
+
+ // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
// Collapse window by double-clicking on title bar
// At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
- if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive)
+ if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse))
{
// We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
ImRect title_bar_rect = window->TitleBarRect();
@@ -5909,7 +5795,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
// SIZE
// Calculate auto-fit size, handle automatic resize
- const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSize);
+ const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);
bool use_current_size_for_scrollbar_x = window_just_created;
bool use_current_size_for_scrollbar_y = window_just_created;
if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
@@ -5957,7 +5843,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
if (window_just_activated_by_user)
{
window->AutoPosLastDirection = ImGuiDir_None;
- if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api)
+ if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
window->Pos = g.BeginPopupStack.back().OpenPopupPos;
}
@@ -5973,7 +5859,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
if (window_pos_with_pivot)
- SetWindowPos(window, window->SetWindowPosVal - window->SizeFull * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
+ SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
window->Pos = FindBestWindowPosForPopup(window);
else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
@@ -5981,117 +5867,26 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
window->Pos = FindBestWindowPosForPopup(window);
- // Late create viewport if we don't fit within our current host viewport.
- if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_Minimized))
- if (!window->Viewport->GetRect().Contains(window->Rect()))
- {
- // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
- //ImGuiViewport* old_viewport = window->Viewport;
- window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
-
- // FIXME-DPI
- //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong
- SetCurrentViewport(window, window->Viewport);
- window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
- SetCurrentWindow(window);
- }
-
- bool viewport_rect_changed = false;
- if (window->ViewportOwned)
- {
- // Synchronize window --> viewport in most situations
- // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM
- if (window->Viewport->PlatformRequestMove)
- {
- window->Pos = window->Viewport->Pos;
- MarkIniSettingsDirty(window);
- }
- else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0)
- {
- viewport_rect_changed = true;
- window->Viewport->Pos = window->Pos;
- }
-
- if (window->Viewport->PlatformRequestResize)
- {
- window->Size = window->SizeFull = window->Viewport->Size;
- MarkIniSettingsDirty(window);
- }
- else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0)
- {
- viewport_rect_changed = true;
- window->Viewport->Size = window->Size;
- }
-
- // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame()
- // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect.
- if (viewport_rect_changed)
- UpdateViewportPlatformMonitor(window->Viewport);
-
- // Update common viewport flags
- ImGuiViewportFlags viewport_flags = (window->Viewport->Flags) & ~(ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration);
- const bool is_short_lived_floating_window = (flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0;
- if (flags & ImGuiWindowFlags_Tooltip)
- viewport_flags |= ImGuiViewportFlags_TopMost;
- if (g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window)
- viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon;
- if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window)
- viewport_flags |= ImGuiViewportFlags_NoDecoration;
-
- // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them
- // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration).
- // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app,
- // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere.
- if (is_short_lived_floating_window && (flags & ImGuiWindowFlags_Modal) == 0)
- viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick;
-
- // We can overwrite viewport flags using ImGuiWindowClass (advanced users)
- // We don't default to the main viewport because.
- if (window->WindowClass.ParentViewportId)
- window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId;
- else if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack)
- window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID;
- else
- window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID;
- if (window->WindowClass.ViewportFlagsOverrideSet)
- viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet;
- if (window->WindowClass.ViewportFlagsOverrideClear)
- viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear;
-
- // We also tell the back-end that clearing the platform window won't be necessary, as our window is filling the viewport and we have disabled BgAlpha
- viewport_flags |= ImGuiViewportFlags_NoRendererClear;
- window->Viewport->Flags = viewport_flags;
- }
+ // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
+ // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
+ ImRect viewport_rect(GetViewportRect());
+ ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
+ ImRect visibility_rect(viewport_rect.Min + visibility_padding, viewport_rect.Max - visibility_padding);
// Clamp position/size so window stays visible within its viewport or monitor
// Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
- ImRect viewport_rect = window->Viewport->GetRect();
if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
- {
- ImVec2 clamp_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
- if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
- ClampWindowRect(window, viewport_rect, clamp_padding);
- else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0)
- {
- if (window->Viewport->PlatformMonitor == -1)
- {
- // Fallback for "lost" window (e.g. a monitor disconnected): we move the window back over the main viewport
- SetWindowPos(window, g.Viewports[0]->Pos + style.DisplayWindowPadding, ImGuiCond_Always);
- }
- else
- {
- ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->Viewport->PlatformMonitor];
- ClampWindowRect(window, ImRect(monitor.WorkPos, monitor.WorkPos + monitor.WorkSize), clamp_padding);
- }
- }
- }
+ if (viewport_rect.GetWidth() > 0.0f && viewport_rect.GetHeight() > 0.0f)
+ ClampWindowRect(window, visibility_rect);
window->Pos = ImFloor(window->Pos);
// Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
- if (window->ViewportOwned || window->DockIsActive)
- window->WindowRounding = 0.0f;
- else
- window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
+ // Large values tend to lead to variety of artifacts and are not recommended.
+ window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
+
+ // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
+ //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
+ // window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
// Apply window focus (new and reactivated windows are moved to front)
bool want_focus = false;
@@ -6099,36 +5894,20 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
{
if (flags & ImGuiWindowFlags_Popup)
want_focus = true;
- else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip))
+ else if ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) == 0)
want_focus = true;
}
- // Decide if we are going to handle borders and resize grips
- const bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
-
// Handle manual resize: Resize Grips, Borders, Gamepad
int border_held = -1;
ImU32 resize_grip_col[4] = {};
- const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // 4
- const float resize_grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
- if (handle_borders_and_resize_grips && !window->Collapsed)
- if (UpdateManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0]))
+ const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
+ const float resize_grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
+ if (!window->Collapsed)
+ if (UpdateWindowManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
use_current_size_for_scrollbar_x = use_current_size_for_scrollbar_y = true;
window->ResizeBorderHeld = (signed char)border_held;
- // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either)
- if (window->ViewportOwned)
- {
- if (!window->Viewport->PlatformRequestMove)
- window->Viewport->Pos = window->Pos;
- if (!window->Viewport->PlatformRequestResize)
- window->Viewport->Size = window->Size;
- viewport_rect = window->Viewport->GetRect();
- }
-
- // Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
- window->ViewportPos = window->Viewport->Pos;
-
// SCROLLBAR VISIBILITY
// Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
@@ -6162,8 +5941,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
const ImRect outer_rect = window->Rect();
const ImRect title_bar_rect = window->TitleBarRect();
window->OuterRectClipped = outer_rect;
- if (window->DockIsActive)
- window->OuterRectClipped.Min.y += window->TitleBarHeight();
window->OuterRectClipped.ClipWith(host_rect);
// Inner rectangle
@@ -6206,19 +5983,19 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
// Apply scrolling
- window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window, true);
+ window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
// DRAWING
// Setup draw list and outer clipping rectangle
- window->DrawList->Clear();
+ IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
PushClipRect(host_rect.Min, host_rect.Max, false);
- // Draw modal or window list full viewport dimming background (for other viewports we'll render them in EndFrame)
+ // Draw modal window background (darkens what is behind them, all viewports)
const bool dim_bg_for_modal = (flags & ImGuiWindowFlags_Modal) && window == GetTopMostPopupModal() && window->HiddenFramesCannotSkipItems <= 0;
- const bool dim_bg_for_window_list = g.NavWindowingTargetAnim && ((window == g.NavWindowingTargetAnim->RootWindow) || (g.NavWindowingList && (window == g.NavWindowingList) && g.NavWindowingList->Viewport != g.NavWindowingTargetAnim->Viewport));
+ const bool dim_bg_for_window_list = g.NavWindowingTargetAnim && (window == g.NavWindowingTargetAnim->RootWindow);
if (dim_bg_for_modal || dim_bg_for_window_list)
{
const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
@@ -6234,14 +6011,11 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha * 0.25f), g.Style.WindowRounding);
}
- const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible;
-
// Since 1.71, child window can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call.
// When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
// We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping child.
// We also disabled this when we have dimming overlay behind this specific one child.
// FIXME: More code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected.
- if (is_undocked_or_docked_visible)
{
bool render_decorations_in_parent = false;
if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
@@ -6252,8 +6026,8 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
// Handle title bar, scrollbar, resize grips and resize borders
const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
- const bool title_bar_is_highlight = want_focus || (window_to_highlight && (window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight || (window->DockNode && window->DockNode == window_to_highlight->DockNode)));
- RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
+ const bool title_bar_is_highlight = want_focus || (window_to_highlight && window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight);
+ RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, resize_grip_count, resize_grip_col, resize_grip_draw_size);
if (render_decorations_in_parent)
window->DrawList = &window->DrawListInst;
@@ -6288,15 +6062,16 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
window->WorkRect.Min.y = ImFloor(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
+ window->ParentWorkRect = window->WorkRect;
- // [LEGACY] Contents Region
- // FIXME-OBSOLETE: window->ContentsRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
+ // [LEGACY] Content Region
+ // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
// Used by:
// - Mouse wheel scrolling + many other things
- window->ContentsRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x;
- window->ContentsRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + decoration_up_height;
- window->ContentsRegionRect.Max.x = window->ContentsRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - window->ScrollbarSizes.x));
- window->ContentsRegionRect.Max.y = window->ContentsRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - decoration_up_height - window->ScrollbarSizes.y));
+ window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x;
+ window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + decoration_up_height;
+ window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - window->ScrollbarSizes.x));
+ window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - decoration_up_height - window->ScrollbarSizes.y));
// Setup drawing context
// (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
@@ -6307,35 +6082,31 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
window->DC.CursorPos = window->DC.CursorStartPos;
window->DC.CursorPosPrevLine = window->DC.CursorPos;
window->DC.CursorMaxPos = window->DC.CursorStartPos;
+ window->DC.IdealMaxPos = window->DC.CursorStartPos;
window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
- window->DC.NavHideHighlightOneFrame = false;
- window->DC.NavHasScroll = (window->ScrollMax.y > 0.0f);
+
+ window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
window->DC.NavLayerActiveMask = window->DC.NavLayerActiveMaskNext;
window->DC.NavLayerActiveMaskNext = 0x00;
+ window->DC.NavHideHighlightOneFrame = false;
+ window->DC.NavHasScroll = (window->ScrollMax.y > 0.0f);
+
window->DC.MenuBarAppending = false;
+ window->DC.MenuColumns.Update(3, style.ItemSpacing.x, window_just_activated_by_user);
+ window->DC.TreeDepth = 0;
+ window->DC.TreeJumpToParentOnPopMask = 0x00;
window->DC.ChildWindows.resize(0);
+ window->DC.StateStorage = &window->StateStorage;
+ window->DC.CurrentColumns = NULL;
window->DC.LayoutType = ImGuiLayoutType_Vertical;
window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
- window->DC.FocusCounterAll = window->DC.FocusCounterTab = -1;
- window->DC.ItemFlags = parent_window ? parent_window->DC.ItemFlags : ImGuiItemFlags_Default_;
+ window->DC.FocusCounterRegular = window->DC.FocusCounterTabStop = -1;
+
window->DC.ItemWidth = window->ItemWidthDefault;
window->DC.TextWrapPos = -1.0f; // disabled
- window->DC.ItemFlagsStack.resize(0);
window->DC.ItemWidthStack.resize(0);
window->DC.TextWrapPosStack.resize(0);
- window->DC.CurrentColumns = NULL;
- window->DC.TreeDepth = 0;
- window->DC.TreeMayJumpToParentOnPopMask = 0x00;
- window->DC.StateStorage = &window->StateStorage;
- window->DC.GroupStack.resize(0);
- window->MenuColumns.Update(3, style.ItemSpacing.x, window_just_activated_by_user);
-
- if ((flags & ImGuiWindowFlags_ChildWindow) && (window->DC.ItemFlags != parent_window->DC.ItemFlags))
- {
- window->DC.ItemFlags = parent_window->DC.ItemFlags;
- window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags);
- }
if (window->AutoFitFramesX > 0)
window->AutoFitFramesX--;
@@ -6349,21 +6120,9 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
NavInitWindow(window, false);
}
- // Close from platform window
- if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
- {
- if (!window->DockIsActive || window->DockTabIsVisible)
- {
- window->Viewport->PlatformRequestClose = false;
- g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue.
- IMGUI_DEBUG_LOG_VIEWPORT("Window '%s' PlatformRequestClose\n", window->Name);
- *p_open = false;
- }
- }
-
// Title bar
- if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
- RenderWindowTitleBarContents(window, title_bar_rect, name, p_open);
+ if (!(flags & ImGuiWindowFlags_NoTitleBar))
+ RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open);
// Clear hit test shape every frame
window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
@@ -6372,41 +6131,15 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
// This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
// Maybe we can support CTRL+C on every element?
/*
- if (g.ActiveId == move_id)
+ //if (g.NavWindow == window && g.ActiveId == 0)
+ if (g.ActiveId == window->MoveId)
if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C))
LogToClipboard();
*/
- if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)
- {
- // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source.
- // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginAsDockableDragDropSource() also overwrites it.
- if ((g.ActiveId == window->MoveId) && (g.IO.ConfigDockingWithShift == g.IO.KeyShift))
- if ((window->Flags & ImGuiWindowFlags_NoMove) == 0)
- if ((window->RootWindow->Flags & (ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking)) == 0)
- BeginAsDockableDragDropSource(window);
-
- // Docking: Any dockable window can act as a target. For dock node hosts we call BeginAsDockableDragDropTarget() in DockNodeUpdate() instead.
- if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking))
- if (g.MovingWindow == NULL || g.MovingWindow->RootWindow != window)
- if ((window == window->RootWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost))
- BeginAsDockableDragDropTarget(window);
- }
-
// We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
// This is useful to allow creating context menus on title bar only, etc.
- if (window->DockIsActive)
- {
- window->DC.LastItemId = window->ID;
- window->DC.LastItemStatusFlags = window->DockTabItemStatusFlags;
- window->DC.LastItemRect = window->DockTabItemRect;
- }
- else
- {
- 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;
- }
+ SetLastItemData(window, window->MoveId, IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, title_bar_rect);
#ifdef IMGUI_ENABLE_TEST_ENGINE
if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
@@ -6416,100 +6149,90 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
else
{
// Append
- SetCurrentViewport(window, window->Viewport);
SetCurrentWindow(window);
}
- if (!(flags & ImGuiWindowFlags_DockNodeHost))
- PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
+ // Pull/inherit current state
+ window->DC.ItemFlags = g.ItemFlagsStack.back(); // Inherit from shared stack
+ window->DC.NavFocusScopeIdCurrent = (flags & ImGuiWindowFlags_ChildWindow) ? parent_window->DC.NavFocusScopeIdCurrent : 0; // Inherit from parent only // -V595
+
+ 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->WriteAccessed = false;
window->BeginCount++;
g.NextWindowData.ClearFlags();
- // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems.
- // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents.
- // This is analogous to regular windows being hidden from one frame.
- // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed.
- if (window->DockIsActive && !window->DockTabIsVisible)
+ // Update visibility
+ if (first_begin_of_the_frame)
{
- if (window->LastFrameJustFocused == g.FrameCount)
- window->HiddenFramesCannotSkipItems = 1;
- else
- window->HiddenFramesCanSkipItems = 1;
- }
+ if (flags & ImGuiWindowFlags_ChildWindow)
+ {
+ // Child window can be out of sight and have "negative" clip windows.
+ // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
+ IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0);
+ if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) // FIXME: Doesn't make sense for ChildWindow??
+ if (!g.LogEnabled)
+ if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
+ window->HiddenFramesCanSkipItems = 1;
- if (flags & ImGuiWindowFlags_ChildWindow)
- {
- // Child window can be out of sight and have "negative" clip windows.
- // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
- IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0 || (window->DockIsActive));
- if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
- if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
+ // Hide along with parent or if parent is collapsed
+ if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
window->HiddenFramesCanSkipItems = 1;
+ if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
+ window->HiddenFramesCannotSkipItems = 1;
+ }
- // Hide along with parent or if parent is collapsed
- if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
+ // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
+ if (style.Alpha <= 0.0f)
window->HiddenFramesCanSkipItems = 1;
- if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
- window->HiddenFramesCannotSkipItems = 1;
+
+ // Update the Hidden flag
+ window->Hidden = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0) || (window->HiddenFramesForRenderOnly > 0);
+
+ // Update the SkipItems flag, used to early out of all items functions (no layout required)
+ bool skip_items = false;
+ if (window->Collapsed || !window->Active || window->Hidden)
+ if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
+ skip_items = true;
+ window->SkipItems = skip_items;
}
- // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
- if (style.Alpha <= 0.0f)
- window->HiddenFramesCanSkipItems = 1;
-
- // Update the Hidden flag
- window->Hidden = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
-
- // Update the SkipItems flag, used to early out of all items functions (no layout required)
- bool skip_items = false;
- if (window->Collapsed || !window->Active || window->Hidden)
- if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
- skip_items = true;
- window->SkipItems = skip_items;
-
- return !skip_items;
+ return !window->SkipItems;
}
void ImGui::End()
{
ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
- if (g.CurrentWindowStack.Size <= 1 && g.FrameScopePushedFallbackWindow)
+ // Error checking: verify that user hasn't called End() too many times!
+ if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
{
- IM_ASSERT(g.CurrentWindowStack.Size > 1 && "Calling End() too many times!");
- return; // FIXME-ERRORHANDLING
+ IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
+ return;
}
IM_ASSERT(g.CurrentWindowStack.Size > 0);
- ImGuiWindow* window = g.CurrentWindow;
+ // Error checking: verify that user doesn't directly call End() on a child window.
+ if (window->Flags & ImGuiWindowFlags_ChildWindow)
+ IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
+ // Close anything that is open
if (window->DC.CurrentColumns)
EndColumns();
- if (!(window->Flags & ImGuiWindowFlags_DockNodeHost)) // Pop inner window clip rectangle
- PopClipRect();
+ PopClipRect(); // Inner window clip rectangle
// Stop logging
if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging
LogFinish();
- // Docking: report contents sizes to parent to allow for auto-resize
- if (window->DockNode && window->DockTabIsVisible)
- if (ImGuiWindow* host_window = window->DockNode->HostWindow) // FIXME-DOCK
- host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding;
-
// Pop from window stack
g.CurrentWindowStack.pop_back();
if (window->Flags & ImGuiWindowFlags_Popup)
g.BeginPopupStack.pop_back();
- CheckStacksSize(window, false);
+ window->DC.StackSizesOnBegin.CompareWithCurrentState();
SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back());
- if (g.CurrentWindow)
- SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport);
}
void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
@@ -6530,7 +6253,7 @@ void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* current_front_window = g.Windows.back();
- if (current_front_window == window || current_front_window->RootWindow == window)
+ if (current_front_window == window || current_front_window->RootWindow == window) // Cheap early out (could be better)
return;
for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
if (g.Windows[i] == window)
@@ -6567,6 +6290,7 @@ void ImGui::FocusWindow(ImGuiWindow* window)
g.NavMousePosDirty = true;
g.NavInitRequest = false;
g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
+ g.NavFocusScopeId = 0;
g.NavIdIsAlive = false;
g.NavLayer = ImGuiNavLayer_Main;
//IMGUI_DEBUG_LOG("FocusWindow(\"%s\")\n", window ? window->Name : NULL);
@@ -6575,28 +6299,26 @@ void ImGui::FocusWindow(ImGuiWindow* window)
// Close popups if any
ClosePopupsOverWindow(window, false);
+ // Move the root window to the top of the pile
+ IM_ASSERT(window == NULL || window->RootWindow != NULL);
+ ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL; // NB: In docking branch this is window->RootWindowDockStop
+ ImGuiWindow* display_front_window = window ? window->RootWindow : NULL;
+
+ // Steal active widgets. Some of the cases it triggers includes:
+ // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
+ // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
+ if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
+ if (!g.ActiveIdNoClearOnFocusLoss)
+ ClearActiveID();
+
// Passing NULL allow to disable keyboard focus
if (!window)
return;
- window->LastFrameJustFocused = g.FrameCount;
-
- // Select in dock node
- if (window->DockNode && window->DockNode->TabBar)
- window->DockNode->TabBar->SelectedTabId = window->DockNode->TabBar->NextSelectedTabId = window->ID;
-
- // Move the root window to the top of the pile
- if (window->RootWindow)
- window = window->RootWindow;
-
- // Steal focus on active widgets
- if (window->Flags & ImGuiWindowFlags_Popup) // FIXME: This statement should be unnecessary. Need further testing before removing it..
- if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != window)
- ClearActiveID();
// Bring to front
- BringWindowToFocusFront(window);
- if (!(window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus))
- BringWindowToDisplayFront(window);
+ BringWindowToFocusFront(focus_front_window);
+ if (((window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
+ BringWindowToDisplayFront(display_front_window);
}
void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window)
@@ -6617,10 +6339,6 @@ void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWind
if (window != ignore_window && window->WasActive && !(window->Flags & ImGuiWindowFlags_ChildWindow))
if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
{
- // FIXME-DOCKING: This is failing (lagging by one frame) for docked windows.
- // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B.
- // We might leverage the tab order implicitly stored in window->DockNodeAsHost->TabBar (essentially the 'most_recently_selected_tab' code in tab bar will do that but on next update)
- // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself?
ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(window);
FocusWindow(focus_window);
return;
@@ -6629,88 +6347,6 @@ void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWind
FocusWindow(NULL);
}
-void ImGui::SetNextItemWidth(float item_width)
-{
- ImGuiContext& g = *GImGui;
- g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
- g.NextItemData.Width = item_width;
-}
-
-void ImGui::PushItemWidth(float item_width)
-{
- ImGuiContext& g = *GImGui;
- ImGuiWindow* window = g.CurrentWindow;
- window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
- window->DC.ItemWidthStack.push_back(window->DC.ItemWidth);
- g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
-}
-
-void ImGui::PushMultiItemsWidths(int components, float w_full)
-{
- ImGuiContext& g = *GImGui;
- ImGuiWindow* window = g.CurrentWindow;
- const ImGuiStyle& style = g.Style;
- const float w_item_one = ImMax(1.0f, IM_FLOOR((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components));
- const float w_item_last = ImMax(1.0f, IM_FLOOR(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1)));
- window->DC.ItemWidthStack.push_back(w_item_last);
- for (int i = 0; i < components-1; i++)
- window->DC.ItemWidthStack.push_back(w_item_one);
- window->DC.ItemWidth = window->DC.ItemWidthStack.back();
- g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
-}
-
-void ImGui::PopItemWidth()
-{
- ImGuiWindow* window = GetCurrentWindow();
- window->DC.ItemWidthStack.pop_back();
- window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back();
-}
-
-// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
-// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
-float ImGui::CalcItemWidth()
-{
- ImGuiContext& g = *GImGui;
- ImGuiWindow* window = g.CurrentWindow;
- float w;
- if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
- w = g.NextItemData.Width;
- else
- w = window->DC.ItemWidth;
- if (w < 0.0f)
- {
- float region_max_x = GetContentRegionMaxAbs().x;
- w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
- }
- w = IM_FLOOR(w);
- return w;
-}
-
-// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
-// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
-// Note that only CalcItemWidth() is publicly exposed.
-// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
-ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
-{
- ImGuiWindow* window = GImGui->CurrentWindow;
-
- ImVec2 region_max;
- if (size.x < 0.0f || size.y < 0.0f)
- region_max = GetContentRegionMaxAbs();
-
- if (size.x == 0.0f)
- size.x = default_w;
- else if (size.x < 0.0f)
- size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
-
- if (size.y == 0.0f)
- size.y = default_h;
- else if (size.y < 0.0f)
- size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
-
- return size;
-}
-
void ImGui::SetCurrentFont(ImFont* font)
{
ImGuiContext& g = *GImGui;
@@ -6722,6 +6358,7 @@ void ImGui::SetCurrentFont(ImFont* font)
ImFontAtlas* atlas = g.Font->ContainerAtlas;
g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
+ g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
g.DrawListSharedData.Font = g.Font;
g.DrawListSharedData.FontSize = g.FontSize;
}
@@ -6746,19 +6383,25 @@ void ImGui::PopFont()
void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
{
- ImGuiWindow* window = GetCurrentWindow();
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ ImGuiItemFlags item_flags = window->DC.ItemFlags;
+ IM_ASSERT(item_flags == g.ItemFlagsStack.back());
if (enabled)
- window->DC.ItemFlags |= option;
+ item_flags |= option;
else
- window->DC.ItemFlags &= ~option;
- window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags);
+ item_flags &= ~option;
+ window->DC.ItemFlags = item_flags;
+ g.ItemFlagsStack.push_back(item_flags);
}
void ImGui::PopItemFlag()
{
- ImGuiWindow* window = GetCurrentWindow();
- window->DC.ItemFlagsStack.pop_back();
- window->DC.ItemFlags = window->DC.ItemFlagsStack.empty() ? ImGuiItemFlags_Default_ : window->DC.ItemFlagsStack.back();
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.
+ g.ItemFlagsStack.pop_back();
+ window->DC.ItemFlags = g.ItemFlagsStack.back();
}
// FIXME: Look into renaming this once we have settled the new Focus/Activation/TabStop system.
@@ -6785,194 +6428,15 @@ void ImGui::PopButtonRepeat()
void ImGui::PushTextWrapPos(float wrap_pos_x)
{
ImGuiWindow* window = GetCurrentWindow();
+ window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
window->DC.TextWrapPos = wrap_pos_x;
- window->DC.TextWrapPosStack.push_back(wrap_pos_x);
}
void ImGui::PopTextWrapPos()
{
ImGuiWindow* window = GetCurrentWindow();
+ window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
window->DC.TextWrapPosStack.pop_back();
- window->DC.TextWrapPos = window->DC.TextWrapPosStack.empty() ? -1.0f : window->DC.TextWrapPosStack.back();
-}
-
-// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
-void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
-{
- ImGuiContext& g = *GImGui;
- ImGuiColorMod backup;
- backup.Col = idx;
- backup.BackupValue = g.Style.Colors[idx];
- g.ColorModifiers.push_back(backup);
- g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
-}
-
-void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
-{
- ImGuiContext& g = *GImGui;
- ImGuiColorMod backup;
- backup.Col = idx;
- backup.BackupValue = g.Style.Colors[idx];
- g.ColorModifiers.push_back(backup);
- g.Style.Colors[idx] = col;
-}
-
-void ImGui::PopStyleColor(int count)
-{
- ImGuiContext& g = *GImGui;
- while (count > 0)
- {
- ImGuiColorMod& backup = g.ColorModifiers.back();
- g.Style.Colors[backup.Col] = backup.BackupValue;
- g.ColorModifiers.pop_back();
- count--;
- }
-}
-
-struct ImGuiStyleVarInfo
-{
- ImGuiDataType Type;
- ImU32 Count;
- ImU32 Offset;
- void* GetVarPtr(ImGuiStyle* style) const { return (void*)((unsigned char*)style + Offset); }
-};
-
-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, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding
- { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
- { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
-};
-
-static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx)
-{
- 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 && var_info->Count == 1)
- {
- ImGuiContext& g = *GImGui;
- float* pvar = (float*)var_info->GetVarPtr(&g.Style);
- g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
- *pvar = val;
- return;
- }
- IM_ASSERT(0 && "Called PushStyleVar() float variant but variable is not a float!");
-}
-
-void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
-{
- const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
- if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
- {
- ImGuiContext& g = *GImGui;
- ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
- g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
- *pvar = val;
- return;
- }
- IM_ASSERT(0 && "Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!");
-}
-
-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);
- 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--;
- }
-}
-
-const char* ImGui::GetStyleColorName(ImGuiCol idx)
-{
- // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
- switch (idx)
- {
- case ImGuiCol_Text: return "Text";
- case ImGuiCol_TextDisabled: return "TextDisabled";
- case ImGuiCol_WindowBg: return "WindowBg";
- case ImGuiCol_ChildBg: return "ChildBg";
- case ImGuiCol_PopupBg: return "PopupBg";
- case ImGuiCol_Border: return "Border";
- case ImGuiCol_BorderShadow: return "BorderShadow";
- case ImGuiCol_FrameBg: return "FrameBg";
- case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
- case ImGuiCol_FrameBgActive: return "FrameBgActive";
- case ImGuiCol_TitleBg: return "TitleBg";
- case ImGuiCol_TitleBgActive: return "TitleBgActive";
- case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
- case ImGuiCol_MenuBarBg: return "MenuBarBg";
- case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
- case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
- case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
- case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
- case ImGuiCol_CheckMark: return "CheckMark";
- case ImGuiCol_SliderGrab: return "SliderGrab";
- case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
- case ImGuiCol_Button: return "Button";
- case ImGuiCol_ButtonHovered: return "ButtonHovered";
- case ImGuiCol_ButtonActive: return "ButtonActive";
- case ImGuiCol_Header: return "Header";
- case ImGuiCol_HeaderHovered: return "HeaderHovered";
- case ImGuiCol_HeaderActive: return "HeaderActive";
- case ImGuiCol_Separator: return "Separator";
- case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
- case ImGuiCol_SeparatorActive: return "SeparatorActive";
- case ImGuiCol_ResizeGrip: return "ResizeGrip";
- case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
- case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
- case ImGuiCol_Tab: return "Tab";
- case ImGuiCol_TabHovered: return "TabHovered";
- case ImGuiCol_TabActive: return "TabActive";
- case ImGuiCol_TabUnfocused: return "TabUnfocused";
- case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
- case ImGuiCol_DockingPreview: return "DockingPreview";
- case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
- case ImGuiCol_PlotLines: return "PlotLines";
- case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
- case ImGuiCol_PlotHistogram: return "PlotHistogram";
- case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
- case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
- case ImGuiCol_DragDropTarget: return "DragDropTarget";
- case ImGuiCol_NavHighlight: return "NavHighlight";
- case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
- case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
- case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
- }
- IM_ASSERT(0);
- return "Unknown";
}
bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
@@ -6988,6 +6452,20 @@ bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
return false;
}
+bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
+{
+ ImGuiContext& g = *GImGui;
+ for (int i = g.Windows.Size - 1; i >= 0; i--)
+ {
+ ImGuiWindow* candidate_window = g.Windows[i];
+ if (candidate_window == potential_above)
+ return true;
+ if (candidate_window == potential_below)
+ return false;
+ }
+ return false;
+}
+
bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
{
IM_ASSERT((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0); // Flags not supported by this function
@@ -7003,11 +6481,11 @@ bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
switch (flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows))
{
case ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows:
- if (g.HoveredWindow == NULL || g.HoveredWindow->RootWindowDockStop != g.CurrentWindow->RootWindowDockStop)
+ if (g.HoveredRootWindow != g.CurrentWindow->RootWindow)
return false;
break;
case ImGuiHoveredFlags_RootWindow:
- if (g.HoveredWindow != g.CurrentWindow->RootWindowDockStop)
+ if (g.HoveredWindow != g.CurrentWindow->RootWindow)
return false;
break;
case ImGuiHoveredFlags_ChildWindows:
@@ -7040,9 +6518,9 @@ bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
switch (flags & (ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows))
{
case ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows:
- return g.NavWindow && g.NavWindow->RootWindowDockStop == g.CurrentWindow->RootWindowDockStop;
+ return g.NavWindow && g.NavWindow->RootWindow == g.CurrentWindow->RootWindow;
case ImGuiFocusedFlags_RootWindow:
- return g.NavWindow == g.CurrentWindow->RootWindowDockStop;
+ return g.NavWindow == g.CurrentWindow->RootWindow;
case ImGuiFocusedFlags_ChildWindows:
return g.NavWindow && IsWindowChildOf(g.NavWindow, g.CurrentWindow);
default:
@@ -7050,24 +6528,12 @@ bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
}
}
-ImGuiID ImGui::GetWindowDockID()
-{
- ImGuiContext& g = *GImGui;
- return g.CurrentWindow->DockId;
-}
-
-bool ImGui::IsWindowDocked()
-{
- ImGuiContext& g = *GImGui;
- return g.CurrentWindow->DockIsActive;
-}
-
// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
-// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmaticaly.
+// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
// If you want a window to never be focused, you may use the e.g. NoInputs flag.
bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
{
- return window->Active && window == window->RootWindowDockStop && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
+ return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
}
float ImGui::GetWindowWidth()
@@ -7139,7 +6605,7 @@ void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond con
if (size.x > 0.0f)
{
window->AutoFitFramesX = 0;
- window->SizeFull.x = ImFloor(size.x);
+ window->SizeFull.x = IM_FLOOR(size.x);
}
else
{
@@ -7149,7 +6615,7 @@ void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond con
if (size.y > 0.0f)
{
window->AutoFitFramesY = 0;
- window->SizeFull.y = ImFloor(size.y);
+ window->SizeFull.y = IM_FLOOR(size.y);
}
else
{
@@ -7180,7 +6646,7 @@ void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond co
window->Collapsed = collapsed;
}
-static void SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
+void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
{
IM_ASSERT(window->HitTestHoleSize.x == 0); // We don't support multiple holes/hit test filters
window->HitTestHoleSize = ImVec2ih(size);
@@ -7236,7 +6702,6 @@ void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pi
g.NextWindowData.PosVal = pos;
g.NextWindowData.PosPivotVal = pivot;
g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
- g.NextWindowData.PosUndock = true;
}
void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
@@ -7263,7 +6728,14 @@ void ImGui::SetNextWindowContentSize(const ImVec2& size)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
- g.NextWindowData.ContentSizeVal = size;
+ g.NextWindowData.ContentSizeVal = ImFloor(size);
+}
+
+void ImGui::SetNextWindowScroll(const ImVec2& scroll)
+{
+ ImGuiContext& g = *GImGui;
+ g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
+ g.NextWindowData.ScrollVal = scroll;
}
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
@@ -7288,120 +6760,12 @@ void ImGui::SetNextWindowBgAlpha(float alpha)
g.NextWindowData.BgAlphaVal = alpha;
}
-void ImGui::SetNextWindowViewport(ImGuiID id)
-{
- ImGuiContext& g = *GImGui;
- g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasViewport;
- g.NextWindowData.ViewportId = id;
-}
-
-void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
-{
- ImGuiContext& g = *GImGui;
- g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasDock;
- g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
- g.NextWindowData.DockId = id;
-}
-
-void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
-{
- ImGuiContext& g = *GImGui;
- IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit
- g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasWindowClass;
- g.NextWindowData.WindowClass = *window_class;
-}
-
-// FIXME: This is in window space (not screen space!). We should try to obsolete all those functions.
-ImVec2 ImGui::GetContentRegionMax()
-{
- ImGuiContext& g = *GImGui;
- ImGuiWindow* window = g.CurrentWindow;
- ImVec2 mx = window->ContentsRegionRect.Max - window->Pos;
- if (window->DC.CurrentColumns)
- mx.x = window->WorkRect.Max.x - window->Pos.x;
- return mx;
-}
-
-// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
-ImVec2 ImGui::GetContentRegionMaxAbs()
-{
- ImGuiContext& g = *GImGui;
- ImGuiWindow* window = g.CurrentWindow;
- ImVec2 mx = window->ContentsRegionRect.Max;
- if (window->DC.CurrentColumns)
- mx.x = window->WorkRect.Max.x;
- return mx;
-}
-
-ImVec2 ImGui::GetContentRegionAvail()
-{
- ImGuiWindow* window = GImGui->CurrentWindow;
- return GetContentRegionMaxAbs() - window->DC.CursorPos;
-}
-
-// In window space (not screen space!)
-ImVec2 ImGui::GetWindowContentRegionMin()
-{
- ImGuiWindow* window = GImGui->CurrentWindow;
- return window->ContentsRegionRect.Min - window->Pos;
-}
-
-ImVec2 ImGui::GetWindowContentRegionMax()
-{
- ImGuiWindow* window = GImGui->CurrentWindow;
- return window->ContentsRegionRect.Max - window->Pos;
-}
-
-float ImGui::GetWindowContentRegionWidth()
-{
- ImGuiWindow* window = GImGui->CurrentWindow;
- return window->ContentsRegionRect.GetWidth();
-}
-
-float ImGui::GetTextLineHeight()
-{
- ImGuiContext& g = *GImGui;
- return g.FontSize;
-}
-
-float ImGui::GetTextLineHeightWithSpacing()
-{
- ImGuiContext& g = *GImGui;
- return g.FontSize + g.Style.ItemSpacing.y;
-}
-
-float ImGui::GetFrameHeight()
-{
- ImGuiContext& g = *GImGui;
- return g.FontSize + g.Style.FramePadding.y * 2.0f;
-}
-
-float ImGui::GetFrameHeightWithSpacing()
-{
- ImGuiContext& g = *GImGui;
- return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
-}
-
ImDrawList* ImGui::GetWindowDrawList()
{
ImGuiWindow* window = GetCurrentWindow();
return window->DrawList;
}
-float ImGui::GetWindowDpiScale()
-{
- ImGuiContext& g = *GImGui;
- IM_ASSERT(g.CurrentViewport != NULL);
- return g.CurrentViewport->DpiScale;
-}
-
-ImGuiViewport* ImGui::GetWindowViewport()
-{
- ImGuiContext& g = *GImGui;
- IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport);
- return g.CurrentViewport;
-}
-
ImFont* ImGui::GetFont()
{
return GImGui->Font;
@@ -7419,12 +6783,545 @@ ImVec2 ImGui::GetFontTexUvWhitePixel()
void ImGui::SetWindowFontScale(float scale)
{
+ IM_ASSERT(scale > 0.0f);
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->FontWindowScale = scale;
g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
}
+void ImGui::ActivateItem(ImGuiID id)
+{
+ ImGuiContext& g = *GImGui;
+ g.NavNextActivateId = id;
+}
+
+void ImGui::PushFocusScope(ImGuiID id)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ g.FocusScopeStack.push_back(window->DC.NavFocusScopeIdCurrent);
+ window->DC.NavFocusScopeIdCurrent = id;
+}
+
+void ImGui::PopFocusScope()
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ IM_ASSERT(g.FocusScopeStack.Size > 0); // Too many PopFocusScope() ?
+ window->DC.NavFocusScopeIdCurrent = g.FocusScopeStack.back();
+ g.FocusScopeStack.pop_back();
+}
+
+void ImGui::SetKeyboardFocusHere(int offset)
+{
+ IM_ASSERT(offset >= -1); // -1 is allowed but not below
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ g.FocusRequestNextWindow = window;
+ g.FocusRequestNextCounterRegular = window->DC.FocusCounterRegular + 1 + offset;
+ g.FocusRequestNextCounterTabStop = 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())
+ SetScrollHereY();
+ }
+}
+
+void ImGui::SetStateStorage(ImGuiStorage* tree)
+{
+ ImGuiWindow* window = GImGui->CurrentWindow;
+ window->DC.StateStorage = tree ? tree : &window->StateStorage;
+}
+
+ImGuiStorage* ImGui::GetStateStorage()
+{
+ ImGuiWindow* window = GImGui->CurrentWindow;
+ return window->DC.StateStorage;
+}
+
+void ImGui::PushID(const char* str_id)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ ImGuiID id = window->GetIDNoKeepAlive(str_id);
+ window->IDStack.push_back(id);
+}
+
+void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ ImGuiID id = window->GetIDNoKeepAlive(str_id_begin, str_id_end);
+ window->IDStack.push_back(id);
+}
+
+void ImGui::PushID(const void* ptr_id)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ ImGuiID id = window->GetIDNoKeepAlive(ptr_id);
+ window->IDStack.push_back(id);
+}
+
+void ImGui::PushID(int int_id)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ ImGuiID id = window->GetIDNoKeepAlive(int_id);
+ window->IDStack.push_back(id);
+}
+
+// Push a given id value ignoring the ID stack as a seed.
+void ImGui::PushOverrideID(ImGuiID id)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ window->IDStack.push_back(id);
+}
+
+// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
+// (note that when using this pattern, TestEngine's "Stack Tool" will tend to not display the intermediate stack level.
+// for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
+ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
+{
+ ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
+ ImGui::KeepAliveID(id);
+#ifdef IMGUI_ENABLE_TEST_ENGINE
+ ImGuiContext& g = *GImGui;
+ IMGUI_TEST_ENGINE_ID_INFO2(id, ImGuiDataType_String, str, str_end);
+#endif
+ return id;
+}
+
+void ImGui::PopID()
+{
+ ImGuiWindow* window = GImGui->CurrentWindow;
+ IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?
+ window->IDStack.pop_back();
+}
+
+ImGuiID ImGui::GetID(const char* str_id)
+{
+ ImGuiWindow* window = GImGui->CurrentWindow;
+ return window->GetID(str_id);
+}
+
+ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
+{
+ ImGuiWindow* window = GImGui->CurrentWindow;
+ return window->GetID(str_id_begin, str_id_end);
+}
+
+ImGuiID ImGui::GetID(const void* ptr_id)
+{
+ ImGuiWindow* window = GImGui->CurrentWindow;
+ return window->GetID(ptr_id);
+}
+
+bool ImGui::IsRectVisible(const ImVec2& size)
+{
+ ImGuiWindow* window = GImGui->CurrentWindow;
+ return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
+}
+
+bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
+{
+ ImGuiWindow* window = GImGui->CurrentWindow;
+ return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
+}
+
+
+//-----------------------------------------------------------------------------
+// [SECTION] ERROR CHECKING
+//-----------------------------------------------------------------------------
+
+// Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
+// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
+// If the user has inconsistent compilation settings, imgui configuration #define, packing pragma, etc. your user code
+// may see different structures than what imgui.cpp sees, which is problematic.
+// We usually require settings to be in imconfig.h to make sure that they are accessible to all compilation units involved with Dear ImGui.
+bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
+{
+ bool error = false;
+ if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
+ if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
+ if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
+ if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
+ if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
+ if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
+ if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
+ return !error;
+}
+
+static void ImGui::ErrorCheckNewFrameSanityChecks()
+{
+ ImGuiContext& g = *GImGui;
+
+ // Check user IM_ASSERT macro
+ // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means you assert macro is incorrectly defined!
+ // If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
+ // This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
+ // #define IM_ASSERT(EXPR) if (SomeCode(EXPR)) SomeMoreCode(); // Wrong!
+ // #define IM_ASSERT(EXPR) do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0) // Correct!
+ if (true) IM_ASSERT(1); else IM_ASSERT(0);
+
+ // Check user data
+ // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
+ IM_ASSERT(g.Initialized);
+ IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!");
+ IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
+ IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!");
+ IM_ASSERT(g.IO.Fonts->Fonts.Size > 0 && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()?");
+ IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded() && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()?");
+ IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!");
+ IM_ASSERT(g.Style.CircleSegmentMaxError > 0.0f && "Invalid style setting!");
+ IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations
+ IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
+ IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
+ for (int n = 0; n < ImGuiKey_COUNT; n++)
+ IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < IM_ARRAYSIZE(g.IO.KeysDown) && "io.KeyMap[] contains an out of bound value (need to be 0..512, or -1 for unmapped key)");
+
+ // Check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only added in 1.60 WIP)
+ if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard)
+ IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
+
+ // Check: the io.ConfigWindowsResizeFromEdges option requires backend to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
+ if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
+ g.IO.ConfigWindowsResizeFromEdges = false;
+}
+
+static void ImGui::ErrorCheckEndFrameSanityChecks()
+{
+ ImGuiContext& g = *GImGui;
+
+ // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
+ // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
+ // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
+ // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
+ // We silently accommodate for this case by ignoring/ the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
+ // while still correctly asserting on mid-frame key press events.
+ const ImGuiKeyModFlags key_mod_flags = GetMergedKeyModFlags();
+ IM_ASSERT((key_mod_flags == 0 || g.IO.KeyMods == key_mod_flags) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
+ IM_UNUSED(key_mod_flags);
+
+ // Recover from errors
+ //ErrorCheckEndFrameRecover();
+
+ // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
+ // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
+ if (g.CurrentWindowStack.Size != 1)
+ {
+ if (g.CurrentWindowStack.Size > 1)
+ {
+ IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
+ while (g.CurrentWindowStack.Size > 1)
+ End();
+ }
+ else
+ {
+ IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
+ }
+ }
+
+ IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
+}
+
+// Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
+// Must be called during or before EndFrame().
+// This is generally flawed as we are not necessarily End/Popping things in the right order.
+// FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
+// FIXME: Can't recover from interleaved BeginTabBar/Begin
+void ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
+{
+ // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
+ ImGuiContext& g = *GImGui;
+ while (g.CurrentWindowStack.Size > 0)
+ {
+#ifdef IMGUI_HAS_TABLE
+ while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
+ {
+ if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name);
+ EndTable();
+ }
+#endif
+ ImGuiWindow* window = g.CurrentWindow;
+ IM_ASSERT(window != NULL);
+ while (g.CurrentTabBar != NULL) //-V1044
+ {
+ if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name);
+ EndTabBar();
+ }
+ while (window->DC.TreeDepth > 0)
+ {
+ if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name);
+ TreePop();
+ }
+ while (g.GroupStack.Size > window->DC.StackSizesOnBegin.SizeOfGroupStack)
+ {
+ if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name);
+ EndGroup();
+ }
+ while (window->IDStack.Size > 1)
+ {
+ if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name);
+ PopID();
+ }
+ while (g.ColorStack.Size > window->DC.StackSizesOnBegin.SizeOfColorStack)
+ {
+ if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col));
+ PopStyleColor();
+ }
+ while (g.StyleVarStack.Size > window->DC.StackSizesOnBegin.SizeOfStyleVarStack)
+ {
+ if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name);
+ PopStyleVar();
+ }
+ while (g.FocusScopeStack.Size > window->DC.StackSizesOnBegin.SizeOfFocusScopeStack)
+ {
+ if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name);
+ PopFocusScope();
+ }
+ if (g.CurrentWindowStack.Size == 1)
+ {
+ IM_ASSERT(g.CurrentWindow->IsFallbackWindow);
+ break;
+ }
+ IM_ASSERT(window == g.CurrentWindow);
+ if (window->Flags & ImGuiWindowFlags_ChildWindow)
+ {
+ if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name);
+ EndChild();
+ }
+ else
+ {
+ if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name);
+ End();
+ }
+ }
+}
+
+// Save current stack sizes for later compare
+void ImGuiStackSizes::SetToCurrentState()
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ SizeOfIDStack = (short)window->IDStack.Size;
+ SizeOfColorStack = (short)g.ColorStack.Size;
+ SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
+ SizeOfFontStack = (short)g.FontStack.Size;
+ SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
+ SizeOfGroupStack = (short)g.GroupStack.Size;
+ SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
+}
+
+// Compare to detect usage errors
+void ImGuiStackSizes::CompareWithCurrentState()
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ IM_UNUSED(window);
+
+ // Window stacks
+ // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
+ IM_ASSERT(SizeOfIDStack == window->IDStack.Size && "PushID/PopID or TreeNode/TreePop Mismatch!");
+
+ // Global stacks
+ // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
+ IM_ASSERT(SizeOfGroupStack == g.GroupStack.Size && "BeginGroup/EndGroup Mismatch!");
+ IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!");
+ IM_ASSERT(SizeOfColorStack >= g.ColorStack.Size && "PushStyleColor/PopStyleColor Mismatch!");
+ IM_ASSERT(SizeOfStyleVarStack >= g.StyleVarStack.Size && "PushStyleVar/PopStyleVar Mismatch!");
+ IM_ASSERT(SizeOfFontStack >= g.FontStack.Size && "PushFont/PopFont Mismatch!");
+ IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size && "PushFocusScope/PopFocusScope Mismatch!");
+}
+
+
+//-----------------------------------------------------------------------------
+// [SECTION] LAYOUT
+//-----------------------------------------------------------------------------
+// - ItemSize()
+// - ItemAdd()
+// - SameLine()
+// - GetCursorScreenPos()
+// - SetCursorScreenPos()
+// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
+// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
+// - GetCursorStartPos()
+// - Indent()
+// - Unindent()
+// - SetNextItemWidth()
+// - PushItemWidth()
+// - PushMultiItemsWidths()
+// - PopItemWidth()
+// - CalcItemWidth()
+// - CalcItemSize()
+// - GetTextLineHeight()
+// - GetTextLineHeightWithSpacing()
+// - GetFrameHeight()
+// - GetFrameHeightWithSpacing()
+// - GetContentRegionMax()
+// - GetContentRegionMaxAbs() [Internal]
+// - GetContentRegionAvail(),
+// - GetWindowContentRegionMin(), GetWindowContentRegionMax()
+// - GetWindowContentRegionWidth()
+// - BeginGroup()
+// - EndGroup()
+// Also see in imgui_widgets: tab bars, columns.
+//-----------------------------------------------------------------------------
+
+// Advance cursor given item size for layout.
+// Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
+// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
+void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ if (window->SkipItems)
+ return;
+
+ // We increase the height in this function to accommodate for baseline offset.
+ // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
+ // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
+ const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
+ const float line_height = ImMax(window->DC.CurrLineSize.y, size.y + offset_to_match_baseline_y);
+
+ // Always align ourselves on pixel boundaries
+ //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
+ window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
+ window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y;
+ window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); // Next line
+ window->DC.CursorPos.y = IM_FLOOR(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y); // Next line
+ window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
+ window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
+ //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
+
+ window->DC.PrevLineSize.y = line_height;
+ window->DC.CurrLineSize.y = 0.0f;
+ window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
+ window->DC.CurrLineTextBaseOffset = 0.0f;
+
+ // Horizontal layout mode
+ if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
+ SameLine();
+}
+
+void ImGui::ItemSize(const ImRect& bb, float text_baseline_y)
+{
+ ItemSize(bb.GetSize(), text_baseline_y);
+}
+
+// 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
+// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
+bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+
+ 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).
+ // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
+ // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
+ window->DC.NavLayerActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
+ if (g.NavId == id || g.NavAnyRequest)
+ if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
+ if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
+ NavProcessItem(window, nav_bb_arg ? *nav_bb_arg : bb, id);
+
+ // [DEBUG] Item Picker tool, when enabling the "extended" version we perform the check in ItemAdd()
+#ifdef IMGUI_DEBUG_TOOL_ITEM_PICKER_EX
+ if (id == g.DebugItemPickerBreakId)
+ {
+ IM_DEBUG_BREAK();
+ g.DebugItemPickerBreakId = 0;
+ }
+#endif
+ }
+
+ // Equivalent to calling SetLastItemData()
+ window->DC.LastItemId = id;
+ window->DC.LastItemRect = bb;
+ window->DC.LastItemStatusFlags = ImGuiItemStatusFlags_None;
+ g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
+
+#ifdef IMGUI_ENABLE_TEST_ENGINE
+ if (id != 0)
+ IMGUI_TEST_ENGINE_ITEM_ADD(nav_bb_arg ? *nav_bb_arg : bb, id);
+#endif
+
+ // Clipping test
+ const bool is_clipped = IsClippedEx(bb, id, false);
+ 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)
+ if (IsMouseHoveringRect(bb.Min, bb.Max))
+ window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HoveredRect;
+ return true;
+}
+
+// Gets back to previous line and continue with horizontal layout
+// offset_from_start_x == 0 : follow right after previous item
+// offset_from_start_x != 0 : align to specified x position (relative to window/group left)
+// spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0
+// spacing_w >= 0 : enforce spacing amount
+void ImGui::SameLine(float offset_from_start_x, float spacing_w)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ if (window->SkipItems)
+ return;
+
+ ImGuiContext& g = *GImGui;
+ if (offset_from_start_x != 0.0f)
+ {
+ if (spacing_w < 0.0f) spacing_w = 0.0f;
+ window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
+ window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
+ }
+ else
+ {
+ if (spacing_w < 0.0f) spacing_w = g.Style.ItemSpacing.x;
+ window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
+ window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
+ }
+ window->DC.CurrLineSize = window->DC.PrevLineSize;
+ window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
+}
+
+ImVec2 ImGui::GetCursorScreenPos()
+{
+ ImGuiWindow* window = GetCurrentWindowRead();
+ return window->DC.CursorPos;
+}
+
+void ImGui::SetCursorScreenPos(const ImVec2& pos)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ window->DC.CursorPos = pos;
+ window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
+}
+
// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
ImVec2 ImGui::GetCursorPos()
@@ -7472,139 +7369,190 @@ ImVec2 ImGui::GetCursorStartPos()
return window->DC.CursorStartPos - window->Pos;
}
-ImVec2 ImGui::GetCursorScreenPos()
+void ImGui::Indent(float indent_w)
{
- ImGuiWindow* window = GetCurrentWindowRead();
- return window->DC.CursorPos;
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = GetCurrentWindow();
+ window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
+ window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
}
-void ImGui::SetCursorScreenPos(const ImVec2& pos)
+void ImGui::Unindent(float indent_w)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = GetCurrentWindow();
+ window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
+ window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
+}
+
+// Affect large frame+labels widgets only.
+void ImGui::SetNextItemWidth(float item_width)
+{
+ ImGuiContext& g = *GImGui;
+ g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
+ g.NextItemData.Width = item_width;
+}
+
+// FIXME: Remove the == 0.0f behavior?
+void ImGui::PushItemWidth(float item_width)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
+ window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
+ g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
+}
+
+void ImGui::PushMultiItemsWidths(int components, float w_full)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ const ImGuiStyle& style = g.Style;
+ const float w_item_one = ImMax(1.0f, IM_FLOOR((w_full - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components));
+ const float w_item_last = ImMax(1.0f, IM_FLOOR(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components - 1)));
+ window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
+ window->DC.ItemWidthStack.push_back(w_item_last);
+ for (int i = 0; i < components - 2; i++)
+ window->DC.ItemWidthStack.push_back(w_item_one);
+ window->DC.ItemWidth = (components == 1) ? w_item_last : w_item_one;
+ g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
+}
+
+void ImGui::PopItemWidth()
{
ImGuiWindow* window = GetCurrentWindow();
- window->DC.CursorPos = pos;
- window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
+ window->DC.ItemWidth = window->DC.ItemWidthStack.back();
+ window->DC.ItemWidthStack.pop_back();
}
-void ImGui::ActivateItem(ImGuiID id)
-{
- ImGuiContext& g = *GImGui;
- g.NavNextActivateId = id;
-}
-
-void ImGui::SetKeyboardFocusHere(int offset)
-{
- IM_ASSERT(offset >= -1); // -1 is allowed but not below
- ImGuiContext& g = *GImGui;
- ImGuiWindow* window = g.CurrentWindow;
- g.FocusRequestNextWindow = window;
- g.FocusRequestNextCounterAll = window->DC.FocusCounterAll + 1 + offset;
- g.FocusRequestNextCounterTab = INT_MAX;
-}
-
-void ImGui::SetItemDefaultFocus()
+// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
+// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
+float ImGui::CalcItemWidth()
{
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)
+ float w;
+ if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
+ w = g.NextItemData.Width;
+ else
+ w = window->DC.ItemWidth;
+ if (w < 0.0f)
{
- 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())
- SetScrollHereY();
+ float region_max_x = GetContentRegionMaxAbs().x;
+ w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
}
+ w = IM_FLOOR(w);
+ return w;
}
-void ImGui::SetStateStorage(ImGuiStorage* tree)
+// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
+// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
+// Note that only CalcItemWidth() is publicly exposed.
+// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
+ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
{
ImGuiWindow* window = GImGui->CurrentWindow;
- window->DC.StateStorage = tree ? tree : &window->StateStorage;
+
+ ImVec2 region_max;
+ if (size.x < 0.0f || size.y < 0.0f)
+ region_max = GetContentRegionMaxAbs();
+
+ if (size.x == 0.0f)
+ size.x = default_w;
+ else if (size.x < 0.0f)
+ size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
+
+ if (size.y == 0.0f)
+ size.y = default_h;
+ else if (size.y < 0.0f)
+ size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
+
+ return size;
}
-ImGuiStorage* ImGui::GetStateStorage()
+float ImGui::GetTextLineHeight()
{
- ImGuiWindow* window = GImGui->CurrentWindow;
- return window->DC.StateStorage;
+ ImGuiContext& g = *GImGui;
+ return g.FontSize;
}
-void ImGui::PushID(const char* str_id)
+float ImGui::GetTextLineHeightWithSpacing()
{
- ImGuiWindow* window = GImGui->CurrentWindow;
- window->IDStack.push_back(window->GetIDNoKeepAlive(str_id));
+ ImGuiContext& g = *GImGui;
+ return g.FontSize + g.Style.ItemSpacing.y;
}
-void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
+float ImGui::GetFrameHeight()
{
- ImGuiWindow* window = GImGui->CurrentWindow;
- window->IDStack.push_back(window->GetIDNoKeepAlive(str_id_begin, str_id_end));
+ ImGuiContext& g = *GImGui;
+ return g.FontSize + g.Style.FramePadding.y * 2.0f;
}
-void ImGui::PushID(const void* ptr_id)
+float ImGui::GetFrameHeightWithSpacing()
{
- ImGuiWindow* window = GImGui->CurrentWindow;
- window->IDStack.push_back(window->GetIDNoKeepAlive(ptr_id));
+ ImGuiContext& g = *GImGui;
+ return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
}
-void ImGui::PushID(int int_id)
+// FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW "WORK RECT" API. Thanks for your patience!
+
+// FIXME: This is in window space (not screen space!).
+ImVec2 ImGui::GetContentRegionMax()
{
- ImGuiWindow* window = GImGui->CurrentWindow;
- window->IDStack.push_back(window->GetIDNoKeepAlive(int_id));
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ ImVec2 mx = window->ContentRegionRect.Max - window->Pos;
+ if (window->DC.CurrentColumns || g.CurrentTable)
+ mx.x = window->WorkRect.Max.x - window->Pos.x;
+ return mx;
}
-// Push a given id value ignoring the ID stack as a seed.
-void ImGui::PushOverrideID(ImGuiID id)
+// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
+ImVec2 ImGui::GetContentRegionMaxAbs()
{
- ImGuiWindow* window = GImGui->CurrentWindow;
- window->IDStack.push_back(id);
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ ImVec2 mx = window->ContentRegionRect.Max;
+ if (window->DC.CurrentColumns || g.CurrentTable)
+ mx.x = window->WorkRect.Max.x;
+ return mx;
}
-void ImGui::PopID()
+ImVec2 ImGui::GetContentRegionAvail()
{
ImGuiWindow* window = GImGui->CurrentWindow;
- window->IDStack.pop_back();
+ return GetContentRegionMaxAbs() - window->DC.CursorPos;
}
-ImGuiID ImGui::GetID(const char* str_id)
+// In window space (not screen space!)
+ImVec2 ImGui::GetWindowContentRegionMin()
{
ImGuiWindow* window = GImGui->CurrentWindow;
- return window->GetID(str_id);
+ return window->ContentRegionRect.Min - window->Pos;
}
-ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
+ImVec2 ImGui::GetWindowContentRegionMax()
{
ImGuiWindow* window = GImGui->CurrentWindow;
- return window->GetID(str_id_begin, str_id_end);
+ return window->ContentRegionRect.Max - window->Pos;
}
-ImGuiID ImGui::GetID(const void* ptr_id)
+float ImGui::GetWindowContentRegionWidth()
{
ImGuiWindow* window = GImGui->CurrentWindow;
- return window->GetID(ptr_id);
-}
-
-bool ImGui::IsRectVisible(const ImVec2& size)
-{
- ImGuiWindow* window = GImGui->CurrentWindow;
- return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
-}
-
-bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
-{
- ImGuiWindow* window = GImGui->CurrentWindow;
- return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
+ return window->ContentRegionRect.GetWidth();
}
// 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.)
+// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
void ImGui::BeginGroup()
{
ImGuiContext& g = *GImGui;
- ImGuiWindow* window = GetCurrentWindow();
+ ImGuiWindow* window = g.CurrentWindow;
- window->DC.GroupStack.resize(window->DC.GroupStack.Size + 1);
- ImGuiGroupData& group_data = window->DC.GroupStack.back();
+ g.GroupStack.resize(g.GroupStack.Size + 1);
+ ImGuiGroupData& group_data = g.GroupStack.back();
+ group_data.WindowID = window->ID;
group_data.BackupCursorPos = window->DC.CursorPos;
group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
group_data.BackupIndent = window->DC.Indent;
@@ -7626,10 +7574,11 @@ void ImGui::BeginGroup()
void ImGui::EndGroup()
{
ImGuiContext& g = *GImGui;
- ImGuiWindow* window = GetCurrentWindow();
- IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls
+ ImGuiWindow* window = g.CurrentWindow;
+ IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
- ImGuiGroupData& group_data = window->DC.GroupStack.back();
+ ImGuiGroupData& group_data = g.GroupStack.back();
+ IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
@@ -7644,7 +7593,7 @@ void ImGui::EndGroup()
if (!group_data.EmitItem)
{
- window->DC.GroupStack.pop_back();
+ g.GroupStack.pop_back();
return;
}
@@ -7655,9 +7604,9 @@ void ImGui::EndGroup()
// If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
// It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
// Also if you grep for LastItemId you'll notice it is only used in that context.
- // (The tests not symmetrical because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
+ // (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
- const bool group_contains_prev_active_id = !group_data.BackupActiveIdPreviousFrameIsAlive && g.ActiveIdPreviousFrameIsAlive;
+ const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
if (group_contains_curr_active_id)
window->DC.LastItemId = g.ActiveId;
else if (group_contains_prev_active_id)
@@ -7673,86 +7622,54 @@ void ImGui::EndGroup()
if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Deactivated;
- window->DC.GroupStack.pop_back();
+ g.GroupStack.pop_back();
//window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug]
}
-// Gets back to previous line and continue with horizontal layout
-// offset_from_start_x == 0 : follow right after previous item
-// offset_from_start_x != 0 : align to specified x position (relative to window/group left)
-// spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0
-// spacing_w >= 0 : enforce spacing amount
-void ImGui::SameLine(float offset_from_start_x, float spacing_w)
-{
- ImGuiWindow* window = GetCurrentWindow();
- if (window->SkipItems)
- return;
-
- ImGuiContext& g = *GImGui;
- if (offset_from_start_x != 0.0f)
- {
- if (spacing_w < 0.0f) spacing_w = 0.0f;
- window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
- window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
- }
- else
- {
- if (spacing_w < 0.0f) spacing_w = g.Style.ItemSpacing.x;
- window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
- window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
- }
- window->DC.CurrLineSize = window->DC.PrevLineSize;
- window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
-}
-
-void ImGui::Indent(float indent_w)
-{
- ImGuiContext& g = *GImGui;
- ImGuiWindow* window = GetCurrentWindow();
- window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
- window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
-}
-
-void ImGui::Unindent(float indent_w)
-{
- ImGuiContext& g = *GImGui;
- ImGuiWindow* window = GetCurrentWindow();
- window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
- window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
-}
-
//-----------------------------------------------------------------------------
// [SECTION] SCROLLING
//-----------------------------------------------------------------------------
-static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges)
+// Helper to snap on edges when aiming at an item very close to the edge,
+// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
+// When we refactor the scrolling API this may be configurable with a flag?
+// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
+static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
+{
+ if (target <= snap_min + snap_threshold)
+ return ImLerp(snap_min, target, center_ratio);
+ if (target >= snap_max - snap_threshold)
+ return ImLerp(target, snap_max, center_ratio);
+ return target;
+}
+
+static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
{
- ImGuiContext& g = *GImGui;
ImVec2 scroll = window->Scroll;
if (window->ScrollTarget.x < FLT_MAX)
{
- float cr_x = window->ScrollTargetCenterRatio.x;
- float target_x = window->ScrollTarget.x;
- if (snap_on_edges && cr_x <= 0.0f && target_x <= window->WindowPadding.x)
- target_x = 0.0f;
- else if (snap_on_edges && cr_x >= 1.0f && target_x >= window->ContentSize.x + window->WindowPadding.x + g.Style.ItemSpacing.x)
- target_x = window->ContentSize.x + window->WindowPadding.x * 2.0f;
- scroll.x = target_x - cr_x * (window->SizeFull.x - window->ScrollbarSizes.x);
+ float center_x_ratio = window->ScrollTargetCenterRatio.x;
+ float scroll_target_x = window->ScrollTarget.x;
+ float snap_x_min = 0.0f;
+ float snap_x_max = window->ScrollMax.x + window->Size.x;
+ if (window->ScrollTargetEdgeSnapDist.x > 0.0f)
+ scroll_target_x = CalcScrollEdgeSnap(scroll_target_x, snap_x_min, snap_x_max, window->ScrollTargetEdgeSnapDist.x, center_x_ratio);
+ scroll.x = scroll_target_x - center_x_ratio * (window->SizeFull.x - window->ScrollbarSizes.x);
}
if (window->ScrollTarget.y < FLT_MAX)
{
- // 'snap_on_edges' allows for a discontinuity at the edge of scrolling limits to take account of WindowPadding so that scrolling to make the last item visible scroll far enough to see the padding.
float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
- float cr_y = window->ScrollTargetCenterRatio.y;
- float target_y = window->ScrollTarget.y;
- if (snap_on_edges && cr_y <= 0.0f && target_y <= window->WindowPadding.y)
- target_y = 0.0f;
- if (snap_on_edges && cr_y >= 1.0f && target_y >= window->ContentSize.y + window->WindowPadding.y + g.Style.ItemSpacing.y)
- target_y = window->ContentSize.y + window->WindowPadding.y * 2.0f;
- scroll.y = target_y - cr_y * (window->SizeFull.y - window->ScrollbarSizes.y - decoration_up_height);
+ float center_y_ratio = window->ScrollTargetCenterRatio.y;
+ float scroll_target_y = window->ScrollTarget.y;
+ float snap_y_min = 0.0f;
+ float snap_y_max = window->ScrollMax.y + window->Size.y - decoration_up_height;
+ if (window->ScrollTargetEdgeSnapDist.y > 0.0f)
+ scroll_target_y = CalcScrollEdgeSnap(scroll_target_y, snap_y_min, snap_y_max, window->ScrollTargetEdgeSnapDist.y, center_y_ratio);
+ scroll.y = scroll_target_y - center_y_ratio * (window->SizeFull.y - window->ScrollbarSizes.y - decoration_up_height);
}
- scroll = ImMax(scroll, ImVec2(0.0f, 0.0f));
+ scroll.x = IM_FLOOR(ImMax(scroll.x, 0.0f));
+ scroll.y = IM_FLOOR(ImMax(scroll.y, 0.0f));
if (!window->Collapsed && !window->SkipItems)
{
scroll.x = ImMin(scroll.x, window->ScrollMax.x);
@@ -7772,7 +7689,7 @@ ImVec2 ImGui::ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_
if (!window_rect.Contains(item_rect))
{
if (window->ScrollbarX && item_rect.Min.x < window_rect.Min.x)
- SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x + g.Style.ItemSpacing.x, 0.0f);
+ SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x - g.Style.ItemSpacing.x, 0.0f);
else if (window->ScrollbarX && item_rect.Max.x >= window_rect.Max.x)
SetScrollFromPosX(window, item_rect.Max.x - window->Pos.x + g.Style.ItemSpacing.x, 1.0f);
if (item_rect.Min.y < window_rect.Min.y)
@@ -7780,7 +7697,7 @@ ImVec2 ImGui::ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_
else if (item_rect.Max.y >= window_rect.Max.y)
SetScrollFromPosY(window, item_rect.Max.y - window->Pos.y + g.Style.ItemSpacing.y, 1.0f);
- ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window, false);
+ ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
delta_scroll = next_scroll - window->Scroll;
}
@@ -7815,49 +7732,57 @@ float ImGui::GetScrollMaxY()
return window->ScrollMax.y;
}
-void ImGui::SetScrollX(float scroll_x)
+void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
{
- ImGuiWindow* window = GetCurrentWindow();
window->ScrollTarget.x = scroll_x;
window->ScrollTargetCenterRatio.x = 0.0f;
+ window->ScrollTargetEdgeSnapDist.x = 0.0f;
+}
+
+void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
+{
+ window->ScrollTarget.y = scroll_y;
+ window->ScrollTargetCenterRatio.y = 0.0f;
+ window->ScrollTargetEdgeSnapDist.y = 0.0f;
+}
+
+void ImGui::SetScrollX(float scroll_x)
+{
+ ImGuiContext& g = *GImGui;
+ SetScrollX(g.CurrentWindow, scroll_x);
}
void ImGui::SetScrollY(float scroll_y)
{
- ImGuiWindow* window = GetCurrentWindow();
- window->ScrollTarget.y = scroll_y;
- window->ScrollTargetCenterRatio.y = 0.0f;
+ ImGuiContext& g = *GImGui;
+ SetScrollY(g.CurrentWindow, scroll_y);
}
-void ImGui::SetScrollX(ImGuiWindow* window, float new_scroll_x)
-{
- window->ScrollTarget.x = new_scroll_x;
- window->ScrollTargetCenterRatio.x = 0.0f;
-}
-
-void ImGui::SetScrollY(ImGuiWindow* window, float new_scroll_y)
-{
- window->ScrollTarget.y = new_scroll_y;
- window->ScrollTargetCenterRatio.y = 0.0f;
-}
-
-
+// Note that a local position will vary depending on initial scroll value,
+// This is a little bit confusing so bear with us:
+// - local_pos = (absolution_pos - window->Pos)
+// - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
+// and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
+// - They mostly exists because of legacy API.
+// Following the rules above, when trying to work with scrolling code, consider that:
+// - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
+// - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
+// We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size
void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
{
- // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size
IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
- window->ScrollTarget.x = IM_FLOOR(local_x + window->Scroll.x);
+ window->ScrollTarget.x = IM_FLOOR(local_x + window->Scroll.x); // Convert local position to scroll offset
window->ScrollTargetCenterRatio.x = center_x_ratio;
+ window->ScrollTargetEdgeSnapDist.x = 0.0f;
}
void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
{
- // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size
IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
- const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
- local_y -= decoration_up_height;
- window->ScrollTarget.y = IM_FLOOR(local_y + window->Scroll.y);
+ local_y -= window->TitleBarHeight() + window->MenuBarHeight(); // FIXME: Would be nice to have a more standardized access to our scrollable/client rect
+ window->ScrollTarget.y = IM_FLOOR(local_y + window->Scroll.y); // Convert local position to scroll offset
window->ScrollTargetCenterRatio.y = center_y_ratio;
+ window->ScrollTargetEdgeSnapDist.y = 0.0f;
}
void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
@@ -7877,10 +7802,12 @@ void ImGui::SetScrollHereX(float center_x_ratio)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
- float target_x = window->DC.LastItemRect.Min.x - window->Pos.x; // Left of last item, in window space
- float last_item_width = window->DC.LastItemRect.GetWidth();
- target_x += (last_item_width * center_x_ratio) + (g.Style.ItemSpacing.x * (center_x_ratio - 0.5f) * 2.0f); // Precisely aim before, in the middle or after the last item.
- SetScrollFromPosX(target_x, center_x_ratio);
+ float spacing_x = g.Style.ItemSpacing.x;
+ float target_pos_x = ImLerp(window->DC.LastItemRect.Min.x - spacing_x, window->DC.LastItemRect.Max.x + spacing_x, center_x_ratio);
+ SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
+
+ // Tweak: snap on edges when aiming at an item very close to the edge
+ window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
}
// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
@@ -7888,9 +7815,12 @@ void ImGui::SetScrollHereY(float center_y_ratio)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
- float target_y = window->DC.CursorPosPrevLine.y - window->Pos.y; // Top of last item, in window space
- target_y += (window->DC.PrevLineSize.y * center_y_ratio) + (g.Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line.
- SetScrollFromPosY(target_y, center_y_ratio);
+ float spacing_y = g.Style.ItemSpacing.y;
+ float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
+ SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
+
+ // Tweak: snap on edges when aiming at an item very close to the edge
+ window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
}
//-----------------------------------------------------------------------------
@@ -7898,9 +7828,15 @@ void ImGui::SetScrollHereY(float center_y_ratio)
//-----------------------------------------------------------------------------
void ImGui::BeginTooltip()
+{
+ BeginTooltipEx(ImGuiWindowFlags_None, ImGuiTooltipFlags_None);
+}
+
+void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, ImGuiTooltipFlags tooltip_flags)
{
ImGuiContext& g = *GImGui;
- if (g.DragDropWithinSourceOrTarget)
+
+ if (g.DragDropWithinSource || g.DragDropWithinTarget)
{
// The default tooltip position is a little offset to give space to see the context menu (it's also clamped within the current viewport/monitor)
// In the context of a dragging tooltip we try to reduce that offset and we enforce following the cursor.
@@ -7910,30 +7846,21 @@ void ImGui::BeginTooltip()
SetNextWindowPos(tooltip_pos);
SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
//PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
- BeginTooltipEx(0, true);
+ tooltip_flags |= ImGuiTooltipFlags_OverridePreviousTooltip;
}
- else
- {
- BeginTooltipEx(0, false);
- }
-}
-// Not exposed publicly as BeginTooltip() because bool parameters are evil. Let's see if other needs arise first.
-void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, bool override_previous_tooltip)
-{
- ImGuiContext& g = *GImGui;
char window_name[16];
ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
- if (override_previous_tooltip)
+ if (tooltip_flags & ImGuiTooltipFlags_OverridePreviousTooltip)
if (ImGuiWindow* window = FindWindowByName(window_name))
if (window->Active)
{
// Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
window->Hidden = true;
- window->HiddenFramesCanSkipItems = 1;
+ window->HiddenFramesCanSkipItems = 1; // FIXME: This may not be necessary?
ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
}
- ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoInputs|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoDocking;
+ ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize;
Begin(window_name, NULL, flags | extra_flags);
}
@@ -7945,11 +7872,7 @@ void ImGui::EndTooltip()
void ImGui::SetTooltipV(const char* fmt, va_list args)
{
- ImGuiContext& g = *GImGui;
- if (g.DragDropWithinSourceOrTarget)
- BeginTooltip();
- else
- BeginTooltipEx(0, true);
+ BeginTooltipEx(0, ImGuiTooltipFlags_OverridePreviousTooltip);
TextV(fmt, args);
EndTooltip();
}
@@ -7966,43 +7889,77 @@ void ImGui::SetTooltip(const char* fmt, ...)
// [SECTION] POPUPS
//-----------------------------------------------------------------------------
-bool ImGui::IsPopupOpen(ImGuiID id)
+// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
+bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
{
ImGuiContext& g = *GImGui;
- return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
+ if (popup_flags & ImGuiPopupFlags_AnyPopupId)
+ {
+ // Return true if any popup is open at the current BeginPopup() level of the popup stack
+ // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
+ IM_ASSERT(id == 0);
+ if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
+ return g.OpenPopupStack.Size > 0;
+ else
+ return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
+ }
+ else
+ {
+ if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
+ {
+ // Return true if the popup is open anywhere in the popup stack
+ for (int n = 0; n < g.OpenPopupStack.Size; n++)
+ if (g.OpenPopupStack[n].PopupId == id)
+ return true;
+ return false;
+ }
+ else
+ {
+ // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
+ return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
+ }
+ }
}
-bool ImGui::IsPopupOpen(const char* str_id)
+bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
{
ImGuiContext& g = *GImGui;
- return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == g.CurrentWindow->GetID(str_id);
+ ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
+ if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
+ IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
+ return IsPopupOpen(id, popup_flags);
}
ImGuiWindow* ImGui::GetTopMostPopupModal()
{
ImGuiContext& g = *GImGui;
- for (int n = g.OpenPopupStack.Size-1; n >= 0; n--)
+ for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
if (popup->Flags & ImGuiWindowFlags_Modal)
return popup;
return NULL;
}
-void ImGui::OpenPopup(const char* str_id)
+void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
{
ImGuiContext& g = *GImGui;
- OpenPopupEx(g.CurrentWindow->GetID(str_id));
+ OpenPopupEx(g.CurrentWindow->GetID(str_id), popup_flags);
}
// 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)
+void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* parent_window = g.CurrentWindow;
- int current_stack_size = g.BeginPopupStack.Size;
+ const int current_stack_size = g.BeginPopupStack.Size;
+
+ if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
+ if (IsPopupOpen(0u, ImGuiPopupFlags_AnyPopupId))
+ return;
+
ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
popup_ref.PopupId = id;
popup_ref.Window = NULL;
@@ -8012,7 +7969,7 @@ void ImGui::OpenPopupEx(ImGuiID id)
popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
- //IMGUI_DEBUG_LOG("OpenPopupEx(0x%08X)\n", g.FrameCount, id);
+ IMGUI_DEBUG_LOG_POPUP("OpenPopupEx(0x%08X)\n", id);
if (g.OpenPopupStack.Size < current_stack_size + 1)
{
g.OpenPopupStack.push_back(popup_ref);
@@ -8029,8 +7986,8 @@ void ImGui::OpenPopupEx(ImGuiID id)
else
{
// Close child popups if any, then flag popup for open/reopen
- g.OpenPopupStack.resize(current_stack_size + 1);
- g.OpenPopupStack[current_stack_size] = popup_ref;
+ ClosePopupToLevel(current_stack_size, false);
+ g.OpenPopupStack.push_back(popup_ref);
}
// When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
@@ -8040,13 +7997,14 @@ void ImGui::OpenPopupEx(ImGuiID id)
}
}
+// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
+// This function closes any popups that are over 'ref_window'.
void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
{
ImGuiContext& g = *GImGui;
- if (g.OpenPopupStack.empty())
+ if (g.OpenPopupStack.Size == 0)
return;
- // When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
// Don't close our own child popup windows.
int popup_count_to_keep = 0;
if (ref_window)
@@ -8061,19 +8019,26 @@ void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to
if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
continue;
- // Trim the stack when popups are not direct descendant of the reference window (the reference window is often the NavWindow)
- bool popup_or_descendent_is_ref_window = false;
- for (int m = popup_count_to_keep; m < g.OpenPopupStack.Size && !popup_or_descendent_is_ref_window; m++)
- if (ImGuiWindow* popup_window = g.OpenPopupStack[m].Window)
+ // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
+ // - With this stack of window, clicking/focusing Popup1 will close Popup2 and Popup3:
+ // Window -> Popup1 -> Popup2 -> Popup3
+ // - Each popups may contain child windows, which is why we compare ->RootWindow!
+ // Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
+ bool ref_window_is_descendent_of_popup = false;
+ for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
+ if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
if (popup_window->RootWindow == ref_window->RootWindow)
- popup_or_descendent_is_ref_window = true;
- if (!popup_or_descendent_is_ref_window)
+ {
+ ref_window_is_descendent_of_popup = true;
+ break;
+ }
+ if (!ref_window_is_descendent_of_popup)
break;
}
}
if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
{
- //IMGUI_DEBUG_LOG("ClosePopupsOverWindow(%s) -> ClosePopupToLevel(%d)\n", ref_window->Name, popup_count_to_keep);
+ IMGUI_DEBUG_LOG_POPUP("ClosePopupsOverWindow(\"%s\") -> ClosePopupToLevel(%d)\n", ref_window->Name, popup_count_to_keep);
ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
}
}
@@ -8081,7 +8046,10 @@ void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to
void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
{
ImGuiContext& g = *GImGui;
+ IMGUI_DEBUG_LOG_POPUP("ClosePopupToLevel(%d), restore_focus_to_window_under_popup=%d\n", remaining, restore_focus_to_window_under_popup);
IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
+
+ // Trim open popup stack
ImGuiWindow* focus_window = g.OpenPopupStack[remaining].SourceWindow;
ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window;
g.OpenPopupStack.resize(remaining);
@@ -8095,7 +8063,7 @@ void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_
}
else
{
- if (g.NavLayer == 0 && focus_window)
+ if (g.NavLayer == ImGuiNavLayer_Main && focus_window)
focus_window = NavRestoreLastChildNavWindow(focus_window);
FocusWindow(focus_window);
}
@@ -8123,7 +8091,7 @@ void ImGui::CloseCurrentPopup()
break;
popup_idx--;
}
- //IMGUI_DEBUG_LOG("CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
+ IMGUI_DEBUG_LOG_POPUP("CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
ClosePopupToLevel(popup_idx, true);
// A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
@@ -8133,10 +8101,11 @@ void ImGui::CloseCurrentPopup()
window->DC.NavHideHighlightOneFrame = true;
}
+// Attention! BeginPopup() adds default flags which BeginPopupEx()!
bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
- if (!IsPopupOpen(id))
+ if (!IsPopupOpen(id, ImGuiPopupFlags_None))
{
g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
return false;
@@ -8148,7 +8117,7 @@ bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags)
else
ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
- flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking;
+ flags |= ImGuiWindowFlags_Popup;
bool is_open = Begin(name, NULL, flags);
if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
EndPopup();
@@ -8175,21 +8144,19 @@ bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags fla
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const ImGuiID id = window->GetID(name);
- if (!IsPopupOpen(id))
+ if (!IsPopupOpen(id, ImGuiPopupFlags_None))
{
g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
return false;
}
- // Center modal windows by default
+ // Center modal windows by default for increased visibility
+ // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
// FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
- {
- ImGuiViewportP* viewport = window->WasActive ? window->Viewport : (ImGuiViewportP*)GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport?
- SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
- }
+ SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
- flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoDocking;
+ flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse;
const bool is_open = Begin(name, p_open, flags);
if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
{
@@ -8204,69 +8171,82 @@ bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags fla
void ImGui::EndPopup()
{
ImGuiContext& g = *GImGui;
- IM_ASSERT(g.CurrentWindow->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
+ ImGuiWindow* window = g.CurrentWindow;
+ IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
IM_ASSERT(g.BeginPopupStack.Size > 0);
// Make all menus and popups wrap around for now, may need to expose that policy.
- NavMoveRequestTryWrapping(g.CurrentWindow, ImGuiNavMoveFlags_LoopY);
+ if (g.NavWindow == window)
+ NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
+ // Child-popups don't need to be laid out
+ IM_ASSERT(g.WithinEndChild == false);
+ if (window->Flags & ImGuiWindowFlags_ChildWindow)
+ g.WithinEndChild = true;
End();
+ g.WithinEndChild = false;
}
-bool ImGui::OpenPopupOnItemClick(const char* str_id, int mouse_button)
+// Helper to open a popup if mouse button is released over the item
+// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
+void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
{
ImGuiWindow* window = GImGui->CurrentWindow;
+ int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
{
ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
- OpenPopupEx(id);
- return true;
+ OpenPopupEx(id, popup_flags);
}
- return false;
}
// This is a helper to handle the simplest case of associating one named popup to one given widget.
-// You may want to handle this on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
-// You can pass a NULL str_id to use the identifier of the last item.
-bool ImGui::BeginPopupContextItem(const char* str_id, int mouse_button)
+// - You can pass a NULL str_id to use the identifier of the last item.
+// - You may want to handle this on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
+// - This is essentially the same as calling OpenPopupOnItemClick() + BeginPopup() but written to avoid
+// computing the ID twice because BeginPopupContextXXX functions may be called very frequently.
+bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
{
ImGuiWindow* window = GImGui->CurrentWindow;
if (window->SkipItems)
return false;
ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
+ int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
- OpenPopupEx(id);
- return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
+ OpenPopupEx(id, popup_flags);
+ return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
}
-bool ImGui::BeginPopupContextWindow(const char* str_id, int mouse_button, bool also_over_items)
+bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
{
+ ImGuiWindow* window = GImGui->CurrentWindow;
if (!str_id)
str_id = "window_context";
- ImGuiID id = GImGui->CurrentWindow->GetID(str_id);
+ ImGuiID id = window->GetID(str_id);
+ int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
- if (also_over_items || !IsAnyItemHovered())
- OpenPopupEx(id);
- return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
+ if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
+ OpenPopupEx(id, popup_flags);
+ return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
}
-bool ImGui::BeginPopupContextVoid(const char* str_id, int mouse_button)
+bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
{
+ ImGuiWindow* window = GImGui->CurrentWindow;
if (!str_id)
str_id = "void_context";
- ImGuiID id = GImGui->CurrentWindow->GetID(str_id);
+ ImGuiID id = window->GetID(str_id);
+ int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
- OpenPopupEx(id);
- return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
+ if (GetTopMostPopupModal() == NULL)
+ OpenPopupEx(id, popup_flags);
+ return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
}
// 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.
-// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
-// information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
-// this allows us to have tooltips/popups displayed out of the parent viewport.)
ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
{
ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
@@ -8294,26 +8274,47 @@ ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& s
}
}
- // 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++)
+ // Tooltip and Default popup policy
+ // (Always first try the direction we used on the last frame, if any)
+ if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
{
- const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
- if (n != -1 && dir == *last_dir) // Already tried this direction?
- continue;
- float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
- float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
- if (avail_w < size.x || avail_h < size.y)
- continue;
- ImVec2 pos;
- pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
- pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
- *last_dir = dir;
- return pos;
+ 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?
+ continue;
+
+ const float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
+ const float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
+
+ // If there not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width)
+ if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
+ continue;
+ if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
+ continue;
+
+ ImVec2 pos;
+ pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
+ pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
+
+ // Clamp top-left corner of popup
+ pos.x = ImMax(pos.x, r_outer.Min.x);
+ pos.y = ImMax(pos.y, r_outer.Min.y);
+
+ *last_dir = dir;
+ return pos;
+ }
}
- // Fallback, try to keep within display
+ // Fallback when not enough room:
*last_dir = ImGuiDir_None;
+
+ // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
+ if (policy == ImGuiPopupPositionPolicy_Tooltip)
+ return ref_pos + ImVec2(2, 2);
+
+ // Otherwise try to keep within display
ImVec2 pos = ref_pos;
pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
@@ -8322,21 +8323,9 @@ ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& s
ImRect ImGui::GetWindowAllowedExtentRect(ImGuiWindow* window)
{
- ImGuiContext& g = *GImGui;
- ImRect r_screen;
- if (window->ViewportAllowPlatformMonitorExtend >= 0)
- {
- // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
- const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend];
- r_screen.Min = monitor.WorkPos;
- r_screen.Max = monitor.WorkPos + monitor.WorkSize;
- }
- else
- {
- r_screen.Min = window->Viewport->Pos;
- r_screen.Max = window->Viewport->Pos + window->Viewport->Size;
- }
- ImVec2 padding = g.Style.DisplaySafeAreaPadding;
+ IM_UNUSED(window);
+ ImVec2 padding = GImGui->Style.DisplaySafeAreaPadding;
+ ImRect r_screen = GetViewportRect();
r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
return r_screen;
}
@@ -8344,51 +8333,93 @@ ImRect ImGui::GetWindowAllowedExtentRect(ImGuiWindow* window)
ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
+
+ ImRect r_outer = GetWindowAllowedExtentRect(window);
if (window->Flags & ImGuiWindowFlags_ChildMenu)
{
// Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
// This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
- ImGuiWindow* parent_window = window->ParentWindow;
+ IM_ASSERT(g.CurrentWindow == window);
+ ImGuiWindow* parent_window = g.CurrentWindowStack[g.CurrentWindowStack.Size - 2];
float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
- ImRect r_outer = GetWindowAllowedExtentRect(window);
ImRect r_avoid;
if (parent_window->DC.MenuBarAppending)
- r_avoid = ImRect(-FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight(), FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight() + parent_window->MenuBarHeight());
+ r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field
else
r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
- return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid);
+ return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
}
if (window->Flags & ImGuiWindowFlags_Popup)
{
- ImRect r_outer = GetWindowAllowedExtentRect(window);
ImRect r_avoid = ImRect(window->Pos.x - 1, window->Pos.y - 1, window->Pos.x + 1, window->Pos.y + 1);
- return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid);
+ return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
}
if (window->Flags & ImGuiWindowFlags_Tooltip)
{
// Position tooltip (always follows mouse)
float sc = g.Style.MouseCursorScale;
ImVec2 ref_pos = NavCalcPreferredRefPos();
- ImRect r_outer = GetWindowAllowedExtentRect(window);
ImRect r_avoid;
if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
else
r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * sc, ref_pos.y + 24 * sc); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
- ImVec2 pos = FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid);
- if (window->AutoPosLastDirection == ImGuiDir_None)
- pos = 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.
- return pos;
+ return FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
}
IM_ASSERT(0);
return window->Pos;
}
-
//-----------------------------------------------------------------------------
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
//-----------------------------------------------------------------------------
+// FIXME-NAV: The existence of SetNavID vs SetNavIDWithRectRel vs SetFocusID is incredibly messy and confusing,
+// and needs some explanation or serious refactoring.
+void ImGui::SetNavID(ImGuiID id, int nav_layer, ImGuiID focus_scope_id)
+{
+ ImGuiContext& g = *GImGui;
+ IM_ASSERT(g.NavWindow);
+ IM_ASSERT(nav_layer == 0 || nav_layer == 1);
+ g.NavId = id;
+ g.NavFocusScopeId = focus_scope_id;
+ g.NavWindow->NavLastIds[nav_layer] = id;
+}
+
+void ImGui::SetNavIDWithRectRel(ImGuiID id, int nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
+{
+ ImGuiContext& g = *GImGui;
+ SetNavID(id, nav_layer, focus_scope_id);
+ g.NavWindow->NavRectRel[nav_layer] = rect_rel;
+ g.NavMousePosDirty = true;
+ g.NavDisableHighlight = false;
+ g.NavDisableMouseHover = true;
+}
+
+void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
+{
+ ImGuiContext& g = *GImGui;
+ IM_ASSERT(id != 0);
+
+ // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and window->DC.NavFocusScopeIdCurrent are valid.
+ // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
+ const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
+ if (g.NavWindow != window)
+ g.NavInitRequest = false;
+ g.NavWindow = window;
+ g.NavId = id;
+ g.NavLayer = nav_layer;
+ g.NavFocusScopeId = window->DC.NavFocusScopeIdCurrent;
+ window->NavLastIds[nav_layer] = id;
+ if (window->DC.LastItemId == id)
+ window->NavRectRel[nav_layer] = ImRect(window->DC.LastItemRect.Min - window->Pos, window->DC.LastItemRect.Max - window->Pos);
+
+ if (g.ActiveIdSource == ImGuiInputSource_Nav)
+ g.NavDisableMouseHover = true;
+ else
+ g.NavDisableHighlight = true;
+}
+
ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
{
if (ImFabs(dx) > ImFabs(dy))
@@ -8419,7 +8450,7 @@ static void inline NavClampRectToVisibleAreaForMoveDir(ImGuiDir move_dir, ImRect
}
}
-// Scoring function for directional navigation. Based on https://gist.github.com/rygorous/6981057
+// Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
static bool ImGui::NavScoreItem(ImGuiNavMoveResult* result, ImRect cand)
{
ImGuiContext& g = *GImGui;
@@ -8427,7 +8458,7 @@ static bool ImGui::NavScoreItem(ImGuiNavMoveResult* result, ImRect cand)
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)
+ const ImRect& curr = g.NavScoringRect; // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
g.NavScoringCount++;
// When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
@@ -8448,7 +8479,7 @@ static bool ImGui::NavScoreItem(ImGuiNavMoveResult* result, ImRect cand)
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);
+ dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
float dist_box = ImFabs(dbx) + ImFabs(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)
@@ -8489,7 +8520,7 @@ static bool ImGui::NavScoreItem(ImGuiNavMoveResult* result, ImRect cand)
ImDrawList* draw_list = GetForegroundDrawList(window);
draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255,200,0,100));
draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200));
- draw_list->AddRectFilled(cand.Max - ImVec2(4,4), cand.Max + CalcTextSize(buf) + ImVec2(4,4), IM_COL32(40,0,0,150));
+ draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40,0,0,150));
draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Max, ~0U, buf);
}
else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate.
@@ -8503,7 +8534,7 @@ static bool ImGui::NavScoreItem(ImGuiNavMoveResult* result, ImRect cand)
draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Min, IM_COL32(255, 255, 255, 255), buf);
}
}
- #endif
+#endif
// Is it in the quadrant we're interesting in moving to?
bool new_best = false;
@@ -8541,7 +8572,7 @@ static bool ImGui::NavScoreItem(ImGuiNavMoveResult* result, ImRect cand)
// 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 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.NavLayer == ImGuiNavLayer_Menu && !(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;
@@ -8551,6 +8582,14 @@ static bool ImGui::NavScoreItem(ImGuiNavMoveResult* result, ImRect cand)
return new_best;
}
+static void ImGui::NavApplyItemToResult(ImGuiNavMoveResult* result, ImGuiWindow* window, ImGuiID id, const ImRect& nav_bb_rel)
+{
+ result->Window = window;
+ result->ID = id;
+ result->FocusScopeId = window->DC.NavFocusScopeIdCurrent;
+ result->RectRel = nav_bb_rel;
+}
+
// 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)
{
@@ -8579,7 +8618,7 @@ static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, con
// Process Move Request (scoring for navigation)
// FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRectScreen + scoring from a rect wrapped according to current wrapping policy)
- if ((g.NavId != id || (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & (ImGuiItemFlags_Disabled|ImGuiItemFlags_NoNav)))
+ if ((g.NavId != id || (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & (ImGuiItemFlags_Disabled | ImGuiItemFlags_NoNav)))
{
ImGuiNavMoveResult* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
#if IMGUI_DEBUG_NAV_SCORING
@@ -8591,24 +8630,14 @@ static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, con
bool new_best = g.NavMoveRequest && NavScoreItem(result, nav_bb);
#endif
if (new_best)
- {
- result->ID = id;
- result->SelectScopeId = g.MultiSelectScopeId;
- result->Window = window;
- result->RectRel = nav_bb_rel;
- }
+ NavApplyItemToResult(result, window, id, nav_bb_rel);
+ // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
const float VISIBLE_RATIO = 0.70f;
if ((g.NavMoveRequestFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
if (NavScoreItem(&g.NavMoveResultLocalVisibleSet, nav_bb))
- {
- result = &g.NavMoveResultLocalVisibleSet;
- result->ID = id;
- result->SelectScopeId = g.MultiSelectScopeId;
- result->Window = window;
- result->RectRel = nav_bb_rel;
- }
+ NavApplyItemToResult(&g.NavMoveResultLocalVisibleSet, window, id, nav_bb_rel);
}
// Update window-relative bounding box of navigated item
@@ -8616,8 +8645,9 @@ static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, con
{
g.NavWindow = window; // Always refresh g.NavWindow, because some operations such as FocusItem() don't have a window.
g.NavLayer = window->DC.NavLayerCurrent;
+ g.NavFocusScopeId = window->DC.NavFocusScopeIdCurrent;
g.NavIdIsAlive = true;
- g.NavIdTabCounter = window->DC.FocusCounterTab;
+ g.NavIdTabCounter = window->DC.FocusCounterTabStop;
window->NavRectRel[window->DC.NavLayerCurrent] = nav_bb_rel; // Store item bounding box (relative to window position)
}
}
@@ -8650,47 +8680,22 @@ void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, const Im
void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags)
{
ImGuiContext& g = *GImGui;
- if (g.NavWindow != window || !NavMoveRequestButNoResultYet() || g.NavMoveRequestForward != ImGuiNavForward_None || g.NavLayer != 0)
- return;
- IM_ASSERT(move_flags != 0); // No points calling this with no wrapping
- ImRect bb_rel = window->NavRectRel[0];
- ImGuiDir clip_dir = g.NavMoveDir;
- if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
- {
- bb_rel.Min.x = bb_rel.Max.x = ImMax(window->SizeFull.x, window->ContentSize.x + window->WindowPadding.x * 2.0f) - window->Scroll.x;
- if (move_flags & ImGuiNavMoveFlags_WrapX) { bb_rel.TranslateY(-bb_rel.GetHeight()); clip_dir = ImGuiDir_Up; }
- NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
- }
- if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
- {
- bb_rel.Min.x = bb_rel.Max.x = -window->Scroll.x;
- if (move_flags & ImGuiNavMoveFlags_WrapX) { bb_rel.TranslateY(+bb_rel.GetHeight()); clip_dir = ImGuiDir_Down; }
- NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
- }
- if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
- {
- bb_rel.Min.y = bb_rel.Max.y = ImMax(window->SizeFull.y, window->ContentSize.y + window->WindowPadding.y * 2.0f) - window->Scroll.y;
- if (move_flags & ImGuiNavMoveFlags_WrapY) { bb_rel.TranslateX(-bb_rel.GetWidth()); clip_dir = ImGuiDir_Left; }
- NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
- }
- if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
- {
- bb_rel.Min.y = bb_rel.Max.y = -window->Scroll.y;
- if (move_flags & ImGuiNavMoveFlags_WrapY) { bb_rel.TranslateX(+bb_rel.GetWidth()); clip_dir = ImGuiDir_Right; }
- NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
- }
+ // Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
+ // popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
+ g.NavWrapRequestWindow = window;
+ g.NavWrapRequestFlags = move_flags;
}
// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
// This way we could find the last focused window among our children. It would be much less confusing this way?
static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
{
- ImGuiWindow* parent_window = nav_window;
- while (parent_window && (parent_window->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (parent_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
- parent_window = parent_window->ParentWindow;
- if (parent_window && parent_window != nav_window)
- parent_window->NavLastChildNavWindow = nav_window;
+ ImGuiWindow* parent = nav_window;
+ while (parent && (parent->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
+ parent = parent->ParentWindow;
+ if (parent && parent != nav_window)
+ parent->NavLastChildNavWindow = nav_window;
}
// Restore the last focused child.
@@ -8699,9 +8704,6 @@ static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
{
if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
return window->NavLastChildNavWindow;
- if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar)
- if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar))
- return tab->Window;
return window;
}
@@ -8711,10 +8713,11 @@ static void NavRestoreLayer(ImGuiNavLayer layer)
g.NavLayer = layer;
if (layer == 0)
g.NavWindow = ImGui::NavRestoreLastChildNavWindow(g.NavWindow);
- if (g.NavWindow->NavLastIds[layer] != 0)
- ImGui::SetNavIDWithRectRel(g.NavWindow->NavLastIds[layer], layer, g.NavWindow->NavRectRel[layer]);
+ ImGuiWindow* window = g.NavWindow;
+ if (layer == 0 && window->NavLastIds[0] != 0)
+ ImGui::SetNavIDWithRectRel(window->NavLastIds[0], layer, 0, window->NavRectRel[0]);
else
- ImGui::NavInitWindow(g.NavWindow, true);
+ ImGui::NavInitWindow(window, true);
}
static inline void ImGui::NavUpdateAnyRequestFlag()
@@ -8734,10 +8737,10 @@ void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
if (!(window->Flags & ImGuiWindowFlags_NoNavInputs))
if (!(window->Flags & ImGuiWindowFlags_ChildWindow) || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
init_for_nav = true;
- //IMGUI_DEBUG_LOG("[Nav] NavInitWindow() init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
+ IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
if (init_for_nav)
{
- SetNavID(0, g.NavLayer);
+ SetNavID(0, g.NavLayer, 0);
g.NavInitRequest = true;
g.NavInitRequestFromMove = false;
g.NavInitResultId = 0;
@@ -8747,6 +8750,7 @@ void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
else
{
g.NavId = window->NavLastIds[0];
+ g.NavFocusScopeId = 0;
}
}
@@ -8765,8 +8769,8 @@ static ImVec2 ImGui::NavCalcPreferredRefPos()
// When navigation is active and mouse is disabled, decide on an arbitrary position around the bottom left of the currently navigated item.
const ImRect& rect_rel = g.NavWindow->NavRectRel[g.NavLayer];
ImVec2 pos = g.NavWindow->Pos + ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight()));
- ImRect visible_rect = g.NavWindow->Viewport->GetRect();
- 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.
+ ImRect visible_rect = GetViewportRect();
+ return ImFloor(ImClamp(pos, visible_rect.Min, visible_rect.Max)); // ImFloor() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
}
}
@@ -8811,22 +8815,30 @@ ImVec2 ImGui::GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInput
static void ImGui::NavUpdate()
{
ImGuiContext& g = *GImGui;
- g.IO.WantSetMousePos = false;
+ ImGuiIO& io = g.IO;
+
+ io.WantSetMousePos = false;
+ g.NavWrapRequestWindow = NULL;
+ g.NavWrapRequestFlags = ImGuiNavMoveFlags_None;
#if 0
if (g.NavScoringCount > 0) IMGUI_DEBUG_LOG("NavScoringCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.FrameCount, g.NavScoringCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
#endif
- // Set input source as Gamepad when buttons are pressed before we map Keyboard (some features differs when used with Gamepad vs Keyboard)
- bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
- bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
- if (nav_gamepad_active)
- 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)
+ // Set input source as Gamepad when buttons are pressed (as some features differs when used with Gamepad vs Keyboard)
+ // (do it before we map Keyboard input!)
+ bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
+ bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
+ if (nav_gamepad_active && g.NavInputSource != ImGuiInputSource_NavGamepad)
+ {
+ if (io.NavInputs[ImGuiNavInput_Activate] > 0.0f || io.NavInputs[ImGuiNavInput_Input] > 0.0f || io.NavInputs[ImGuiNavInput_Cancel] > 0.0f || io.NavInputs[ImGuiNavInput_Menu] > 0.0f
+ || io.NavInputs[ImGuiNavInput_DpadLeft] > 0.0f || io.NavInputs[ImGuiNavInput_DpadRight] > 0.0f || io.NavInputs[ImGuiNavInput_DpadUp] > 0.0f || io.NavInputs[ImGuiNavInput_DpadDown] > 0.0f)
g.NavInputSource = ImGuiInputSource_NavGamepad;
+ }
// Update Keyboard->Nav inputs mapping
if (nav_keyboard_active)
{
- #define NAV_MAP_KEY(_KEY, _NAV_INPUT) do { if (IsKeyDown(g.IO.KeyMap[_KEY])) { g.IO.NavInputs[_NAV_INPUT] = 1.0f; g.NavInputSource = ImGuiInputSource_NavKeyboard; } } while (0)
+ #define NAV_MAP_KEY(_KEY, _NAV_INPUT) do { if (IsKeyDown(io.KeyMap[_KEY])) { io.NavInputs[_NAV_INPUT] = 1.0f; g.NavInputSource = ImGuiInputSource_NavKeyboard; } } while (0)
NAV_MAP_KEY(ImGuiKey_Space, ImGuiNavInput_Activate );
NAV_MAP_KEY(ImGuiKey_Enter, ImGuiNavInput_Input );
NAV_MAP_KEY(ImGuiKey_Escape, ImGuiNavInput_Cancel );
@@ -8834,30 +8846,21 @@ static void ImGui::NavUpdate()
NAV_MAP_KEY(ImGuiKey_RightArrow,ImGuiNavInput_KeyRight_);
NAV_MAP_KEY(ImGuiKey_UpArrow, ImGuiNavInput_KeyUp_ );
NAV_MAP_KEY(ImGuiKey_DownArrow, ImGuiNavInput_KeyDown_ );
- if (g.IO.KeyCtrl)
- g.IO.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f;
- if (g.IO.KeyShift)
- g.IO.NavInputs[ImGuiNavInput_TweakFast] = 1.0f;
- if (g.IO.KeyAlt && !g.IO.KeyCtrl) // AltGR is Alt+Ctrl, also even on keyboards without AltGR we don't want Alt+Ctrl to open menu.
- g.IO.NavInputs[ImGuiNavInput_KeyMenu_] = 1.0f;
+ if (io.KeyCtrl)
+ io.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f;
+ if (io.KeyShift)
+ io.NavInputs[ImGuiNavInput_TweakFast] = 1.0f;
+ if (io.KeyAlt && !io.KeyCtrl) // AltGR is Alt+Ctrl, also even on keyboards without AltGR we don't want Alt+Ctrl to open menu.
+ 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;
+ memcpy(io.NavInputsDownDurationPrev, io.NavInputsDownDuration, sizeof(io.NavInputsDownDuration));
+ for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++)
+ io.NavInputsDownDuration[i] = (io.NavInputs[i] > 0.0f) ? (io.NavInputsDownDuration[i] < 0.0f ? 0.0f : io.NavInputsDownDuration[i] + io.DeltaTime) : -1.0f;
// Process navigation init request (select first/default focus)
- // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
- if (g.NavInitResultId != 0 && (!g.NavDisableHighlight || g.NavInitRequestFromMove) && g.NavWindow)
- {
- // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
- //IMGUI_DEBUG_LOG("[Nav] Apply NavInitRequest result: 0x%08X Layer %d in \"%s\"\n", g.NavInitResultId, g.NavLayer, g.NavWindow->Name);
- if (g.NavInitRequestFromMove)
- SetNavIDWithRectRel(g.NavInitResultId, g.NavLayer, g.NavInitResultRectRel);
- else
- SetNavID(g.NavInitResultId, g.NavLayer);
- g.NavWindow->NavRectRel[g.NavLayer] = g.NavInitResultRectRel;
- }
+ if (g.NavInitResultId != 0 && (!g.NavDisableHighlight || g.NavInitRequestFromMove))
+ NavUpdateInitResult();
g.NavInitRequest = false;
g.NavInitRequestFromMove = false;
g.NavInitResultId = 0;
@@ -8880,12 +8883,12 @@ static void ImGui::NavUpdate()
if (g.NavMousePosDirty && g.NavIdIsAlive)
{
// Set mouse position given our knowledge of the navigated item position from last frame
- if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (g.IO.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
+ if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
{
if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
{
- g.IO.MousePos = g.IO.MousePosPrev = NavCalcPreferredRefPos();
- g.IO.WantSetMousePos = true;
+ io.MousePos = io.MousePosPrev = NavCalcPreferredRefPos();
+ io.WantSetMousePos = true;
}
}
g.NavMousePosDirty = false;
@@ -8897,33 +8900,35 @@ static void ImGui::NavUpdate()
// Store our return window (for returning from Layer 1 to Layer 0) and clear it as soon as we step back in our own Layer 0
if (g.NavWindow)
NavSaveLastChildNavWindowIntoParent(g.NavWindow);
- if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == 0)
+ if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
g.NavWindow->NavLastChildNavWindow = NULL;
// Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
NavUpdateWindowing();
// Set output flags for user application
- g.IO.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
- g.IO.NavVisible = (g.IO.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
+ io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
+ io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
// Process NavCancel input (to close a popup, get back to parent, clear focus)
- if (IsNavInputPressed(ImGuiNavInput_Cancel, ImGuiInputReadMode_Pressed))
+ if (IsNavInputTest(ImGuiNavInput_Cancel, ImGuiInputReadMode_Pressed))
{
+ IMGUI_DEBUG_LOG_NAV("[nav] ImGuiNavInput_Cancel\n");
if (g.ActiveId != 0)
{
if (!IsActiveIdUsingNavInput(ImGuiNavInput_Cancel))
ClearActiveID();
}
- else if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow) && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow && g.NavWindow != g.NavWindow->RootWindowDockStop)
+ 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;
+ SetNavID(child_window->ChildId, 0, 0);
+ // Reassigning with same value, we're being explicit here.
+ g.NavIdIsAlive = false; // -V1048
if (g.NavDisableMouseHover)
g.NavMousePosDirty = true;
}
@@ -8933,7 +8938,7 @@ static void ImGui::NavUpdate()
if (!(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
}
- else if (g.NavLayer != 0)
+ else if (g.NavLayer != ImGuiNavLayer_Main)
{
// Leave the "menu" layer
NavRestoreLayer(ImGuiNavLayer_Main);
@@ -8943,7 +8948,7 @@ static void ImGui::NavUpdate()
// Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
g.NavWindow->NavLastIds[0] = 0;
- g.NavId = 0;
+ g.NavId = g.NavFocusScopeId = 0;
}
}
@@ -8952,14 +8957,14 @@ static void ImGui::NavUpdate()
if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
{
bool activate_down = IsNavInputDown(ImGuiNavInput_Activate);
- bool activate_pressed = activate_down && IsNavInputPressed(ImGuiNavInput_Activate, ImGuiInputReadMode_Pressed);
+ bool activate_pressed = activate_down && IsNavInputTest(ImGuiNavInput_Activate, ImGuiInputReadMode_Pressed);
if (g.ActiveId == 0 && activate_pressed)
g.NavActivateId = g.NavId;
if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_down)
g.NavActivateDownId = g.NavId;
if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_pressed)
g.NavActivatePressedId = g.NavId;
- if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && IsNavInputPressed(ImGuiNavInput_Input, ImGuiInputReadMode_Pressed))
+ if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && IsNavInputTest(ImGuiNavInput_Input, ImGuiInputReadMode_Pressed))
g.NavInputId = g.NavId;
}
if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
@@ -8980,10 +8985,11 @@ static void ImGui::NavUpdate()
g.NavMoveRequestFlags = ImGuiNavMoveFlags_None;
if (g.NavWindow && !g.NavWindowingTarget && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
{
- if (!IsActiveIdUsingNavDir(ImGuiDir_Left) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadLeft, ImGuiNavInput_KeyLeft_, ImGuiInputReadMode_Repeat)) { g.NavMoveDir = ImGuiDir_Left; }
- if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadRight,ImGuiNavInput_KeyRight_,ImGuiInputReadMode_Repeat)) { g.NavMoveDir = ImGuiDir_Right; }
- if (!IsActiveIdUsingNavDir(ImGuiDir_Up) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadUp, ImGuiNavInput_KeyUp_, ImGuiInputReadMode_Repeat)) { g.NavMoveDir = ImGuiDir_Up; }
- if (!IsActiveIdUsingNavDir(ImGuiDir_Down) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadDown, ImGuiNavInput_KeyDown_, ImGuiInputReadMode_Repeat)) { g.NavMoveDir = ImGuiDir_Down; }
+ const ImGuiInputReadMode read_mode = ImGuiInputReadMode_Repeat;
+ if (!IsActiveIdUsingNavDir(ImGuiDir_Left) && (IsNavInputTest(ImGuiNavInput_DpadLeft, read_mode) || IsNavInputTest(ImGuiNavInput_KeyLeft_, read_mode))) { g.NavMoveDir = ImGuiDir_Left; }
+ if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && (IsNavInputTest(ImGuiNavInput_DpadRight, read_mode) || IsNavInputTest(ImGuiNavInput_KeyRight_, read_mode))) { g.NavMoveDir = ImGuiDir_Right; }
+ if (!IsActiveIdUsingNavDir(ImGuiDir_Up) && (IsNavInputTest(ImGuiNavInput_DpadUp, read_mode) || IsNavInputTest(ImGuiNavInput_KeyUp_, read_mode))) { g.NavMoveDir = ImGuiDir_Up; }
+ if (!IsActiveIdUsingNavDir(ImGuiDir_Down) && (IsNavInputTest(ImGuiNavInput_DpadDown, read_mode) || IsNavInputTest(ImGuiNavInput_KeyDown_, read_mode))) { g.NavMoveDir = ImGuiDir_Down; }
}
g.NavMoveClipDir = g.NavMoveDir;
}
@@ -8993,6 +8999,7 @@ static void ImGui::NavUpdate()
// (Preserve g.NavMoveRequestFlags, g.NavMoveClipDir which were set by the NavMoveRequestForward() function)
IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_ForwardQueued);
+ IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
g.NavMoveRequestForward = ImGuiNavForward_ForwardActive;
}
@@ -9006,13 +9013,15 @@ static void ImGui::NavUpdate()
if (g.NavMoveDir != ImGuiDir_None)
{
g.NavMoveRequest = true;
+ g.NavMoveRequestKeyMods = io.KeyMods;
g.NavMoveDirLast = g.NavMoveDir;
}
if (g.NavMoveRequest && g.NavId == 0)
{
- //IMGUI_DEBUG_LOG("[Nav] NavInitRequest from move, window \"%s\", layer=%d\n", g.NavWindow->Name, g.NavLayer);
+ IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", g.NavWindow->Name, g.NavLayer);
g.NavInitRequest = g.NavInitRequestFromMove = true;
- g.NavInitResultId = 0;
+ // Reassigning with same value, we're being explicit here.
+ g.NavInitResultId = 0; // -V1048
g.NavDisableHighlight = false;
}
NavUpdateAnyRequestFlag();
@@ -9022,7 +9031,7 @@ static void ImGui::NavUpdate()
{
// *Fallback* manual-scroll with Nav directional keys when window has no navigable item
ImGuiWindow* window = g.NavWindow;
- const float scroll_speed = ImFloor(window->CalcFontSize() * 100 * g.IO.DeltaTime + 0.5f); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
+ const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll && g.NavMoveRequest)
{
if (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right)
@@ -9033,17 +9042,11 @@ static void ImGui::NavUpdate()
// *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);
+ ImVec2 scroll_dir = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down, 1.0f / 10.0f, 10.0f);
if (scroll_dir.x != 0.0f && window->ScrollbarX)
- {
SetScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed));
- g.NavMoveFromClampedRefRect = true;
- }
if (scroll_dir.y != 0.0f)
- {
SetScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed));
- g.NavMoveFromClampedRefRect = true;
- }
}
// Reset search results
@@ -9051,28 +9054,30 @@ static void ImGui::NavUpdate()
g.NavMoveResultLocalVisibleSet.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)
+ // When using gamepad, we project the reference nav bounding box into window visible area.
+ // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling, since with gamepad every movements are relative
+ // (can't focus a visible object like we can with the mouse).
+ if (g.NavMoveRequest && g.NavInputSource == ImGuiInputSource_NavGamepad && g.NavLayer == ImGuiNavLayer_Main)
{
ImGuiWindow* window = g.NavWindow;
- ImRect window_rect_rel(window->InnerRect.Min - window->Pos - ImVec2(1,1), window->InnerRect.Max - window->Pos + ImVec2(1,1));
+ ImRect window_rect_rel(window->InnerRect.Min - window->Pos - ImVec2(1, 1), window->InnerRect.Max - window->Pos + ImVec2(1, 1));
if (!window_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
{
+ IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel\n");
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;
+ window->NavRectRel[g.NavLayer].ClipWithFull(window_rect_rel);
+ g.NavId = g.NavFocusScopeId = 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) : ImRect(0,0,0,0);
- g.NavScoringRectScreen.TranslateY(nav_scoring_rect_offset_y);
- g.NavScoringRectScreen.Min.x = ImMin(g.NavScoringRectScreen.Min.x + 1.0f, g.NavScoringRectScreen.Max.x);
- g.NavScoringRectScreen.Max.x = g.NavScoringRectScreen.Min.x;
- IM_ASSERT(!g.NavScoringRectScreen.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allows us to remove extraneous ImFabs() calls in NavScoreItem().
+ ImRect nav_rect_rel = g.NavWindow ? g.NavWindow->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
+ g.NavScoringRect = g.NavWindow ? ImRect(g.NavWindow->Pos + nav_rect_rel.Min, g.NavWindow->Pos + nav_rect_rel.Max) : GetViewportRect();
+ g.NavScoringRect.TranslateY(nav_scoring_rect_offset_y);
+ g.NavScoringRect.Min.x = ImMin(g.NavScoringRect.Min.x + 1.0f, g.NavScoringRect.Max.x);
+ g.NavScoringRect.Max.x = g.NavScoringRect.Min.x;
+ IM_ASSERT(!g.NavScoringRect.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allows us to remove extraneous ImFabs() calls in NavScoreItem().
//GetForegroundDrawList()->AddRect(g.NavScoringRectScreen.Min, g.NavScoringRectScreen.Max, IM_COL32(255,200,0,255)); // [DEBUG]
g.NavScoringCount = 0;
#if IMGUI_DEBUG_NAV_RECTS
@@ -9085,6 +9090,22 @@ static void ImGui::NavUpdate()
#endif
}
+static void ImGui::NavUpdateInitResult()
+{
+ // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
+ ImGuiContext& g = *GImGui;
+ if (!g.NavWindow)
+ return;
+
+ // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
+ IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", g.NavInitResultId, g.NavLayer, g.NavWindow->Name);
+ if (g.NavInitRequestFromMove)
+ SetNavIDWithRectRel(g.NavInitResultId, g.NavLayer, 0, g.NavInitResultRectRel);
+ else
+ SetNavID(g.NavInitResultId, g.NavLayer, 0);
+ g.NavWindow->NavRectRel[g.NavLayer] = g.NavInitResultRectRel;
+}
+
// Apply result from previous frame navigation directional move request
static void ImGui::NavUpdateMoveResult()
{
@@ -9115,7 +9136,7 @@ static void ImGui::NavUpdateMoveResult()
IM_ASSERT(g.NavWindow && result->Window);
// Scroll to keep newly navigated item fully into view.
- if (g.NavLayer == 0)
+ if (g.NavLayer == ImGuiNavLayer_Main)
{
ImVec2 delta_scroll;
if (g.NavMoveRequestFlags & ImGuiNavMoveFlags_ScrollToEdge)
@@ -9141,34 +9162,37 @@ static void ImGui::NavUpdateMoveResult()
{
// Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
g.NavJustMovedToId = result->ID;
- g.NavJustMovedToMultiSelectScopeId = result->SelectScopeId;
+ g.NavJustMovedToFocusScopeId = result->FocusScopeId;
+ g.NavJustMovedToKeyMods = g.NavMoveRequestKeyMods;
}
- SetNavIDWithRectRel(result->ID, g.NavLayer, result->RectRel);
- g.NavMoveFromClampedRefRect = false;
+ IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
+ SetNavIDWithRectRel(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
}
// Handle PageUp/PageDown/Home/End keys
static float ImGui::NavUpdatePageUpPageDown()
{
ImGuiContext& g = *GImGui;
+ ImGuiIO& io = g.IO;
+
if (g.NavMoveDir != ImGuiDir_None || g.NavWindow == NULL)
return 0.0f;
- if ((g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL || g.NavLayer != 0)
+ if ((g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL || g.NavLayer != ImGuiNavLayer_Main)
return 0.0f;
ImGuiWindow* window = g.NavWindow;
- const bool page_up_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageUp]) && !IsActiveIdUsingKey(ImGuiKey_PageUp);
- const bool page_down_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageDown]) && !IsActiveIdUsingKey(ImGuiKey_PageDown);
- const bool home_pressed = IsKeyPressed(g.IO.KeyMap[ImGuiKey_Home]) && !IsActiveIdUsingKey(ImGuiKey_Home);
- const bool end_pressed = IsKeyPressed(g.IO.KeyMap[ImGuiKey_End]) && !IsActiveIdUsingKey(ImGuiKey_End);
+ const bool page_up_held = IsKeyDown(io.KeyMap[ImGuiKey_PageUp]) && !IsActiveIdUsingKey(ImGuiKey_PageUp);
+ const bool page_down_held = IsKeyDown(io.KeyMap[ImGuiKey_PageDown]) && !IsActiveIdUsingKey(ImGuiKey_PageDown);
+ const bool home_pressed = IsKeyPressed(io.KeyMap[ImGuiKey_Home]) && !IsActiveIdUsingKey(ImGuiKey_Home);
+ const bool end_pressed = IsKeyPressed(io.KeyMap[ImGuiKey_End]) && !IsActiveIdUsingKey(ImGuiKey_End);
if (page_up_held != page_down_held || home_pressed != end_pressed) // If either (not both) are pressed
{
if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll)
{
// Fallback manual-scroll when window has no navigable item
- if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true))
+ if (IsKeyPressed(io.KeyMap[ImGuiKey_PageUp], true))
SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
- else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true))
+ else if (IsKeyPressed(io.KeyMap[ImGuiKey_PageDown], true))
SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
else if (home_pressed)
SetScrollY(window, 0.0f);
@@ -9180,14 +9204,14 @@ static float ImGui::NavUpdatePageUpPageDown()
ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
float nav_scoring_rect_offset_y = 0.0f;
- if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true))
+ if (IsKeyPressed(io.KeyMap[ImGuiKey_PageUp], true))
{
nav_scoring_rect_offset_y = -page_offset_y;
g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)
g.NavMoveClipDir = ImGuiDir_Up;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
}
- else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true))
+ else if (IsKeyPressed(io.KeyMap[ImGuiKey_PageDown], true))
{
nav_scoring_rect_offset_y = +page_offset_y;
g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)
@@ -9219,10 +9243,72 @@ static float ImGui::NavUpdatePageUpPageDown()
return 0.0f;
}
+static void ImGui::NavEndFrame()
+{
+ ImGuiContext& g = *GImGui;
+
+ // Show CTRL+TAB list window
+ if (g.NavWindowingTarget != NULL)
+ NavUpdateWindowingOverlay();
+
+ // Perform wrap-around in menus
+ ImGuiWindow* window = g.NavWrapRequestWindow;
+ ImGuiNavMoveFlags move_flags = g.NavWrapRequestFlags;
+ if (window != NULL && g.NavWindow == window && NavMoveRequestButNoResultYet() && g.NavMoveRequestForward == ImGuiNavForward_None && g.NavLayer == ImGuiNavLayer_Main)
+ {
+ IM_ASSERT(move_flags != 0); // No points calling this with no wrapping
+ ImRect bb_rel = window->NavRectRel[0];
+
+ ImGuiDir clip_dir = g.NavMoveDir;
+ if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
+ {
+ bb_rel.Min.x = bb_rel.Max.x =
+ ImMax(window->SizeFull.x, window->ContentSize.x + window->WindowPadding.x * 2.0f) - window->Scroll.x;
+ if (move_flags & ImGuiNavMoveFlags_WrapX)
+ {
+ bb_rel.TranslateY(-bb_rel.GetHeight());
+ clip_dir = ImGuiDir_Up;
+ }
+ NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
+ }
+ if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
+ {
+ bb_rel.Min.x = bb_rel.Max.x = -window->Scroll.x;
+ if (move_flags & ImGuiNavMoveFlags_WrapX)
+ {
+ bb_rel.TranslateY(+bb_rel.GetHeight());
+ clip_dir = ImGuiDir_Down;
+ }
+ NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
+ }
+ if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
+ {
+ bb_rel.Min.y = bb_rel.Max.y =
+ ImMax(window->SizeFull.y, window->ContentSize.y + window->WindowPadding.y * 2.0f) - window->Scroll.y;
+ if (move_flags & ImGuiNavMoveFlags_WrapY)
+ {
+ bb_rel.TranslateX(-bb_rel.GetWidth());
+ clip_dir = ImGuiDir_Left;
+ }
+ NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
+ }
+ if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
+ {
+ bb_rel.Min.y = bb_rel.Max.y = -window->Scroll.y;
+ if (move_flags & ImGuiNavMoveFlags_WrapY)
+ {
+ bb_rel.TranslateX(+bb_rel.GetWidth());
+ clip_dir = ImGuiDir_Right;
+ }
+ NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
+ }
+ }
+}
+
static int ImGui::FindWindowFocusIndex(ImGuiWindow* window) // FIXME-OPT O(N)
{
ImGuiContext& g = *GImGui;
- for (int i = g.WindowsFocusOrder.Size-1; i >= 0; i--)
+ for (int i = g.WindowsFocusOrder.Size - 1; i >= 0; i--)
if (g.WindowsFocusOrder[i] == window)
return i;
return -1;
@@ -9263,11 +9349,9 @@ static void ImGui::NavUpdateWindowing()
bool apply_toggle_layer = false;
ImGuiWindow* modal_window = GetTopMostPopupModal();
- if (modal_window != NULL)
- {
+ bool allow_windowing = (modal_window == NULL);
+ if (!allow_windowing)
g.NavWindowingTarget = NULL;
- return;
- }
// Fade out
if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
@@ -9278,12 +9362,12 @@ static void ImGui::NavUpdateWindowing()
}
// Start CTRL-TAB or Square+L/R window selection
- bool start_windowing_with_gamepad = !g.NavWindowingTarget && IsNavInputPressed(ImGuiNavInput_Menu, ImGuiInputReadMode_Pressed);
- bool start_windowing_with_keyboard = !g.NavWindowingTarget && g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab) && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard);
+ bool start_windowing_with_gamepad = allow_windowing && !g.NavWindowingTarget && IsNavInputTest(ImGuiNavInput_Menu, ImGuiInputReadMode_Pressed);
+ bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab) && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard);
if (start_windowing_with_gamepad || start_windowing_with_keyboard)
if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
{
- g.NavWindowingTarget = g.NavWindowingTargetAnim = window;
+ g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow; // FIXME-DOCK: Will need to use RootWindowDockStop
g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
g.NavWindowingToggleLayer = start_windowing_with_keyboard ? false : true;
g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_NavKeyboard : ImGuiInputSource_NavGamepad;
@@ -9297,7 +9381,7 @@ static void ImGui::NavUpdateWindowing()
g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
// Select window to focus
- const int focus_change_dir = (int)IsNavInputPressed(ImGuiNavInput_FocusPrev, ImGuiInputReadMode_RepeatSlow) - (int)IsNavInputPressed(ImGuiNavInput_FocusNext, ImGuiInputReadMode_RepeatSlow);
+ const int focus_change_dir = (int)IsNavInputTest(ImGuiNavInput_FocusPrev, ImGuiInputReadMode_RepeatSlow) - (int)IsNavInputTest(ImGuiNavInput_FocusNext, ImGuiInputReadMode_RepeatSlow);
if (focus_change_dir != 0)
{
NavUpdateWindowingHighlightWindow(focus_change_dir);
@@ -9328,10 +9412,10 @@ static void ImGui::NavUpdateWindowing()
}
// Keyboard: Press and Release ALT to toggle menu layer
- // FIXME: We lack an explicit IO variable for "is the imgui window focused", so compare mouse validity to detect the common case of back-end clearing releases all keys on ALT-TAB
- if (IsNavInputPressed(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Pressed))
+ // FIXME: We lack an explicit IO variable for "is the imgui window focused", so compare mouse validity to detect the common case of backend clearing releases all keys on ALT-TAB
+ if (IsNavInputTest(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Pressed))
g.NavWindowingToggleLayer = true;
- if ((g.ActiveId == 0 || g.ActiveIdAllowOverlap) && g.NavWindowingToggleLayer && IsNavInputPressed(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Released))
+ if ((g.ActiveId == 0 || g.ActiveIdAllowOverlap) && g.NavWindowingToggleLayer && IsNavInputTest(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Released))
if (IsMousePosValid(&g.IO.MousePos) == IsMousePosValid(&g.IO.MousePosPrev))
apply_toggle_layer = true;
@@ -9346,17 +9430,17 @@ static void ImGui::NavUpdateWindowing()
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)); // FIXME: Doesn't code variable framerate very well
- SetWindowPos(g.NavWindowingTarget->RootWindow, g.NavWindowingTarget->RootWindow->Pos + move_delta * move_speed, ImGuiCond_Always);
+ const float move_speed = ImFloor(NAV_MOVE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); // FIXME: Doesn't handle variable framerate very well
+ ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindow;
+ SetWindowPos(moving_window, moving_window->Pos + move_delta * move_speed, ImGuiCond_Always);
+ MarkIniSettingsDirty(moving_window);
g.NavDisableMouseHover = true;
- MarkIniSettingsDirty(g.NavWindowingTarget);
}
}
// Apply final focus
- if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindowDockStop))
+ if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
{
- ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
ClearActiveID();
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
@@ -9369,10 +9453,6 @@ static void ImGui::NavUpdateWindowing()
// If the window only has a menu layer, select it directly
if (apply_focus_window->DC.NavLayerActiveMask == (1 << ImGuiNavLayer_Menu))
g.NavLayer = ImGuiNavLayer_Menu;
-
- // Request OS level focus
- if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus)
- g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport);
}
if (apply_focus_window)
g.NavWindowingTarget = NULL;
@@ -9396,11 +9476,8 @@ static void ImGui::NavUpdateWindowing()
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
- // When entering a regular menu bar with the Alt key, we always reinitialize the navigation ID. It however persist on docking tab tabs.
+ // When entering a regular menu bar with the Alt key, we always reinitialize the navigation ID.
const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayerActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
- const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL);
- if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id)
- g.NavWindow->NavLastIds[ImGuiNavLayer_Menu] = 0;
NavRestoreLayer(new_nav_layer);
}
}
@@ -9412,8 +9489,6 @@ static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
return "(Popup)";
if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
return "(Main menu bar)";
- if (window->DockNodeAsHost)
- return "(Dock node)";
return "(Untitled)";
}
@@ -9426,11 +9501,10 @@ void ImGui::NavUpdateWindowingOverlay()
if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
return;
- if (g.NavWindowingList == NULL)
- g.NavWindowingList = FindWindowByName("###NavWindowingList");
- ImGuiViewportP* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ (ImGuiViewportP*)GetMainViewport();
- SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
- SetNextWindowPos(viewport->Pos + viewport->Size * 0.5f, ImGuiCond_Always, ImVec2(0.5f, 0.5f));
+ if (g.NavWindowingListWindow == NULL)
+ g.NavWindowingListWindow = FindWindowByName("###NavWindowingList");
+ SetNextWindowSizeConstraints(ImVec2(g.IO.DisplaySize.x * 0.20f, g.IO.DisplaySize.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
+ SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_Always, ImVec2(0.5f, 0.5f));
PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
@@ -9476,7 +9550,7 @@ bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
bool source_drag_active = false;
ImGuiID source_id = 0;
ImGuiID source_parent_id = 0;
- int mouse_button = 0;
+ ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
if (!(flags & ImGuiDragDropFlags_SourceExtern))
{
source_id = window->DC.LastItemId;
@@ -9521,6 +9595,11 @@ bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
return false;
source_parent_id = window->IDStack.back();
source_drag_active = IsMouseDragging(mouse_button);
+
+ // Disable navigation and key inputs while dragging
+ g.ActiveIdUsingNavDirMask = ~(ImU32)0;
+ g.ActiveIdUsingNavInputMask = ~(ImU32)0;
+ g.ActiveIdUsingKeyInputMask = ~(ImU64)0;
}
else
{
@@ -9541,9 +9620,11 @@ bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
g.DragDropActive = true;
g.DragDropSourceFlags = flags;
g.DragDropMouseButton = mouse_button;
+ if (payload.SourceId == g.ActiveId)
+ g.ActiveIdNoClearOnFocusLoss = true;
}
g.DragDropSourceFrameCount = g.FrameCount;
- g.DragDropWithinSourceOrTarget = true;
+ g.DragDropWithinSource = true;
if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
{
@@ -9570,7 +9651,7 @@ void ImGui::EndDragDropSource()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.DragDropActive);
- IM_ASSERT(g.DragDropWithinSourceOrTarget && "Not after a BeginDragDropSource()?");
+ IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
EndTooltip();
@@ -9578,7 +9659,7 @@ void ImGui::EndDragDropSource()
// Discard the drag if have not called SetDragDropPayload()
if (g.DragDropPayload.DataFrameCount == -1)
ClearDragDrop();
- g.DragDropWithinSourceOrTarget = false;
+ g.DragDropWithinSource = false;
}
// Use 'cond' to choose to submit payload on drag start or every frame
@@ -9632,7 +9713,8 @@ bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
return false;
ImGuiWindow* window = g.CurrentWindow;
- if (g.HoveredWindowUnderMovingWindow == NULL || window->RootWindow != g.HoveredWindowUnderMovingWindow->RootWindow)
+ ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
+ if (hovered_window == NULL || window->RootWindow != hovered_window->RootWindow)
return false;
IM_ASSERT(id != 0);
if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
@@ -9640,10 +9722,10 @@ bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
if (window->SkipItems)
return false;
- IM_ASSERT(g.DragDropWithinSourceOrTarget == false);
+ IM_ASSERT(g.DragDropWithinTarget == false);
g.DragDropTargetRect = bb;
g.DragDropTargetId = id;
- g.DragDropWithinSourceOrTarget = true;
+ g.DragDropWithinTarget = true;
return true;
}
@@ -9660,7 +9742,8 @@ bool ImGui::BeginDragDropTarget()
ImGuiWindow* window = g.CurrentWindow;
if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect))
return false;
- if (g.HoveredWindowUnderMovingWindow == NULL || window->RootWindow != g.HoveredWindowUnderMovingWindow->RootWindow)
+ ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
+ if (hovered_window == NULL || window->RootWindow != hovered_window->RootWindow)
return false;
const ImRect& display_rect = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? window->DC.LastItemDisplayRect : window->DC.LastItemRect;
@@ -9670,10 +9753,10 @@ bool ImGui::BeginDragDropTarget()
if (g.DragDropPayload.SourceId == id)
return false;
- IM_ASSERT(g.DragDropWithinSourceOrTarget == false);
+ IM_ASSERT(g.DragDropWithinTarget == false);
g.DragDropTargetRect = display_rect;
g.DragDropTargetId = id;
- g.DragDropWithinSourceOrTarget = true;
+ g.DragDropWithinTarget = true;
return true;
}
@@ -9698,7 +9781,7 @@ const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDrop
const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
ImRect r = g.DragDropTargetRect;
float r_surface = r.GetWidth() * r.GetHeight();
- if (r_surface < g.DragDropAcceptIdCurrRectSurface)
+ if (r_surface <= g.DragDropAcceptIdCurrRectSurface)
{
g.DragDropAcceptFlags = flags;
g.DragDropAcceptIdCurr = g.DragDropTargetId;
@@ -9713,7 +9796,7 @@ const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDrop
// FIXME-DRAG: Settle on a proper default visuals for drop target.
r.Expand(3.5f);
bool push_clip_rect = !window->ClipRect.Contains(r);
- if (push_clip_rect) window->DrawList->PushClipRect(r.Min-ImVec2(1,1), r.Max+ImVec2(1,1));
+ if (push_clip_rect) window->DrawList->PushClipRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1));
window->DrawList->AddRect(r.Min, r.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, ~0, 2.0f);
if (push_clip_rect) window->DrawList->PopClipRect();
}
@@ -9737,11 +9820,10 @@ void ImGui::EndDragDropTarget()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.DragDropActive);
- IM_ASSERT(g.DragDropWithinSourceOrTarget);
- g.DragDropWithinSourceOrTarget = false;
+ IM_ASSERT(g.DragDropWithinTarget);
+ g.DragDropWithinTarget = false;
}
-
//-----------------------------------------------------------------------------
// [SECTION] LOGGING/CAPTURING
//-----------------------------------------------------------------------------
@@ -9759,9 +9841,15 @@ void ImGui::LogText(const char* fmt, ...)
va_list args;
va_start(args, fmt);
if (g.LogFile)
- vfprintf(g.LogFile, fmt, args);
- else
+ {
+ g.LogBuffer.Buf.resize(0);
g.LogBuffer.appendfv(fmt, args);
+ ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
+ }
+ else
+ {
+ g.LogBuffer.appendfv(fmt, args);
+ }
va_end(args);
}
@@ -9838,8 +9926,11 @@ void ImGui::LogToTTY(int auto_open_depth)
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
+ IM_UNUSED(auto_open_depth);
+#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
LogBegin(ImGuiLogType_TTY, auto_open_depth);
g.LogFile = stdout;
+#endif
}
// Start logging/capturing text output to given file
@@ -9856,8 +9947,8 @@ void ImGui::LogToFile(int auto_open_depth, const char* filename)
filename = g.IO.LogFilename;
if (!filename || !filename[0])
return;
- FILE* f = ImFileOpen(filename, "ab");
- if (f == NULL)
+ ImFileHandle f = ImFileOpen(filename, "ab");
+ if (!f)
{
IM_ASSERT(0);
return;
@@ -9894,10 +9985,12 @@ void ImGui::LogFinish()
switch (g.LogType)
{
case ImGuiLogType_TTY:
+#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
fflush(g.LogFile);
+#endif
break;
case ImGuiLogType_File:
- fclose(g.LogFile);
+ ImFileClose(g.LogFile);
break;
case ImGuiLogType_Buffer:
break;
@@ -9923,7 +10016,11 @@ void ImGui::LogButtons()
ImGuiContext& g = *GImGui;
PushID("LogButtons");
+#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
const bool log_to_tty = Button("Log To TTY"); SameLine();
+#else
+ const bool log_to_tty = false;
+#endif
const bool log_to_file = Button("Log To File"); SameLine();
const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
PushAllowKeyboardFocus(false);
@@ -9945,6 +10042,47 @@ void ImGui::LogButtons()
//-----------------------------------------------------------------------------
// [SECTION] SETTINGS
//-----------------------------------------------------------------------------
+// - UpdateSettings() [Internal]
+// - MarkIniSettingsDirty() [Internal]
+// - CreateNewWindowSettings() [Internal]
+// - FindWindowSettings() [Internal]
+// - FindOrCreateWindowSettings() [Internal]
+// - FindSettingsHandler() [Internal]
+// - ClearIniSettings() [Internal]
+// - LoadIniSettingsFromDisk()
+// - LoadIniSettingsFromMemory()
+// - SaveIniSettingsToDisk()
+// - SaveIniSettingsToMemory()
+// - WindowSettingsHandler_***() [Internal]
+//-----------------------------------------------------------------------------
+
+// Called by NewFrame()
+void ImGui::UpdateSettings()
+{
+ // Load settings on first frame (if not explicitly loaded manually before)
+ ImGuiContext& g = *GImGui;
+ if (!g.SettingsLoaded)
+ {
+ IM_ASSERT(g.SettingsWindows.empty());
+ if (g.IO.IniFilename)
+ LoadIniSettingsFromDisk(g.IO.IniFilename);
+ g.SettingsLoaded = true;
+ }
+
+ // Save settings (with a delay after the last modification, so we don't spam disk too much)
+ if (g.SettingsDirtyTimer > 0.0f)
+ {
+ g.SettingsDirtyTimer -= g.IO.DeltaTime;
+ if (g.SettingsDirtyTimer <= 0.0f)
+ {
+ if (g.IO.IniFilename != NULL)
+ SaveIniSettingsToDisk(g.IO.IniFilename);
+ else
+ g.IO.WantSaveIniSettings = true; // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
+ g.SettingsDirtyTimer = 0.0f;
+ }
+ }
+}
void ImGui::MarkIniSettingsDirty()
{
@@ -9964,25 +10102,31 @@ void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
{
ImGuiContext& g = *GImGui;
- g.SettingsWindows.push_back(ImGuiWindowSettings());
- ImGuiWindowSettings* settings = &g.SettingsWindows.back();
+
#if !IMGUI_DEBUG_INI_SETTINGS
// Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
// Preserve the full string when IMGUI_DEBUG_INI_SETTINGS is set to make .ini inspection easier.
if (const char* p = strstr(name, "###"))
name = p;
#endif
- settings->Name = ImStrdup(name);
- settings->ID = ImHashStr(name);
+ const size_t name_len = strlen(name);
+
+ // Allocate chunk
+ const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
+ ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
+ IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
+ settings->ID = ImHashStr(name, name_len);
+ memcpy(settings->GetName(), name, name_len + 1); // Store with zero terminator
+
return settings;
}
ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id)
{
ImGuiContext& g = *GImGui;
- for (int i = 0; i != g.SettingsWindows.Size; i++)
- if (g.SettingsWindows[i].ID == id)
- return &g.SettingsWindows[i];
+ for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
+ if (settings->ID == id)
+ return settings;
return NULL;
}
@@ -9993,16 +10137,6 @@ ImGuiWindowSettings* ImGui::FindOrCreateWindowSettings(const char* name)
return CreateNewWindowSettings(name);
}
-void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
-{
- size_t file_data_size = 0;
- char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
- if (!file_data)
- return;
- LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
- IM_FREE(file_data);
-}
-
ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
{
ImGuiContext& g = *GImGui;
@@ -10013,21 +10147,48 @@ ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
return NULL;
}
+void ImGui::ClearIniSettings()
+{
+ ImGuiContext& g = *GImGui;
+ g.SettingsIniData.clear();
+ for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
+ if (g.SettingsHandlers[handler_n].ClearAllFn)
+ g.SettingsHandlers[handler_n].ClearAllFn(&g, &g.SettingsHandlers[handler_n]);
+}
+
+void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
+{
+ size_t file_data_size = 0;
+ char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
+ if (!file_data)
+ return;
+ LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
+ IM_FREE(file_data);
+}
+
// Zero-tolerance, no error reporting, cheap .ini parsing
void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.Initialized);
- IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
+ //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
+ //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
// For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
// For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
if (ini_size == 0)
ini_size = strlen(ini_data);
- char* buf = (char*)IM_ALLOC(ini_size + 1);
- char* buf_end = buf + ini_size;
+ g.SettingsIniData.Buf.resize((int)ini_size + 1);
+ char* const buf = g.SettingsIniData.Buf.Data;
+ char* const buf_end = buf + ini_size;
memcpy(buf, ini_data, ini_size);
- buf[ini_size] = 0;
+ buf_end[0] = 0;
+
+ // Call pre-read handlers
+ // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
+ for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
+ if (g.SettingsHandlers[handler_n].ReadInitFn)
+ g.SettingsHandlers[handler_n].ReadInitFn(&g, &g.SettingsHandlers[handler_n]);
void* entry_data = NULL;
ImGuiSettingsHandler* entry_handler = NULL;
@@ -10050,18 +10211,12 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
line_end[-1] = 0;
const char* name_end = line_end - 1;
const char* type_start = line + 1;
- char* type_end = (char*)(intptr_t)ImStrchrRange(type_start, name_end, ']');
+ char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
if (!type_end || !name_start)
- {
- name_start = type_start; // Import legacy entries that have no type
- type_start = "Window";
- }
- else
- {
- *type_end = 0; // Overwrite first ']'
- name_start++; // Skip second '['
- }
+ continue;
+ *type_end = 0; // Overwrite first ']'
+ name_start++; // Skip second '['
entry_handler = FindSettingsHandler(type_start);
entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
}
@@ -10071,9 +10226,15 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
}
}
- IM_FREE(buf);
g.SettingsLoaded = true;
- DockContextOnLoadSettings(&g);
+
+ // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
+ memcpy(buf, ini_data, ini_size);
+
+ // Call post-read handlers
+ for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
+ if (g.SettingsHandlers[handler_n].ApplyAllFn)
+ g.SettingsHandlers[handler_n].ApplyAllFn(&g, &g.SettingsHandlers[handler_n]);
}
void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
@@ -10085,11 +10246,11 @@ void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
size_t ini_data_size = 0;
const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
- FILE* f = ImFileOpen(ini_filename, "wt");
+ ImFileHandle f = ImFileOpen(ini_filename, "wt");
if (!f)
return;
- fwrite(ini_data, sizeof(char), ini_data_size, f);
- fclose(f);
+ ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
+ ImFileClose(f);
}
// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
@@ -10109,31 +10270,48 @@ const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
return g.SettingsIniData.c_str();
}
-static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
+static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
{
- ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHashStr(name));
- if (!settings)
- settings = ImGui::CreateNewWindowSettings(name);
+ ImGuiContext& g = *ctx;
+ for (int i = 0; i != g.Windows.Size; i++)
+ g.Windows[i]->SettingsOffset = -1;
+ g.SettingsWindows.clear();
+}
+
+static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
+{
+ ImGuiWindowSettings* settings = ImGui::FindOrCreateWindowSettings(name);
+ ImGuiID id = settings->ID;
+ *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
+ settings->ID = id;
+ settings->WantApply = true;
return (void*)settings;
}
-static void SettingsHandlerWindow_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
+static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
{
ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
int x, y;
int i;
- ImU32 u1;
- if (sscanf(line, "Pos=%i,%i", &x, &y) == 2) { settings->Pos = ImVec2ih((short)x, (short)y); }
- else if (sscanf(line, "Size=%i,%i", &x, &y) == 2) { settings->Size = ImVec2ih((short)x, (short)y); }
- else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1) { settings->ViewportId = u1; }
- else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2) { settings->ViewportPos = ImVec2ih((short)x, (short)y); }
- else if (sscanf(line, "Collapsed=%d", &i) == 1) { settings->Collapsed = (i != 0); }
- else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2) { settings->DockId = u1; settings->DockOrder = (short)i; }
- else if (sscanf(line, "DockId=0x%X", &u1) == 1) { settings->DockId = u1; settings->DockOrder = -1; }
- else if (sscanf(line, "ClassId=0x%X", &u1) == 1) { settings->ClassId = u1; }
+ if (sscanf(line, "Pos=%i,%i", &x, &y) == 2) { settings->Pos = ImVec2ih((short)x, (short)y); }
+ else if (sscanf(line, "Size=%i,%i", &x, &y) == 2) { settings->Size = ImVec2ih((short)x, (short)y); }
+ else if (sscanf(line, "Collapsed=%d", &i) == 1) { settings->Collapsed = (i != 0); }
}
-static void SettingsHandlerWindow_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
+// Apply to existing windows (if any)
+static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
+{
+ ImGuiContext& g = *ctx;
+ for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
+ if (settings->WantApply)
+ {
+ if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
+ ApplyWindowSettings(window, settings);
+ settings->WantApply = false;
+ }
+}
+
+static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
{
// Gather data from windows that were active during this session
// (if a window wasn't opened in this session we preserve its settings)
@@ -10144,51 +10322,28 @@ static void SettingsHandlerWindow_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandl
if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
continue;
- ImGuiWindowSettings* settings = (window->SettingsIdx != -1) ? &g.SettingsWindows[window->SettingsIdx] : ImGui::FindWindowSettings(window->ID);
+ ImGuiWindowSettings* settings = (window->SettingsOffset != -1) ? g.SettingsWindows.ptr_from_offset(window->SettingsOffset) : ImGui::FindWindowSettings(window->ID);
if (!settings)
{
settings = ImGui::CreateNewWindowSettings(window->Name);
- window->SettingsIdx = g.SettingsWindows.index_from_ptr(settings);
+ window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
}
IM_ASSERT(settings->ID == window->ID);
- settings->Pos = ImVec2ih(window->Pos - window->ViewportPos);
- settings->Size = ImVec2ih(window->SizeFull);
- settings->ViewportId = window->ViewportId;
- settings->ViewportPos = ImVec2ih(window->ViewportPos);
- IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId);
- settings->DockId = window->DockId;
- settings->ClassId = window->WindowClass.ClassId;
- settings->DockOrder = window->DockOrder;
+ settings->Pos = ImVec2ih((short)window->Pos.x, (short)window->Pos.y);
+ settings->Size = ImVec2ih((short)window->SizeFull.x, (short)window->SizeFull.y);
settings->Collapsed = window->Collapsed;
}
// Write to text buffer
- buf->reserve(buf->size() + g.SettingsWindows.Size * 96); // ballpark reserve
- for (int i = 0; i != g.SettingsWindows.Size; i++)
+ buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
+ for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
{
- const ImGuiWindowSettings* settings = &g.SettingsWindows[i];
- buf->appendf("[%s][%s]\n", handler->TypeName, settings->Name);
- if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
- {
- buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y);
- buf->appendf("ViewportId=0x%08X\n", settings->ViewportId);
- }
- if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
- buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
- if (settings->Size.x != 0 || settings->Size.y != 0)
- buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
+ const char* settings_name = settings->GetName();
+ buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
+ buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
+ buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
buf->appendf("Collapsed=%d\n", settings->Collapsed);
- if (settings->DockId != 0)
- {
- // Write DockId as 4 digits if possible. Automatic DockId are small numbers, but full explicit DockSpace() are full ImGuiID range.
- if (settings->DockOrder == -1)
- buf->appendf("DockId=0x%08X\n", settings->DockId);
- else
- buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder);
- if (settings->ClassId != 0)
- buf->appendf("ClassId=0x%08X\n", settings->ClassId);
- }
- buf->appendf("\n");
+ buf->append("\n");
}
}
@@ -10196,4300 +10351,34 @@ static void SettingsHandlerWindow_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandl
//-----------------------------------------------------------------------------
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
//-----------------------------------------------------------------------------
-// - GetMainViewport()
-// - FindViewportByID()
-// - FindViewportByPlatformHandle()
-// - SetCurrentViewport() [Internal]
-// - SetWindowViewport() [Internal]
-// - GetWindowAlwaysWantOwnViewport() [Internal]
-// - UpdateTryMergeWindowIntoHostViewport() [Internal]
-// - UpdateTryMergeWindowIntoHostViewports() [Internal]
-// - TranslateWindowsInViewport() [Internal]
-// - ScaleWindowsInViewport() [Internal]
-// - FindHoveredViewportFromPlatformWindowStack() [Internal]
-// - UpdateViewportsNewFrame() [Internal]
-// - UpdateViewportsEndFrame() [Internal]
-// - AddUpdateViewport() [Internal]
-// - UpdateSelectWindowViewport() [Internal]
-// - UpdatePlatformWindows()
-// - RenderPlatformWindowsDefault()
-// - FindPlatformMonitorForPos() [Internal]
-// - FindPlatformMonitorForRect() [Internal]
-// - UpdateViewportPlatformMonitor() [Internal]
-// - DestroyPlatformWindow() [Internal]
-// - DestroyPlatformWindows()
-//-----------------------------------------------------------------------------
-ImGuiViewport* ImGui::GetMainViewport()
-{
- ImGuiContext& g = *GImGui;
- return g.Viewports[0];
-}
-
-ImGuiViewport* ImGui::FindViewportByID(ImGuiID id)
-{
- ImGuiContext& g = *GImGui;
- for (int n = 0; n < g.Viewports.Size; n++)
- if (g.Viewports[n]->ID == id)
- return g.Viewports[n];
- return NULL;
-}
-
-ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle)
-{
- ImGuiContext& g = *GImGui;
- for (int i = 0; i != g.Viewports.Size; i++)
- if (g.Viewports[i]->PlatformHandle == platform_handle)
- return g.Viewports[i];
- return NULL;
-}
-
-void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport)
-{
- ImGuiContext& g = *GImGui;
- (void)current_window;
-
- if (viewport)
- viewport->LastFrameActive = g.FrameCount;
- if (g.CurrentViewport == viewport)
- return;
- g.CurrentViewport = viewport;
- //IMGUI_DEBUG_LOG_VIEWPORT("SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0);
-
- // Notify platform layer of viewport changes
- // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
- if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport)
- g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport);
-}
-
-static void SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
-{
- window->Viewport = viewport;
- window->ViewportId = viewport->ID;
- window->ViewportOwned = (viewport->Window == window);
-}
-
-static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window)
-{
- // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own.
- ImGuiContext& g = *GImGui;
- if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge))
- if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
- if (!window->DockIsActive)
- if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0)
- if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0)
- return true;
- return false;
-}
-
-static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
-{
- ImGuiContext& g = *GImGui;
- if (!(viewport->Flags & (ImGuiViewportFlags_CanHostOtherWindows | ImGuiViewportFlags_Minimized)) || window->Viewport == viewport)
- return false;
- if (!viewport->GetRect().Contains(window->Rect()))
- return false;
- if (GetWindowAlwaysWantOwnViewport(window))
- return false;
-
- for (int n = 0; n < g.Windows.Size; n++)
- {
- ImGuiWindow* window_behind = g.Windows[n];
- if (window_behind == window)
- break;
- if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow))
- if (window_behind->Viewport->GetRect().Overlaps(window->Rect()))
- return false;
- }
-
- // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child)
- ImGuiViewportP* old_viewport = window->Viewport;
- if (window->ViewportOwned)
- for (int n = 0; n < g.Windows.Size; n++)
- if (g.Windows[n]->Viewport == old_viewport)
- SetWindowViewport(g.Windows[n], viewport);
- SetWindowViewport(window, viewport);
- BringWindowToDisplayFront(window);
-
- return true;
-}
-
-static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window)
-{
- ImGuiContext& g = *GImGui;
- return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]);
-}
-
-// Translate imgui windows when a Host Viewport has been moved
-// (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
-void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos)
-{
- ImGuiContext& g = *GImGui;
- IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows));
-
- // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently
- // translate imgui windows from OS-window-local to absolute coordinates or vice-versa.
- // 2) If it's not going to fit into the new size, keep it at same absolute position.
- // One problem with this is that most Win32 applications doesn't update their render while dragging,
- // and so the window will appear to teleport when releasing the mouse.
- const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable);
- ImRect test_still_fit_rect(old_pos, old_pos + viewport->Size);
- ImVec2 delta_pos = new_pos - old_pos;
- for (int window_n = 0; window_n < g.Windows.Size; window_n++) // FIXME-OPT
- if (translate_all_windows || (g.Windows[window_n]->Viewport == viewport && test_still_fit_rect.Contains(g.Windows[window_n]->Rect())))
- TranslateWindow(g.Windows[window_n], delta_pos);
-}
-
-// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
-void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
-{
- ImGuiContext& g = *GImGui;
- if (viewport->Window)
- {
- ScaleWindow(viewport->Window, scale);
- }
- else
- {
- for (int i = 0; i != g.Windows.Size; i++)
- if (g.Windows[i]->Viewport == viewport)
- ScaleWindow(g.Windows[i], scale);
- }
-}
-
-// If the back-end doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
-// A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
-// B) It requires Platform_GetWindowFocus to be implemented by back-end.
-static ImGuiViewportP* FindHoveredViewportFromPlatformWindowStack(const ImVec2 mouse_platform_pos)
-{
- ImGuiContext& g = *GImGui;
- ImGuiViewportP* best_candidate = NULL;
- for (int n = 0; n < g.Viewports.Size; n++)
- {
- ImGuiViewportP* viewport = g.Viewports[n];
- if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_Minimized)) && viewport->GetRect().Contains(mouse_platform_pos))
- if (best_candidate == NULL || best_candidate->LastFrontMostStampCount < viewport->LastFrontMostStampCount)
- best_candidate = viewport;
- }
- return best_candidate;
-}
-
-// Update viewports and monitor infos
-// Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info.
-static void ImGui::UpdateViewportsNewFrame()
-{
- ImGuiContext& g = *GImGui;
- IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size);
-
- // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport)
- if ((g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
- {
- for (int n = 0; n < g.Viewports.Size; n++)
- {
- ImGuiViewportP* viewport = g.Viewports[n];
- const bool platform_funcs_available = viewport->PlatformWindowCreated;
- if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available)
- {
- bool minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport);
- if (minimized)
- viewport->Flags |= ImGuiViewportFlags_Minimized;
- else
- viewport->Flags &= ~ImGuiViewportFlags_Minimized;
- }
- }
- }
-
- // Create/update main viewport with current platform position and size
- ImGuiViewportP* main_viewport = g.Viewports[0];
- IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID);
- IM_ASSERT(main_viewport->Window == NULL);
- ImVec2 main_viewport_platform_pos = ImVec2(0.0f, 0.0f);
- ImVec2 main_viewport_platform_size = g.IO.DisplaySize;
- if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
- main_viewport_platform_pos = (main_viewport->Flags & ImGuiViewportFlags_Minimized) ? main_viewport->Pos : g.PlatformIO.Platform_GetWindowPos(main_viewport);
- AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_platform_pos, main_viewport_platform_size, ImGuiViewportFlags_CanHostOtherWindows);
-
- g.CurrentViewport = NULL;
- g.MouseViewport = NULL;
- for (int n = 0; n < g.Viewports.Size; n++)
- {
- ImGuiViewportP* viewport = g.Viewports[n];
- viewport->Idx = n;
-
- // Erase unused viewports
- if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2)
- {
- // Clear references to this viewport in windows (window->ViewportId becomes the master data)
- for (int window_n = 0; window_n < g.Windows.Size; window_n++)
- if (g.Windows[window_n]->Viewport == viewport)
- {
- g.Windows[window_n]->Viewport = NULL;
- g.Windows[window_n]->ViewportOwned = false;
- }
- if (viewport == g.MouseLastHoveredViewport)
- g.MouseLastHoveredViewport = NULL;
- g.Viewports.erase(g.Viewports.Data + n);
-
- // Destroy
- IMGUI_DEBUG_LOG_VIEWPORT("Delete Viewport %08X (%s)\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
- DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here.
- IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false);
- IM_DELETE(viewport);
- n--;
- continue;
- }
-
- const bool platform_funcs_available = viewport->PlatformWindowCreated;
- if ((g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
- {
- // Update Position and Size (from Platform Window to ImGui) if requested.
- // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities.
- if (!(viewport->Flags & ImGuiViewportFlags_Minimized) && platform_funcs_available)
- {
- if (viewport->PlatformRequestMove)
- viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
- if (viewport->PlatformRequestResize)
- viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport);
- }
- }
-
- // Update/copy monitor info
- UpdateViewportPlatformMonitor(viewport);
-
- // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back.
- viewport->Alpha = 1.0f;
-
- // Translate imgui windows when a Host Viewport has been moved
- // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
- const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos;
- if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f))
- TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos);
-
- // Update DPI scale
- float new_dpi_scale;
- if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available)
- new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
- else if (viewport->PlatformMonitor != -1)
- new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
- else
- new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
- if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale)
- {
- float scale_factor = new_dpi_scale / viewport->DpiScale;
- if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
- ScaleWindowsInViewport(viewport, scale_factor);
- //if (viewport == GetMainViewport())
- // g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
-
- // Scale our window moving pivot so that the window will rescale roughly around the mouse position.
- // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border.
- // (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.)
- //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport)
- // g.ActiveIdClickOffset = ImFloor(g.ActiveIdClickOffset * scale_factor);
- }
- viewport->DpiScale = new_dpi_scale;
- }
-
- if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
- {
- g.MouseViewport = main_viewport;
- return;
- }
-
- // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
- // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set.
- ImGuiViewportP* viewport_hovered = NULL;
- if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
- {
- viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL;
- if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
- {
- // Back-end failed at honoring its contract if it returned a viewport with the _NoInputs flag.
- IM_ASSERT(0);
- viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos);
- }
- }
- else
- {
- // If the back-end doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search:
- // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
- // B) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO)
- viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos);
- }
- if (viewport_hovered != NULL)
- g.MouseLastHoveredViewport = viewport_hovered;
- else if (g.MouseLastHoveredViewport == NULL)
- g.MouseLastHoveredViewport = g.Viewports[0];
-
- // Update mouse reference viewport
- // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode)
- if (g.MovingWindow)
- g.MouseViewport = g.MovingWindow->Viewport;
- else
- g.MouseViewport = g.MouseLastHoveredViewport;
-
- // When dragging something, always refer to the last hovered viewport.
- // - when releasing a moving window we will revert to aiming behind (at viewport_hovered)
- // - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info)
- // - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release.
- const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive;
- if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL)
- viewport_hovered = g.MouseLastHoveredViewport;
- if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown())
- if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
- g.MouseViewport = viewport_hovered;
-
- IM_ASSERT(g.MouseViewport != NULL);
-}
-
-// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
-static void ImGui::UpdateViewportsEndFrame()
-{
- ImGuiContext& g = *GImGui;
- g.PlatformIO.MainViewport = g.Viewports[0];
- g.PlatformIO.Viewports.resize(0);
- for (int i = 0; i < g.Viewports.Size; i++)
- {
- ImGuiViewportP* viewport = g.Viewports[i];
- viewport->LastPos = viewport->Pos;
- if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f)
- if (i > 0) // Always include main viewport in the list
- continue;
- if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window))
- continue;
- if (i > 0)
- IM_ASSERT(viewport->Window != NULL);
- g.PlatformIO.Viewports.push_back(viewport);
- }
- g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called
-}
-
-// FIXME: We should ideally refactor the system to call this every frame (we currently don't)
-ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags)
-{
- ImGuiContext& g = *GImGui;
- IM_ASSERT(id != 0);
-
- if (window != NULL)
- {
- if (g.MovingWindow && g.MovingWindow->RootWindow == window)
- flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing;
- if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs))
- flags |= ImGuiViewportFlags_NoInputs;
- if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing)
- flags |= ImGuiViewportFlags_NoFocusOnAppearing;
- }
-
- ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id);
- if (viewport)
- {
- if (!viewport->PlatformRequestMove)
- viewport->Pos = pos;
- if (!viewport->PlatformRequestResize)
- viewport->Size = size;
- viewport->Flags = flags | (viewport->Flags & ImGuiViewportFlags_Minimized); // Preserve existing flags
- }
- else
- {
- // New viewport
- viewport = IM_NEW(ImGuiViewportP)();
- viewport->ID = id;
- viewport->Idx = g.Viewports.Size;
- viewport->Pos = viewport->LastPos = pos;
- viewport->Size = size;
- viewport->Flags = flags;
- UpdateViewportPlatformMonitor(viewport);
- g.Viewports.push_back(viewport);
- IMGUI_DEBUG_LOG_VIEWPORT("Add Viewport %08X (%s)\n", id, window->Name);
-
- // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport.
- // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame
- g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x);
- g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y);
- g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x);
- g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y);
-
- // Store initial DpiScale before the OS platform window creation, based on expected monitor data.
- // This is so we can select an appropriate font size on the first frame of our window lifetime
- if (viewport->PlatformMonitor != -1)
- viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
- }
-
- viewport->Window = window;
- viewport->LastFrameActive = g.FrameCount;
- IM_ASSERT(window == NULL || viewport->ID == window->ID);
-
- if (window != NULL)
- window->ViewportOwned = true;
-
- return viewport;
-}
-
-// FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten.
-static void ImGui::UpdateSelectWindowViewport(ImGuiWindow* window)
-{
- ImGuiContext& g = *GImGui;
- ImGuiWindowFlags flags = window->Flags;
- window->ViewportAllowPlatformMonitorExtend = -1;
-
- // Restore main viewport if multi-viewport is not supported by the back-end
- ImGuiViewportP* main_viewport = g.Viewports[0];
- if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
- {
- SetWindowViewport(window, main_viewport);
- return;
- }
- window->ViewportOwned = false;
-
- // Appearing popups reset their viewport so they can inherit again
- if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing)
- {
- window->Viewport = NULL;
- window->ViewportId = 0;
- }
-
- if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0)
- {
- // By default inherit from parent window
- if (window->Viewport == NULL && window->ParentWindow && !window->ParentWindow->IsFallbackWindow)
- window->Viewport = window->ParentWindow->Viewport;
-
- // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file
- if (window->Viewport == NULL && window->ViewportId != 0)
- {
- window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId);
- if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX)
- window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None);
- }
- }
-
- bool lock_viewport = false;
- if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport)
- {
- // Code explicitly request a viewport
- window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId);
- window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet.
- lock_viewport = true;
- }
- else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu))
- {
- // Always inherit viewport from parent window
- window->Viewport = window->ParentWindow->Viewport;
- }
- else if (flags & ImGuiWindowFlags_Tooltip)
- {
- window->Viewport = g.MouseViewport;
- }
- else if (GetWindowAlwaysWantOwnViewport(window))
- {
- window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
- }
- else if (g.MovingWindow && g.MovingWindow->RootWindow == window && IsMousePosValid())
- {
- if (window->Viewport != NULL && window->Viewport->Window == window)
- window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
- }
- else
- {
- // Merge into host viewport?
- // We cannot test window->ViewportOwned as it set lower in the function.
- bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && g.ActiveId == 0);
- if (try_to_merge_into_host_viewport)
- UpdateTryMergeWindowIntoHostViewports(window);
- }
-
- // Fallback to default viewport
- if (window->Viewport == NULL)
- window->Viewport = main_viewport;
-
- // Mark window as allowed to protrude outside of its viewport and into the current monitor
- if (!lock_viewport)
- {
- if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
- {
- // We need to take account of the possibility that mouse may become invalid.
- // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds.
- ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos;
- bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow);
- bool mouse_valid = IsMousePosValid(&mouse_ref);
- if ((window->Appearing || (flags & ImGuiWindowFlags_Tooltip)) && (!use_mouse_ref || mouse_valid))
- window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos());
- else
- window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
- }
- else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow))
- {
- // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code.
- const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true;
- if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible)
- {
- // Steal/transfer ownership
- IMGUI_DEBUG_LOG_VIEWPORT("Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name);
- window->Viewport->Window = window;
- window->Viewport->ID = window->ID;
- window->Viewport->LastNameHash = 0;
- }
- else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge?
- {
- // New viewport
- window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
- }
- }
- else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0)
- {
- // Regular (non-child, non-popup) windows by default are also allowed to protrude
- // Child windows are kept contained within their parent.
- window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
- }
- }
-
- // Update flags
- window->ViewportOwned = (window == window->Viewport->Window);
- window->ViewportId = window->Viewport->ID;
-
- // If the OS window has a title bar, hide our imgui title bar
- //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
- // window->Flags |= ImGuiWindowFlags_NoTitleBar;
-}
-
-// Called by user at the end of the main loop, after EndFrame()
-// This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api.
-void ImGui::UpdatePlatformWindows()
-{
- ImGuiContext& g = *GImGui;
- IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?");
- IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount);
- g.FrameCountPlatformEnded = g.FrameCount;
- if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
- return;
-
- // Create/resize/destroy platform windows to match each active viewport.
- // Skip the main viewport (index 0), which is always fully handled by the application!
- for (int i = 1; i < g.Viewports.Size; i++)
- {
- ImGuiViewportP* viewport = g.Viewports[i];
-
- // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window
- // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame)
- bool destroy_platform_window = false;
- destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1);
- destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window));
- if (destroy_platform_window)
- {
- DestroyPlatformWindow(viewport);
- continue;
- }
-
- // New windows that appears directly in a new viewport won't always have a size on their first frame
- if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0)
- continue;
-
- // Create window
- bool is_new_platform_window = (viewport->PlatformWindowCreated == false);
- if (is_new_platform_window)
- {
- IMGUI_DEBUG_LOG_VIEWPORT("Create Platform Window %08X (%s)\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
- g.PlatformIO.Platform_CreateWindow(viewport);
- if (g.PlatformIO.Renderer_CreateWindow != NULL)
- g.PlatformIO.Renderer_CreateWindow(viewport);
- viewport->LastNameHash = 0;
- viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?)
- viewport->LastRendererSize = viewport->Size; // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it.
- viewport->PlatformWindowCreated = true;
- }
-
- // Apply Position and Size (from ImGui to Platform/Renderer back-ends)
- if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove)
- g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos);
- if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize)
- g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size);
- if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize)
- g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size);
- viewport->LastPlatformPos = viewport->Pos;
- viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size;
-
- // Update title bar (if it changed)
- if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window))
- {
- const char* title_begin = window_for_title->Name;
- char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin);
- const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin);
- if (viewport->LastNameHash != title_hash)
- {
- char title_end_backup_c = *title_end;
- *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain.
- g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin);
- *title_end = title_end_backup_c;
- viewport->LastNameHash = title_hash;
- }
- }
-
- // Update alpha (if it changed)
- if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha)
- g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha);
- viewport->LastAlpha = viewport->Alpha;
-
- // Optional, general purpose call to allow the back-end to perform general book-keeping even if things haven't changed.
- if (g.PlatformIO.Platform_UpdateWindow)
- g.PlatformIO.Platform_UpdateWindow(viewport);
-
- if (is_new_platform_window)
- {
- // On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late)
- if (g.FrameCount < 3)
- viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing;
-
- // Show window
- g.PlatformIO.Platform_ShowWindow(viewport);
-
- // Even without focus, we assume the window becomes front-most.
- // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available.
- if (viewport->LastFrontMostStampCount != g.ViewportFrontMostStampCount)
- viewport->LastFrontMostStampCount = ++g.ViewportFrontMostStampCount;
- }
-
- // Clear request flags
- viewport->ClearRequestFlags();
- }
-
- // Update our implicit z-order knowledge of platform windows, which is used when the back-end cannot provide io.MouseHoveredViewport.
- // When setting Platform_GetWindowFocus, it is expected that the platform back-end can handle calls without crashing if it doesn't have data stored.
- if (g.PlatformIO.Platform_GetWindowFocus != NULL)
- {
- ImGuiViewportP* focused_viewport = NULL;
- for (int n = 0; n < g.Viewports.Size && focused_viewport == NULL; n++)
- {
- ImGuiViewportP* viewport = g.Viewports[n];
- if (viewport->PlatformWindowCreated)
- if (g.PlatformIO.Platform_GetWindowFocus(viewport))
- focused_viewport = viewport;
- }
- if (focused_viewport && g.PlatformLastFocusedViewport != focused_viewport->ID)
- {
- if (focused_viewport->LastFrontMostStampCount != g.ViewportFrontMostStampCount)
- focused_viewport->LastFrontMostStampCount = ++g.ViewportFrontMostStampCount;
- g.PlatformLastFocusedViewport = focused_viewport->ID;
- }
- }
-}
-
-// This is a default/basic function for performing the rendering/swap of multiple Platform Windows.
-// Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves.
-// The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
-//
-// ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
-// for (int i = 1; i < platform_io.Viewports.Size; i++)
-// if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
-// MyRenderFunction(platform_io.Viewports[i], my_args);
-// for (int i = 1; i < platform_io.Viewports.Size; i++)
-// if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
-// MySwapBufferFunction(platform_io.Viewports[i], my_args);
-//
-void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg)
-{
- // Skip the main viewport (index 0), which is always fully handled by the application!
- ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
- for (int i = 1; i < platform_io.Viewports.Size; i++)
- {
- ImGuiViewport* viewport = platform_io.Viewports[i];
- if (viewport->Flags & ImGuiViewportFlags_Minimized)
- continue;
- if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg);
- if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg);
- }
- for (int i = 1; i < platform_io.Viewports.Size; i++)
- {
- ImGuiViewport* viewport = platform_io.Viewports[i];
- if (viewport->Flags & ImGuiViewportFlags_Minimized)
- continue;
- if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg);
- if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg);
- }
-}
-
-static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos)
-{
- ImGuiContext& g = *GImGui;
- for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
- {
- const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
- if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos))
- return monitor_n;
- }
- return -1;
-}
-
-// Search for the monitor with the largest intersection area with the given rectangle
-// We generally try to avoid searching loops but the monitor count should be very small here
-// FIXME-OPT: We could test the last monitor used for that viewport first, and early
-static int ImGui::FindPlatformMonitorForRect(const ImRect& rect)
-{
- ImGuiContext& g = *GImGui;
-
- const int monitor_count = g.PlatformIO.Monitors.Size;
- if (monitor_count <= 1)
- return monitor_count - 1;
-
- // Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position.
- // This is necessary for tooltips which always resize down to zero at first.
- const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f);
- int best_monitor_n = -1;
- float best_monitor_surface = 0.001f;
-
- for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++)
- {
- const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
- const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize);
- if (monitor_rect.Contains(rect))
- return monitor_n;
- ImRect overlapping_rect = rect;
- overlapping_rect.ClipWithFull(monitor_rect);
- float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight();
- if (overlapping_surface < best_monitor_surface)
- continue;
- best_monitor_surface = overlapping_surface;
- best_monitor_n = monitor_n;
- }
- return best_monitor_n;
-}
-
-// Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor)
-static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport)
-{
- viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetRect());
-}
-
-void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport)
-{
- ImGuiContext& g = *GImGui;
- if (viewport->PlatformWindowCreated)
- {
- if (g.PlatformIO.Renderer_DestroyWindow)
- g.PlatformIO.Renderer_DestroyWindow(viewport);
- if (g.PlatformIO.Platform_DestroyWindow)
- g.PlatformIO.Platform_DestroyWindow(viewport);
- IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL);
-
- // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize()
- // The right-er way may be to leave it to the back-end to set this flag all-together, and made the flag public.
- if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID)
- viewport->PlatformWindowCreated = false;
- }
- else
- {
- IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL);
- }
- viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL;
- viewport->ClearRequestFlags();
-}
-
-void ImGui::DestroyPlatformWindows()
-{
- // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the back-end
- // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData.
- // It is convenient for the platform back-end code to store something in the main viewport, in order for e.g. the mouse handling
- // code to operator a consistent manner.
- // It is expected that the back-end can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without
- // crashing if it doesn't have data stored.
- ImGuiContext& g = *GImGui;
- for (int i = 0; i < g.Viewports.Size; i++)
- DestroyPlatformWindow(g.Viewports[i]);
-}
+// (this section is filled in the 'docking' branch)
//-----------------------------------------------------------------------------
// [SECTION] DOCKING
//-----------------------------------------------------------------------------
-// Docking: Internal Types
-// Docking: Forward Declarations
-// Docking: ImGuiDockContext
-// Docking: ImGuiDockContext Docking/Undocking functions
-// Docking: ImGuiDockNode
-// Docking: ImGuiDockNode Tree manipulation functions
-// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
-// Docking: Builder Functions
-// Docking: Begin/End Support Functions (called from Begin/End)
-// Docking: Settings
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-// Docking: Internal Types
-//-----------------------------------------------------------------------------
-// - ImGuiDockRequestType
-// - ImGuiDockRequest
-// - ImGuiDockPreviewData
-// - ImGuiDockNodeSettings
-// - ImGuiDockContext
-//-----------------------------------------------------------------------------
-
-static float IMGUI_DOCK_SPLITTER_SIZE = 2.0f;
-
-enum ImGuiDockRequestType
-{
- ImGuiDockRequestType_None = 0,
- ImGuiDockRequestType_Dock,
- ImGuiDockRequestType_Undock,
- ImGuiDockRequestType_Split // Split is the same as Dock but without a DockPayload
-};
-
-struct ImGuiDockRequest
-{
- ImGuiDockRequestType Type;
- ImGuiWindow* DockTargetWindow; // Destination/Target Window to dock into (may be a loose window or a DockNode, might be NULL in which case DockTargetNode cannot be NULL)
- ImGuiDockNode* DockTargetNode; // Destination/Target Node to dock into
- ImGuiWindow* DockPayload; // Source/Payload window to dock (may be a loose window or a DockNode), [Optional]
- ImGuiDir DockSplitDir;
- float DockSplitRatio;
- bool DockSplitOuter;
- ImGuiWindow* UndockTargetWindow;
- ImGuiDockNode* UndockTargetNode;
-
- ImGuiDockRequest()
- {
- Type = ImGuiDockRequestType_None;
- DockTargetWindow = DockPayload = UndockTargetWindow = NULL;
- DockTargetNode = UndockTargetNode = NULL;
- DockSplitDir = ImGuiDir_None;
- DockSplitRatio = 0.5f;
- DockSplitOuter = false;
- }
-};
-
-struct ImGuiDockPreviewData
-{
- ImGuiDockNode FutureNode;
- bool IsDropAllowed;
- bool IsCenterAvailable;
- bool IsSidesAvailable; // Hold your breath, grammar freaks..
- bool IsSplitDirExplicit; // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window)
- ImGuiDockNode* SplitNode;
- ImGuiDir SplitDir;
- float SplitRatio;
- ImRect DropRectsDraw[ImGuiDir_COUNT + 1]; // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects()
-
- ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; }
-};
-
-// Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes)
-struct ImGuiDockNodeSettings
-{
- ImGuiID ID;
- ImGuiID ParentNodeID;
- ImGuiID ParentWindowID;
- ImGuiID SelectedWindowID;
- signed char SplitAxis;
- char Depth;
- ImGuiDockNodeFlags Flags; // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_)
- ImVec2ih Pos;
- ImVec2ih Size;
- ImVec2ih SizeRef;
- ImGuiDockNodeSettings() { ID = ParentNodeID = ParentWindowID = SelectedWindowID = 0; SplitAxis = ImGuiAxis_None; Depth = 0; Flags = ImGuiDockNodeFlags_None; }
-};
-
-struct ImGuiDockContext
-{
- ImGuiStorage Nodes; // Map ID -> ImGuiDockNode*: Active nodes
- ImVector Requests;
- ImVector SettingsNodes;
- bool WantFullRebuild;
- ImGuiDockContext() { WantFullRebuild = false; }
-};
-
-//-----------------------------------------------------------------------------
-// Docking: Forward Declarations
-//-----------------------------------------------------------------------------
-
-namespace ImGui
-{
- // ImGuiDockContext
- static ImGuiDockNode* DockContextAddNode(ImGuiContext* ctx, ImGuiID id);
- static void DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node);
- static void DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node);
- static void DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req);
- static void DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref = true);
- static void DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node);
- static void DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx);
- static ImGuiDockNode* DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id);
- static ImGuiDockNode* DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window);
- static void DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_persistent_docking_refs); // Use root_id==0 to clear all
- static void DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count);
- static void DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id); // Use root_id==0 to add all
-
- // ImGuiDockNode
- static void DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar);
- static void DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
- static void DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
- static ImGuiWindow* DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id);
- static void DockNodeApplyPosSizeToWindows(ImGuiDockNode* node);
- static void DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id);
- static void DockNodeHideHostWindow(ImGuiDockNode* node);
- static void DockNodeUpdate(ImGuiDockNode* node);
- static void DockNodeUpdateVisibleFlagAndInactiveChilds(ImGuiDockNode* node);
- static void DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window);
- static void DockNodeAddTabBar(ImGuiDockNode* node);
- static void DockNodeRemoveTabBar(ImGuiDockNode* node);
- static ImGuiID DockNodeUpdateWindowMenu(ImGuiDockNode* node, ImGuiTabBar* tab_bar);
- static void DockNodeUpdateVisibleFlag(ImGuiDockNode* node);
- static void DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window);
- static bool DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window);
- static void DockNodePreviewDockCalc(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking);
- static void DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data);
- static void DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos);
- static void DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired);
- static bool DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos);
- static const char* DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; }
- static int DockNodeGetDepth(const ImGuiDockNode* node) { int depth = 0; while (node->ParentNode) { node = node->ParentNode; depth++; } return depth; }
- static int DockNodeGetTabOrder(ImGuiWindow* window);
-
- // ImGuiDockNode tree manipulations
- static void DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node);
- static void DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child);
- static void DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, bool only_write_to_marked_nodes = false);
- static void DockNodeTreeUpdateSplitter(ImGuiDockNode* node);
- static ImGuiDockNode* DockNodeTreeFindNodeByPos(ImGuiDockNode* node, ImVec2 pos);
- static ImGuiDockNode* DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node);
-
- // Settings
- static void DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id);
- static void DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count);
- static ImGuiDockNodeSettings* DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id);
- static void* DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
- static void DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
- static void DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
-}
-
-//-----------------------------------------------------------------------------
-// Docking: ImGuiDockContext
-//-----------------------------------------------------------------------------
-// The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings,
-// or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active.
-// At boot time only, we run a simple GC to remove nodes that have no references.
-// Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures),
-// we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does).
-// This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data.
-//-----------------------------------------------------------------------------
-// - DockContextInitialize()
-// - DockContextShutdown()
-// - DockContextOnLoadSettings()
-// - DockContextClearNodes()
-// - DockContextRebuildNodes()
-// - DockContextUpdateUndocking()
-// - DockContextUpdateDocking()
-// - DockContextFindNodeByID()
-// - DockContextBindNodeToWindow()
-// - DockContextGenNodeID()
-// - DockContextAddNode()
-// - DockContextRemoveNode()
-// - ImGuiDockContextPruneNodeData
-// - DockContextPruneUnusedSettingsNodes()
-// - DockContextBuildNodesFromSettings()
-// - DockContextBuildAddWindowsToNodes()
-//-----------------------------------------------------------------------------
-
-void ImGui::DockContextInitialize(ImGuiContext* ctx)
-{
- ImGuiContext& g = *ctx;
- IM_ASSERT(g.DockContext == NULL);
- g.DockContext = IM_NEW(ImGuiDockContext)();
-
- // Add .ini handle for persistent docking data
- ImGuiSettingsHandler ini_handler;
- ini_handler.TypeName = "Docking";
- ini_handler.TypeHash = ImHashStr("Docking");
- ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen;
- ini_handler.ReadLineFn = DockSettingsHandler_ReadLine;
- ini_handler.WriteAllFn = DockSettingsHandler_WriteAll;
- g.SettingsHandlers.push_back(ini_handler);
-}
-
-void ImGui::DockContextShutdown(ImGuiContext* ctx)
-{
- ImGuiContext& g = *ctx;
- ImGuiDockContext* dc = ctx->DockContext;
- for (int n = 0; n < dc->Nodes.Data.Size; n++)
- if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
- IM_DELETE(node);
- IM_DELETE(g.DockContext);
- g.DockContext = NULL;
-}
-
-void ImGui::DockContextOnLoadSettings(ImGuiContext* ctx)
-{
- ImGuiDockContext* dc = ctx->DockContext;
- DockContextPruneUnusedSettingsNodes(ctx);
- DockContextBuildNodesFromSettings(ctx, dc->SettingsNodes.Data, dc->SettingsNodes.Size);
-}
-
-void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_persistent_docking_references)
-{
- IM_UNUSED(ctx);
- IM_ASSERT(ctx == GImGui);
- DockBuilderRemoveNodeDockedWindows(root_id, clear_persistent_docking_references);
- DockBuilderRemoveNodeChildNodes(root_id);
-}
-
-// This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch
-void ImGui::DockContextRebuildNodes(ImGuiContext* ctx)
-{
- IMGUI_DEBUG_LOG_DOCKING("DockContextRebuild()\n");
- ImGuiDockContext* dc = ctx->DockContext;
- SaveIniSettingsToMemory();
- ImGuiID root_id = 0; // Rebuild all
- DockContextClearNodes(ctx, root_id, false);
- DockContextBuildNodesFromSettings(ctx, dc->SettingsNodes.Data, dc->SettingsNodes.Size);
- DockContextBuildAddWindowsToNodes(ctx, root_id);
-}
-
-// Docking context update function, called by NewFrame()
-void ImGui::DockContextUpdateUndocking(ImGuiContext* ctx)
-{
- ImGuiContext& g = *ctx;
- ImGuiDockContext* dc = ctx->DockContext;
- if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
- {
- if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0)
- DockContextClearNodes(ctx, 0, true);
- return;
- }
-
- // Setting NoSplit at runtime merges all nodes
- if (g.IO.ConfigDockingNoSplit)
- for (int n = 0; n < dc->Nodes.Data.Size; n++)
- if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
- if (node->IsRootNode() && node->IsSplitNode())
- {
- DockBuilderRemoveNodeChildNodes(node->ID);
- //dc->WantFullRebuild = true;
- }
-
- // Process full rebuild
-#if 0
- if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))
- dc->WantFullRebuild = true;
-#endif
- if (dc->WantFullRebuild)
- {
- DockContextRebuildNodes(ctx);
- dc->WantFullRebuild = false;
- }
-
- // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame)
- for (int n = 0; n < dc->Requests.Size; n++)
- {
- ImGuiDockRequest* req = &dc->Requests[n];
- if (req->Type == ImGuiDockRequestType_Undock && req->UndockTargetWindow)
- DockContextProcessUndockWindow(ctx, req->UndockTargetWindow);
- else if (req->Type == ImGuiDockRequestType_Undock && req->UndockTargetNode)
- DockContextProcessUndockNode(ctx, req->UndockTargetNode);
- }
-}
-
-// Docking context update function, called by NewFrame()
-void ImGui::DockContextUpdateDocking(ImGuiContext* ctx)
-{
- ImGuiContext& g = *ctx;
- ImGuiDockContext* dc = ctx->DockContext;
- if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
- return;
-
- // Process Docking requests
- for (int n = 0; n < dc->Requests.Size; n++)
- if (dc->Requests[n].Type == ImGuiDockRequestType_Dock)
- DockContextProcessDock(ctx, &dc->Requests[n]);
- dc->Requests.resize(0);
-
- // Create windows for each automatic docking nodes
- // We can have NULL pointers when we delete nodes, but because ID are recycled this should amortize nicely (and our node count will never be very high)
- for (int n = 0; n < dc->Nodes.Data.Size; n++)
- if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
- if (node->IsFloatingNode())
- DockNodeUpdate(node);
-}
-
-static ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id)
-{
- return (ImGuiDockNode*)ctx->DockContext->Nodes.GetVoidPtr(id);
-}
-
-ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx)
-{
- // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used)
- // FIXME-OPT FIXME-DOCKING: This is suboptimal, even if the node count is small enough not to be a worry. We should poke in ctx->Nodes to find a suitable ID faster.
- ImGuiID id = 0x0001;
- while (DockContextFindNodeByID(ctx, id) != NULL)
- id++;
- return id;
-}
-
-static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id)
-{
- // Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window.
- if (id == 0)
- id = DockContextGenNodeID(ctx);
- else
- IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL);
-
- // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings!
- IMGUI_DEBUG_LOG_DOCKING("DockContextAddNode 0x%08X\n", id);
- ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id);
- ctx->DockContext->Nodes.SetVoidPtr(node->ID, node);
- return node;
-}
-
-static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node)
-{
- ImGuiContext& g = *ctx;
- ImGuiDockContext* dc = ctx->DockContext;
-
- IMGUI_DEBUG_LOG_DOCKING("DockContextRemoveNode 0x%08X\n", node->ID);
- IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node);
- IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL);
- IM_ASSERT(node->Windows.Size == 0);
-
- if (node->HostWindow)
- node->HostWindow->DockNodeAsHost = NULL;
-
- ImGuiDockNode* parent_node = node->ParentNode;
- const bool merge = (merge_sibling_into_parent_node && parent_node != NULL);
- if (merge)
- {
- IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node);
- ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]);
- DockNodeTreeMerge(&g, parent_node, sibling_node);
- }
- else
- {
- for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++)
- if (parent_node->ChildNodes[n] == node)
- node->ParentNode->ChildNodes[n] = NULL;
- dc->Nodes.SetVoidPtr(node->ID, NULL);
- IM_DELETE(node);
- }
-}
-
-static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs)
-{
- const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs;
- const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs;
- return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a);
-}
-
-// Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here.
-struct ImGuiDockContextPruneNodeData
-{
- int CountWindows, CountChildWindows, CountChildNodes;
- ImGuiID RootID;
- ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootID = 0; }
-};
-
-// Garbage collect unused nodes (run once at init time)
-static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx)
-{
- ImGuiContext& g = *ctx;
- ImGuiDockContext* dc = ctx->DockContext;
- IM_ASSERT(g.Windows.Size == 0);
-
- ImPool pool;
- pool.Reserve(dc->SettingsNodes.Size);
-
- // Count child nodes and compute RootID
- for (int settings_n = 0; settings_n < dc->SettingsNodes.Size; settings_n++)
- {
- ImGuiDockNodeSettings* settings = &dc->SettingsNodes[settings_n];
- ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeID ? pool.GetByKey(settings->ParentNodeID) : 0;
- pool.GetOrAddByKey(settings->ID)->RootID = parent_data ? parent_data->RootID : settings->ID;
- if (settings->ParentNodeID)
- pool.GetOrAddByKey(settings->ParentNodeID)->CountChildNodes++;
- }
-
- // Count reference to dock ids from dockspaces
- // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes()
- for (int settings_n = 0; settings_n < dc->SettingsNodes.Size; settings_n++)
- {
- ImGuiDockNodeSettings* settings = &dc->SettingsNodes[settings_n];
- if (settings->ParentWindowID != 0)
- if (ImGuiWindowSettings* window_settings = FindWindowSettings(settings->ParentWindowID))
- if (window_settings->DockId)
- if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(window_settings->DockId))
- data->CountChildNodes++;
- }
-
- // Count reference to dock ids from window settings
- // We guard against the possibility of an invalid .ini file (RootID may point to a missing node)
- for (int settings_n = 0; settings_n < g.SettingsWindows.Size; settings_n++)
- if (ImGuiID dock_id = g.SettingsWindows[settings_n].DockId)
- if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id))
- {
- data->CountWindows++;
- if (ImGuiDockContextPruneNodeData* data_root = (data->RootID == dock_id) ? data : pool.GetByKey(data->RootID))
- data_root->CountChildWindows++;
- }
-
- // Prune
- for (int settings_n = 0; settings_n < dc->SettingsNodes.Size; settings_n++)
- {
- ImGuiDockNodeSettings* settings = &dc->SettingsNodes[settings_n];
- ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID);
- if (data->CountWindows > 1)
- continue;
- ImGuiDockContextPruneNodeData* data_root = (data->RootID == settings->ID) ? data : pool.GetByKey(data->RootID);
-
- bool remove = false;
- remove |= (data->CountWindows == 1 && settings->ParentNodeID == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode)); // Floating root node with only 1 window
- remove |= (data->CountWindows == 0 && settings->ParentNodeID == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window
- remove |= (data_root->CountChildWindows == 0);
- if (remove)
- {
- IMGUI_DEBUG_LOG_DOCKING("DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID);
- DockSettingsRemoveNodeReferences(&settings->ID, 1);
- settings->ID = 0;
- }
- }
-}
-
-static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count)
-{
- // Build nodes
- for (int node_n = 0; node_n < node_settings_count; node_n++)
- {
- ImGuiDockNodeSettings* settings = &node_settings_array[node_n];
- if (settings->ID == 0)
- continue;
- ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID);
- node->ParentNode = settings->ParentNodeID ? DockContextFindNodeByID(ctx, settings->ParentNodeID) : NULL;
- node->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
- node->Size = ImVec2(settings->Size.x, settings->Size.y);
- node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y);
- node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode;
- if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL)
- node->ParentNode->ChildNodes[0] = node;
- else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL)
- node->ParentNode->ChildNodes[1] = node;
- node->SelectedTabID = settings->SelectedWindowID;
- node->SplitAxis = settings->SplitAxis;
- node->LocalFlags |= (settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_);
-
- // Bind host window immediately if it already exist (in case of a rebuild)
- // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set.
- char host_window_title[20];
- ImGuiDockNode* root_node = DockNodeGetRootNode(node);
- node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_ARRAYSIZE(host_window_title)));
- }
-}
-
-void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id)
-{
- // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame)
- ImGuiContext& g = *ctx;
- for (int n = 0; n < g.Windows.Size; n++)
- {
- ImGuiWindow* window = g.Windows[n];
- if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1)
- continue;
- if (window->DockNode != NULL)
- continue;
-
- ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
- IM_ASSERT(node != NULL); // This should have been called after DockContextBuildNodesFromSettings()
- if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id)
- DockNodeAddWindow(node, window, true);
- }
-}
-
-//-----------------------------------------------------------------------------
-// Docking: ImGuiDockContext Docking/Undocking functions
-//-----------------------------------------------------------------------------
-// - DockContextQueueDock()
-// - DockContextQueueUndockWindow()
-// - DockContextQueueUndockNode()
-// - DockContextQueueNotifyRemovedNode()
-// - DockContextProcessDock()
-// - DockContextProcessUndockWindow()
-// - DockContextProcessUndockNode()
-// - DockContextCalcDropPosForDocking()
-//-----------------------------------------------------------------------------
-
-void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer)
-{
- IM_ASSERT(target != payload);
- ImGuiDockRequest req;
- req.Type = ImGuiDockRequestType_Dock;
- req.DockTargetWindow = target;
- req.DockTargetNode = target_node;
- req.DockPayload = payload;
- req.DockSplitDir = split_dir;
- req.DockSplitRatio = split_ratio;
- req.DockSplitOuter = split_outer;
- ctx->DockContext->Requests.push_back(req);
-}
-
-void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window)
-{
- ImGuiDockRequest req;
- req.Type = ImGuiDockRequestType_Undock;
- req.UndockTargetWindow = window;
- ctx->DockContext->Requests.push_back(req);
-}
-
-void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
-{
- ImGuiDockRequest req;
- req.Type = ImGuiDockRequestType_Undock;
- req.UndockTargetNode = node;
- ctx->DockContext->Requests.push_back(req);
-}
-
-void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node)
-{
- ImGuiDockContext* dc = ctx->DockContext;
- for (int n = 0; n < dc->Requests.Size; n++)
- if (dc->Requests[n].DockTargetNode == node)
- dc->Requests[n].Type = ImGuiDockRequestType_None;
-}
-
-void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req)
-{
- IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL));
- IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL);
-
- ImGuiContext& g = *ctx;
- IM_UNUSED(g);
-
- ImGuiWindow* payload_window = req->DockPayload; // Optional
- ImGuiWindow* target_window = req->DockTargetWindow;
- ImGuiDockNode* node = req->DockTargetNode;
- if (payload_window)
- IMGUI_DEBUG_LOG_DOCKING("DockContextProcessDock node 0x%08X target '%s' dock window '%s', split_dir %d\n", node ? node->ID : 0, target_window ? target_window->Name : "NULL", payload_window ? payload_window->Name : "NULL", req->DockSplitDir);
- else
- IMGUI_DEBUG_LOG_DOCKING("DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir);
-
- // Decide which Tab will be selected at the end of the operation
- ImGuiID next_selected_id = 0;
- ImGuiDockNode* payload_node = NULL;
- if (payload_window)
- {
- payload_node = payload_window->DockNodeAsHost;
- payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later.
- if (payload_node && payload_node->IsLeafNode())
- next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId;
- if (payload_node == NULL)
- next_selected_id = payload_window->ID;
- }
-
- // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well
- // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==.
- if (node)
- IM_ASSERT(node->LastFrameAlive <= g.FrameCount);
- if (node && target_window && node == target_window->DockNodeAsHost)
- IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode());
-
- // Create new node and add existing window to it
- if (node == NULL)
- {
- node = DockContextAddNode(ctx, 0);
- node->Pos = target_window->Pos;
- node->Size = target_window->Size;
- if (target_window->DockNodeAsHost == NULL)
- {
- DockNodeAddWindow(node, target_window, true);
- node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted;
- target_window->DockIsActive = true;
- }
- }
-
- ImGuiDir split_dir = req->DockSplitDir;
- if (split_dir != ImGuiDir_None)
- {
- // Split into one, one side will be our payload node unless we are dropping a loose window
- const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
- const int split_inheritor_child_idx = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0; // Current contents will be moved to the opposite side
- const float split_ratio = req->DockSplitRatio;
- DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node); // payload_node may be NULL here!
- ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1];
- new_node->HostWindow = node->HostWindow;
- node = new_node;
- }
- node->LocalFlags &= ~ImGuiDockNodeFlags_HiddenTabBar;
-
- if (node != payload_node)
- {
- // Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!)
- if (node->Windows.Size > 0 && node->TabBar == NULL)
- {
- DockNodeAddTabBar(node);
- for (int n = 0; n < node->Windows.Size; n++)
- TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
- }
-
- if (payload_node != NULL)
- {
- // Transfer full payload node (with 1+ child windows or child nodes)
- if (payload_node->IsSplitNode())
- {
- if (node->Windows.Size > 0)
- {
- // We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node.
- // In this situation, we move the windows of the target node into the currently visible node of the payload.
- // This allows us to preserve some of the underlying dock tree settings nicely.
- IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockCalc() early on and never submitted.
- ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows;
- if (visible_node->TabBar)
- IM_ASSERT(visible_node->TabBar->Tabs.Size > 0);
- DockNodeMoveWindows(node, visible_node);
- DockNodeMoveWindows(visible_node, node);
- DockSettingsRenameNodeReferences(node->ID, visible_node->ID);
- }
- if (node->IsCentralNode())
- {
- // Central node property needs to be moved to a leaf node, pick the last focused one.
- // FIXME-DOCKING: If we had to transfer other flags here, what would the policy be?
- ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeID);
- IM_ASSERT(last_focused_node != NULL);
- ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node);
- IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node));
- last_focused_node->LocalFlags |= ImGuiDockNodeFlags_CentralNode;
- node->LocalFlags &= ~ImGuiDockNodeFlags_CentralNode;
- last_focused_root_node->CentralNode = last_focused_node;
- }
-
- IM_ASSERT(node->Windows.Size == 0);
- DockNodeMoveChildNodes(node, payload_node);
- }
- else
- {
- const ImGuiID payload_dock_id = payload_node->ID;
- DockNodeMoveWindows(node, payload_node);
- DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
- }
- DockContextRemoveNode(ctx, payload_node, true);
- }
- else if (payload_window)
- {
- // Transfer single window
- const ImGuiID payload_dock_id = payload_window->DockId;
- node->VisibleWindow = payload_window;
- DockNodeAddWindow(node, payload_window, true);
- if (payload_dock_id != 0)
- DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
- }
- }
- else
- {
- // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar
- node->WantHiddenTabBarUpdate = true;
- }
-
- // Update selection immediately
- if (ImGuiTabBar* tab_bar = node->TabBar)
- tab_bar->NextSelectedTabId = next_selected_id;
- MarkIniSettingsDirty();
-}
-
-void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref)
-{
- (void)ctx;
- if (window->DockNode)
- DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId);
- else
- window->DockId = 0;
- window->Collapsed = false;
- window->DockIsActive = false;
- window->DockTabIsVisible = false;
- MarkIniSettingsDirty();
-}
-
-void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
-{
- IM_ASSERT(node->IsLeafNode());
- IM_ASSERT(node->Windows.Size >= 1);
-
- if (node->IsRootNode() || node->IsCentralNode())
- {
- // In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload.
- ImGuiDockNode* new_node = DockContextAddNode(ctx, 0);
- DockNodeMoveWindows(new_node, node);
- DockSettingsRenameNodeReferences(node->ID, new_node->ID);
- for (int n = 0; n < new_node->Windows.Size; n++)
- UpdateWindowParentAndRootLinks(new_node->Windows[n], new_node->Windows[n]->Flags, NULL);
- new_node->AuthorityForPos = new_node->AuthorityForSize = ImGuiDataAuthority_Window;
- new_node->WantMouseMove = true;
- }
- else
- {
- // Otherwise extract our node and merging our sibling back into the parent node.
- IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
- int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1;
- node->ParentNode->ChildNodes[index_in_parent] = NULL;
- DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]);
- node->ParentNode->AuthorityForViewport = ImGuiDataAuthority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport
- node->ParentNode = NULL;
- node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_Window;
- node->WantMouseMove = true;
- }
- MarkIniSettingsDirty();
-}
-
-// This is mostly used for automation.
-bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos)
-{
- if (split_outer)
- {
- IM_ASSERT(0);
- }
- else
- {
- ImGuiDockPreviewData split_data;
- DockNodePreviewDockCalc(target, target_node, payload, &split_data, false, split_outer);
- if (split_data.DropRectsDraw[split_dir+1].IsInverted())
- return false;
- *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter();
- return true;
- }
- return false;
-}
-
-//-----------------------------------------------------------------------------
-// Docking: ImGuiDockNode
-//-----------------------------------------------------------------------------
-// - DockNodeGetTabOrder()
-// - DockNodeAddWindow()
-// - DockNodeRemoveWindow()
-// - DockNodeMoveChildNodes()
-// - DockNodeMoveWindows()
-// - DockNodeApplyPosSizeToWindows()
-// - DockNodeHideHostWindow()
-// - ImGuiDockNodeFindInfoResults
-// - DockNodeFindInfo()
-// - DockNodeFindWindowByID()
-// - DockNodeUpdateVisibleFlagAndInactiveChilds()
-// - DockNodeUpdateVisibleFlag()
-// - DockNodeStartMouseMovingWindow()
-// - DockNodeUpdate()
-// - DockNodeUpdateWindowMenu()
-// - DockNodeUpdateTabBar()
-// - DockNodeAddTabBar()
-// - DockNodeRemoveTabBar()
-// - DockNodeIsDropAllowedOne()
-// - DockNodeIsDropAllowed()
-// - DockNodeCalcTabBarLayout()
-// - DockNodeCalcSplitRects()
-// - DockNodeCalcDropRectsAndTestMousePos()
-// - DockNodePreviewDockCalc()
-// - DockNodePreviewDockRender()
-//-----------------------------------------------------------------------------
-
-ImGuiDockNode::ImGuiDockNode(ImGuiID id)
-{
- ID = id;
- SharedFlags = LocalFlags = ImGuiDockNodeFlags_None;
- ParentNode = ChildNodes[0] = ChildNodes[1] = NULL;
- TabBar = NULL;
- SplitAxis = ImGuiAxis_None;
-
- State = ImGuiDockNodeState_Unknown;
- HostWindow = VisibleWindow = NULL;
- CentralNode = OnlyNodeWithWindows = NULL;
- LastFrameAlive = LastFrameActive = LastFrameFocused = -1;
- LastFocusedNodeID = 0;
- SelectedTabID = 0;
- WantCloseTabID = 0;
- AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode;
- AuthorityForViewport = ImGuiDataAuthority_Auto;
- IsVisible = true;
- IsFocused = HasCloseButton = HasWindowMenuButton = EnableCloseButton = false;
- WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false;
- MarkedForPosSizeWrite = false;
-}
-
-ImGuiDockNode::~ImGuiDockNode()
-{
- IM_DELETE(TabBar);
- TabBar = NULL;
- ChildNodes[0] = ChildNodes[1] = NULL;
-}
-
-int ImGui::DockNodeGetTabOrder(ImGuiWindow* window)
-{
- ImGuiTabBar* tab_bar = window->DockNode->TabBar;
- if (tab_bar == NULL)
- return -1;
- ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, window->ID);
- return tab ? tab_bar->GetTabOrder(tab) : -1;
-}
-
-static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar)
-{
- ImGuiContext& g = *GImGui; (void)g;
- if (window->DockNode)
- {
- // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node)
- IM_ASSERT(window->DockNode->ID != node->ID);
- DockNodeRemoveWindow(window->DockNode, window, 0);
- }
- IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL);
- IMGUI_DEBUG_LOG_DOCKING("DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name);
-
- node->Windows.push_back(window);
- node->WantHiddenTabBarUpdate = true;
- window->DockNode = node;
- window->DockId = node->ID;
- window->DockIsActive = (node->Windows.Size > 1);
- window->DockTabWantClose = false;
-
- // If more than 2 windows appeared on the same frame, we'll create a new hosting DockNode from the point of the second window submission.
- // Then we need to hide the first window (after its been output) otherwise it would be visible as a standalone window for one frame.
- if (node->HostWindow == NULL && node->Windows.Size == 2 && node->Windows[0]->WasActive == false)
- {
- node->Windows[0]->Hidden = true;
- node->Windows[0]->HiddenFramesCanSkipItems = 1;
- }
-
- // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage.
- // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one.
- if (node->HostWindow == NULL && node->IsFloatingNode())
- {
- if (node->AuthorityForPos == ImGuiDataAuthority_Auto)
- node->AuthorityForPos = ImGuiDataAuthority_Window;
- if (node->AuthorityForSize == ImGuiDataAuthority_Auto)
- node->AuthorityForSize = ImGuiDataAuthority_Window;
- if (node->AuthorityForViewport == ImGuiDataAuthority_Auto)
- node->AuthorityForViewport = ImGuiDataAuthority_Window;
- }
-
- // Add to tab bar if requested
- if (add_to_tab_bar)
- {
- if (node->TabBar == NULL)
- {
- DockNodeAddTabBar(node);
- node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabID;
-
- // Add existing windows
- for (int n = 0; n < node->Windows.Size - 1; n++)
- TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
- }
- TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window);
- }
-
- DockNodeUpdateVisibleFlag(node);
-
- // Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame.
- if (node->HostWindow)
- UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow);
-}
-
-static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id)
-{
- ImGuiContext& g = *GImGui;
- IM_ASSERT(window->DockNode == node);
- //IM_ASSERT(window->RootWindow == node->HostWindow);
- //IM_ASSERT(window->LastFrameActive < g.FrameCount); // We may call this from Begin()
- IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID);
- IMGUI_DEBUG_LOG_DOCKING("DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name);
-
- window->DockNode = NULL;
- window->DockIsActive = window->DockTabWantClose = false;
- window->DockId = save_dock_id;
- UpdateWindowParentAndRootLinks(window, window->Flags & ~ImGuiWindowFlags_ChildWindow, NULL); // Update immediately
-
- // Remove window
- bool erased = false;
- for (int n = 0; n < node->Windows.Size; n++)
- if (node->Windows[n] == window)
- {
- node->Windows.erase(node->Windows.Data + n);
- erased = true;
- break;
- }
- IM_ASSERT(erased);
- if (node->VisibleWindow == window)
- node->VisibleWindow = NULL;
-
- // Remove tab and possibly tab bar
- node->WantHiddenTabBarUpdate = true;
- if (node->TabBar)
- {
- TabBarRemoveTab(node->TabBar, window->ID);
- const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2;
- if (node->Windows.Size < tab_count_threshold_for_tab_bar)
- DockNodeRemoveTabBar(node);
- }
-
- if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID)
- {
- // Automatic dock node delete themselves if they are not holding at least one tab
- DockContextRemoveNode(&g, node, true);
- return;
- }
-
- if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow)
- {
- ImGuiWindow* remaining_window = node->Windows[0];
- if (node->HostWindow->ViewportOwned && node->IsRootNode())
- {
- // Transfer viewport back to the remaining loose window
- IM_ASSERT(node->HostWindow->Viewport->Window == node->HostWindow);
- node->HostWindow->Viewport->Window = remaining_window;
- node->HostWindow->Viewport->ID = remaining_window->ID;
- }
- remaining_window->Collapsed = node->HostWindow->Collapsed;
- }
-
- // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree
- DockNodeUpdateVisibleFlag(node);
-}
-
-static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
-{
- IM_ASSERT(dst_node->Windows.Size == 0);
- dst_node->ChildNodes[0] = src_node->ChildNodes[0];
- dst_node->ChildNodes[1] = src_node->ChildNodes[1];
- if (dst_node->ChildNodes[0])
- dst_node->ChildNodes[0]->ParentNode = dst_node;
- if (dst_node->ChildNodes[1])
- dst_node->ChildNodes[1]->ParentNode = dst_node;
- dst_node->SplitAxis = src_node->SplitAxis;
- dst_node->SizeRef = src_node->SizeRef;
- src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL;
-}
-
-static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
-{
- // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered)
- IM_ASSERT(src_node && dst_node && dst_node != src_node);
- ImGuiTabBar* src_tab_bar = src_node->TabBar;
- if (src_tab_bar != NULL)
- IM_ASSERT(src_node->Windows.Size == src_node->TabBar->Tabs.Size);
-
- // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.)
- bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL);
- if (move_tab_bar)
- {
- dst_node->TabBar = src_node->TabBar;
- src_node->TabBar = NULL;
- }
-
- for (int n = 0; n < src_node->Windows.Size; n++)
- {
- ImGuiWindow* window = src_tab_bar ? src_tab_bar->Tabs[n].Window : src_node->Windows[n];
- window->DockNode = NULL;
- window->DockIsActive = false;
- DockNodeAddWindow(dst_node, window, move_tab_bar ? false : true);
- }
- src_node->Windows.clear();
-
- if (!move_tab_bar && src_node->TabBar)
- {
- if (dst_node->TabBar)
- dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId;
- DockNodeRemoveTabBar(src_node);
- }
-}
-
-static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node)
-{
- for (int n = 0; n < node->Windows.Size; n++)
- {
- SetWindowPos(node->Windows[n], node->Pos, ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame
- SetWindowSize(node->Windows[n], node->Size, ImGuiCond_Always);
- }
-}
-
-static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node)
-{
- if (node->HostWindow)
- {
- if (node->HostWindow->DockNodeAsHost == node)
- node->HostWindow->DockNodeAsHost = NULL;
- node->HostWindow = NULL;
- }
-
- if (node->Windows.Size == 1)
- {
- node->VisibleWindow = node->Windows[0];
- node->Windows[0]->DockIsActive = false;
- }
-
- if (node->TabBar)
- DockNodeRemoveTabBar(node);
-}
-
-// Search function called once by root node in DockNodeUpdate()
-struct ImGuiDockNodeFindInfoResults
-{
- ImGuiDockNode* CentralNode;
- ImGuiDockNode* FirstNodeWithWindows;
- int CountNodesWithWindows;
- //ImGuiWindowClass WindowClassForMerges;
-
- ImGuiDockNodeFindInfoResults() { CentralNode = FirstNodeWithWindows = NULL; CountNodesWithWindows = 0; }
-};
-
-static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeFindInfoResults* results)
-{
- if (node->Windows.Size > 0)
- {
- if (results->FirstNodeWithWindows == NULL)
- results->FirstNodeWithWindows = node;
- results->CountNodesWithWindows++;
- }
- if (node->IsCentralNode())
- {
- IM_ASSERT(results->CentralNode == NULL); // Should be only one
- IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this.");
- results->CentralNode = node;
- }
- if (results->CountNodesWithWindows > 1 && results->CentralNode != NULL)
- return;
- if (node->ChildNodes[0])
- DockNodeFindInfo(node->ChildNodes[0], results);
- if (node->ChildNodes[1])
- DockNodeFindInfo(node->ChildNodes[1], results);
-}
-
-static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id)
-{
- IM_ASSERT(id != 0);
- for (int n = 0; n < node->Windows.Size; n++)
- if (node->Windows[n]->ID == id)
- return node->Windows[n];
- return NULL;
-}
-
-// - Remove inactive windows/nodes.
-// - Update visibility flag.
-static void ImGui::DockNodeUpdateVisibleFlagAndInactiveChilds(ImGuiDockNode* node)
-{
- ImGuiContext& g = *GImGui;
-
- IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
-
- // Inherit most flags
- if (node->ParentNode)
- node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
-
- // Recurse into children
- // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'.
- // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node'
- // If 'node->ChildNode[1]' delete itself, then 'node->ChildNode[0]->Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless)
- if (node->ChildNodes[0])
- DockNodeUpdateVisibleFlagAndInactiveChilds(node->ChildNodes[0]);
- if (node->ChildNodes[1])
- DockNodeUpdateVisibleFlagAndInactiveChilds(node->ChildNodes[1]);
-
- // Remove inactive windows
- for (int window_n = 0; window_n < node->Windows.Size; window_n++)
- {
- ImGuiWindow* window = node->Windows[window_n];
- IM_ASSERT(window->DockNode == node);
-
- bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
- bool remove = false;
- remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount);
- remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabID == window->ID) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument); // Submit all _expected_ closure from last frame
- remove |= (window->DockTabWantClose);
- if (!remove)
- continue;
- window->DockTabWantClose = false;
- if (node->Windows.Size == 1 && !node->IsCentralNode())
- {
- DockNodeHideHostWindow(node);
- node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
- DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return
- return;
- }
- DockNodeRemoveWindow(node, window, node->ID);
- window_n--;
- }
-
- // Auto-hide tab bar option
- ImGuiDockNodeFlags node_flags = node->GetMergedFlags();
- if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar())
- node->WantHiddenTabBarToggle = true;
- node->WantHiddenTabBarUpdate = false;
-
- // Apply toggles at a single point of the frame (here!)
- if (node->Windows.Size > 1)
- node->LocalFlags &= ~ImGuiDockNodeFlags_HiddenTabBar;
- else if (node->WantHiddenTabBarToggle)
- node->LocalFlags ^= ImGuiDockNodeFlags_HiddenTabBar;
- node->WantHiddenTabBarToggle = false;
-
- DockNodeUpdateVisibleFlag(node);
-}
-
-static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node)
-{
- // Update visibility flag
- bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode();
- is_visible |= (node->Windows.Size > 0);
- is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible);
- is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible);
- node->IsVisible = is_visible;
-}
-
-static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window)
-{
- ImGuiContext& g = *GImGui;
- IM_ASSERT(node->WantMouseMove == true);
- ImVec2 backup_active_click_offset = g.ActiveIdClickOffset;
- StartMouseMovingWindow(window);
- g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision.
- node->WantMouseMove = false;
- g.ActiveIdClickOffset = backup_active_click_offset;
-}
-
-static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
-{
- ImGuiContext& g = *GImGui;
- IM_ASSERT(node->LastFrameActive != g.FrameCount);
- node->LastFrameAlive = g.FrameCount;
- node->MarkedForPosSizeWrite = false;
-
- node->CentralNode = node->OnlyNodeWithWindows = NULL;
- if (node->IsRootNode())
- {
- DockNodeUpdateVisibleFlagAndInactiveChilds(node);
-
- // FIXME-DOCK: Merge this scan into the one above.
- // - Setup central node pointers
- // - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!)
- ImGuiDockNodeFindInfoResults results;
- DockNodeFindInfo(node, &results);
- node->CentralNode = results.CentralNode;
- node->OnlyNodeWithWindows = (results.CountNodesWithWindows == 1) ? results.FirstNodeWithWindows : NULL;
- if (node->LastFocusedNodeID == 0 && results.FirstNodeWithWindows != NULL)
- node->LastFocusedNodeID = results.FirstNodeWithWindows->ID;
-
- // Copy the window class from of our first window so it can be used for proper dock filtering.
- // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy.
- // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec.
- if (ImGuiDockNode* first_node_with_windows = results.FirstNodeWithWindows)
- {
- node->WindowClass = first_node_with_windows->Windows[0]->WindowClass;
- for (int n = 1; n < first_node_with_windows->Windows.Size; n++)
- if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false)
- {
- node->WindowClass = first_node_with_windows->Windows[n]->WindowClass;
- break;
- }
- }
- }
-
- // Remove tab bar if not needed
- if (node->TabBar && node->IsNoTabBar())
- DockNodeRemoveTabBar(node);
-
- // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId)
- bool want_to_hide_host_window = false;
- if (node->Windows.Size <= 1 && node->IsFloatingNode() && node->IsLeafNode())
- if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar))
- want_to_hide_host_window = true;
- if (want_to_hide_host_window)
- {
- if (node->Windows.Size == 1)
- {
- // Floating window pos/size is authoritative
- ImGuiWindow* single_window = node->Windows[0];
- node->Pos = single_window->Pos;
- node->Size = single_window->SizeFull;
- node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
-
- // Transfer focus immediately so when we revert to a regular window it is immediately selected
- if (node->HostWindow && g.NavWindow == node->HostWindow)
- FocusWindow(single_window);
- if (node->HostWindow)
- {
- single_window->Viewport = node->HostWindow->Viewport;
- single_window->ViewportId = node->HostWindow->ViewportId;
- if (node->HostWindow->ViewportOwned)
- {
- single_window->Viewport->Window = single_window;
- single_window->ViewportOwned = true;
- }
- }
- }
-
- DockNodeHideHostWindow(node);
- node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
- node->WantCloseAll = false;
- node->WantCloseTabID = 0;
- node->HasCloseButton = node->HasWindowMenuButton = node->EnableCloseButton = false;
- node->LastFrameActive = g.FrameCount;
-
- if (node->WantMouseMove && node->Windows.Size == 1)
- DockNodeStartMouseMovingWindow(node, node->Windows[0]);
- return;
- }
-
- // In some circumstance we will defer creating the host window (so everything will be kept hidden),
- // while the expected visible window is resizing itself.
- // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled,
- // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up:
- // N+0: Begin(): window created (with no known size), node is created
- // N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible
- // N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible
- // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code.
- // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin().
- // In reality it isn't very important as user quickly ends up with size data in .ini file.
- if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode())
- {
- IM_ASSERT(node->Windows.Size > 0);
- ImGuiWindow* ref_window = NULL;
- if (node->SelectedTabID != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them!
- ref_window = DockNodeFindWindowByID(node, node->SelectedTabID);
- if (ref_window == NULL)
- ref_window = node->Windows[0];
- if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0)
- {
- node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing;
- return;
- }
- }
-
- const ImGuiDockNodeFlags node_flags = node->GetMergedFlags();
-
- // Bind or create host window
- ImGuiWindow* host_window = NULL;
- bool beginned_into_host_window = false;
- if (node->IsDockSpace())
- {
- // [Explicit root dockspace node]
- IM_ASSERT(node->HostWindow);
- node->EnableCloseButton = false;
- node->HasCloseButton = (node_flags & ImGuiDockNodeFlags_NoCloseButton) == 0;
- node->HasWindowMenuButton = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
- host_window = node->HostWindow;
- }
- else
- {
- // [Automatic root or child nodes]
- node->EnableCloseButton = false;
- node->HasCloseButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
- node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
- for (int window_n = 0; window_n < node->Windows.Size; window_n++)
- {
- // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call.
- ImGuiWindow* window = node->Windows[window_n];
- window->DockIsActive = (node->Windows.Size > 1);
- node->EnableCloseButton |= window->HasCloseButton;
- }
-
- if (node->IsRootNode() && node->IsVisible)
- {
- ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
-
- // Sync Pos
- if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window)
- SetNextWindowPos(ref_window->Pos);
- else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode)
- SetNextWindowPos(node->Pos);
-
- // Sync Size
- if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
- SetNextWindowSize(ref_window->SizeFull);
- else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode)
- SetNextWindowSize(node->Size);
-
- // Sync Collapsed
- if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
- SetNextWindowCollapsed(ref_window->Collapsed);
-
- // Sync Viewport
- if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window)
- SetNextWindowViewport(ref_window->ViewportId);
-
- SetNextWindowClass(&node->WindowClass);
-
- // Begin into the host window
- char window_label[20];
- DockNodeGetHostWindowTitle(node, window_label, IM_ARRAYSIZE(window_label));
- ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost;
- window_flags |= ImGuiWindowFlags_NoFocusOnAppearing;
- window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse;
- window_flags |= ImGuiWindowFlags_NoTitleBar;
-
- PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
- Begin(window_label, NULL, window_flags);
- PopStyleVar();
- beginned_into_host_window = true;
-
- node->HostWindow = host_window = g.CurrentWindow;
- host_window->DockNodeAsHost = node;
- host_window->DC.CursorPos = host_window->Pos;
- node->Pos = host_window->Pos;
- node->Size = host_window->Size;
-
- // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow)
- // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags.
- // One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again.
- // When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window
- // during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back
- // after the dock host window, losing their top-most status.
- if (node->HostWindow->Appearing)
- BringWindowToDisplayFront(node->HostWindow);
-
- node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
- }
- else if (node->ParentNode)
- {
- node->HostWindow = host_window = node->ParentNode->HostWindow;
- node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
- }
- if (node->WantMouseMove && node->HostWindow)
- DockNodeStartMouseMovingWindow(node, node->HostWindow);
- }
-
- // Update focused node (the one whose title bar is highlight) within a node tree
- if (node->IsSplitNode())
- IM_ASSERT(node->TabBar == NULL);
- if (node->IsRootNode())
- if (g.NavWindow && g.NavWindow->RootWindowDockStop->DockNode && g.NavWindow->RootWindowDockStop->ParentWindow == host_window)
- node->LastFocusedNodeID = g.NavWindow->RootWindowDockStop->DockNode->ID;
-
- // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size after
- // processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order!
- const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0;
- if (render_dockspace_bg)
- {
- host_window->DrawList->ChannelsSplit(2);
- host_window->DrawList->ChannelsSetCurrent(1);
- }
-
- // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace
- const ImGuiDockNode* central_node = node->CentralNode;
- const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty();
- bool central_node_hole_register_hit_test_hole = central_node_hole;
- if (central_node_hole)
- if (const ImGuiPayload* payload = ImGui::GetDragDropPayload())
- if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow**)payload->Data))
- central_node_hole_register_hit_test_hole = false;
- if (central_node_hole_register_hit_test_hole)
- {
- // Add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily.
- IM_ASSERT(node->IsDockSpace()); // We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window->ParentNode
- ImRect central_hole(central_node->Pos, central_node->Pos + central_node->Size);
- central_hole.Expand(ImVec2(-WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS, -WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS));
- if (central_node_hole && !central_hole.IsInverted())
- {
- SetWindowHitTestHole(host_window, central_hole.Min, central_hole.Max - central_hole.Min);
- SetWindowHitTestHole(host_window->ParentWindow, central_hole.Min, central_hole.Max - central_hole.Min);
- }
- }
-
- // Update position/size, process and draw resizing splitters
- if (node->IsRootNode() && host_window)
- {
- DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size);
- DockNodeTreeUpdateSplitter(node);
- }
-
- // Draw empty node background (currently can only be the Central Node)
- if (host_window && node->IsEmpty() && node->IsVisible && !(node_flags & ImGuiDockNodeFlags_PassthruCentralNode))
- host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_DockingEmptyBg));
-
- // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set.
- if (render_dockspace_bg && node->IsVisible)
- {
- host_window->DrawList->ChannelsSetCurrent(0);
- if (central_node_hole)
- RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f);
- else
- host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f);
- host_window->DrawList->ChannelsMerge();
- }
-
- // Draw and populate Tab Bar
- if (host_window && node->Windows.Size > 0)
- {
- DockNodeUpdateTabBar(node, host_window);
- }
- else
- {
- node->WantCloseAll = false;
- node->WantCloseTabID = 0;
- node->IsFocused = false;
- }
- if (node->TabBar && node->TabBar->SelectedTabId)
- node->SelectedTabID = node->TabBar->SelectedTabId;
- else if (node->Windows.Size > 0)
- node->SelectedTabID = node->Windows[0]->ID;
-
- // Draw payload drop target
- if (host_window && node->IsVisible)
- if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindow != host_window))
- BeginAsDockableDragDropTarget(host_window);
-
- // We update this after DockNodeUpdateTabBar()
- node->LastFrameActive = g.FrameCount;
-
- // Recurse into children
- // FIXME-DOCK FIXME-OPT: Should not need to recurse into children
- if (host_window)
- {
- if (node->ChildNodes[0])
- DockNodeUpdate(node->ChildNodes[0]);
- if (node->ChildNodes[1])
- DockNodeUpdate(node->ChildNodes[1]);
-
- // Render outer borders last (after the tab bar)
- if (node->IsRootNode())
- RenderWindowOuterBorders(host_window);
- }
-
- // End host window
- if (beginned_into_host_window) //-V1020
- End();
-}
-
-// Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame.
-static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs)
-{
- ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window;
- ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window;
- if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder))
- return d;
- return (a->BeginOrderWithinContext - b->BeginOrderWithinContext);
-}
-
-static ImGuiID ImGui::DockNodeUpdateWindowMenu(ImGuiDockNode* node, ImGuiTabBar* tab_bar)
-{
- // Try to position the menu so it is more likely to stays within the same viewport
- ImGuiContext& g = *GImGui;
- ImGuiID ret_tab_id = 0;
- if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left)
- SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f));
- else
- SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f));
- if (BeginPopup("#WindowMenu"))
- {
- node->IsFocused = true;
- if (tab_bar->Tabs.Size == 1)
- {
- if (MenuItem("Hide tab bar", NULL, node->IsHiddenTabBar()))
- node->WantHiddenTabBarToggle = true;
- }
- else
- {
- for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
- {
- ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
- IM_ASSERT(tab->Window != NULL);
- if (Selectable(tab->Window->Name, tab->ID == tab_bar->SelectedTabId))
- ret_tab_id = tab->ID;
- SameLine();
- Text(" ");
- }
- }
- EndPopup();
- }
- return ret_tab_id;
-}
-
-static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window)
-{
- ImGuiContext& g = *GImGui;
- ImGuiStyle& style = g.Style;
-
- const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
- const bool closed_all = node->WantCloseAll && node_was_active;
- const ImGuiID closed_one = node->WantCloseTabID && node_was_active;
- node->WantCloseAll = false;
- node->WantCloseTabID = 0;
-
- // Decide if we should use a focused title bar color
- bool is_focused = false;
- ImGuiDockNode* root_node = DockNodeGetRootNode(node);
- if (g.NavWindowingTarget)
- is_focused = (g.NavWindowingTarget->DockNode == node);
- else if (g.NavWindow && g.NavWindow->RootWindowForTitleBarHighlight == host_window->RootWindow && root_node->LastFocusedNodeID == node->ID)
- is_focused = true;
-
- // Hidden tab bar will show a triangle on the upper-left (in Begin)
- if (node->IsHiddenTabBar() || node->IsNoTabBar())
- {
- node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
- node->IsFocused = is_focused;
- if (is_focused)
- node->LastFrameFocused = g.FrameCount;
- if (node->VisibleWindow)
- {
- // Notify root of visible window (used to display title in OS task bar)
- if (is_focused || root_node->VisibleWindow == NULL)
- root_node->VisibleWindow = node->VisibleWindow;
- if (node->TabBar)
- node->TabBar->VisibleTabId = node->VisibleWindow->ID;
- }
- return;
- }
-
- // Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed
- bool backup_skip_item = host_window->SkipItems;
- if (!node->IsDockSpace())
- {
- host_window->SkipItems = false;
- host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
- host_window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu);
- }
-
- // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID.
- // This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs,
- // as docked windows themselves will override the stack with their own root ID.
- PushOverrideID(node->ID);
- ImGuiTabBar* tab_bar = node->TabBar;
- bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden
- if (tab_bar == NULL)
- {
- DockNodeAddTabBar(node);
- tab_bar = node->TabBar;
- }
-
- ImGuiID focus_tab_id = 0;
- node->IsFocused = is_focused;
-
- const ImGuiDockNodeFlags node_flags = node->GetMergedFlags();
- const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
- const bool has_close_button = (node_flags & ImGuiDockNodeFlags_NoCloseButton) == 0;
-
- // In a dock node, the Collapse Button turns into the Window Menu button.
- // FIXME-DOCK FIXME-OPT: Could we recycle popups id accross multiple dock nodes?
- if (has_window_menu_button && IsPopupOpen("#WindowMenu"))
- {
- if (ImGuiID tab_id = DockNodeUpdateWindowMenu(node, tab_bar))
- focus_tab_id = tab_bar->NextSelectedTabId = tab_id;
- is_focused |= node->IsFocused;
- }
-
- // Layout
- ImRect title_bar_rect, tab_bar_rect;
- ImVec2 window_menu_button_pos;
- DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos);
-
- // Title bar
- if (is_focused)
- node->LastFrameFocused = g.FrameCount;
- ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
- host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, ImDrawCornerFlags_Top);
-
- // Docking/Collapse button
- if (has_window_menu_button)
- {
- if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node))
- OpenPopup("#WindowMenu");
- if (IsItemActive())
- focus_tab_id = tab_bar->SelectedTabId;
- }
-
- // Submit new tabs and apply NavWindow focus back to the tab bar. They will be added as Unsorted and sorted below based on relative DockOrder value.
- const int tabs_count_old = tab_bar->Tabs.Size;
- for (int window_n = 0; window_n < node->Windows.Size; window_n++)
- {
- ImGuiWindow* window = node->Windows[window_n];
- if (g.NavWindow && g.NavWindow->RootWindowDockStop == window)
- tab_bar->SelectedTabId = window->ID;
- if (TabBarFindTabByID(tab_bar, window->ID) == NULL)
- TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window);
- }
-
- // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value
- int tabs_unsorted_start = tab_bar->Tabs.Size;
- for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--)
- {
- // FIXME-DOCKING: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting?
- tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted;
- tabs_unsorted_start = tab_n;
- }
- if (tab_bar->Tabs.Size > tabs_unsorted_start)
- {
- IMGUI_DEBUG_LOG_DOCKING("In node 0x%08X: %d new appearing tabs:%s\n", node->ID, tab_bar->Tabs.Size - tabs_unsorted_start, (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ? " (will sort)" : "");
- for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++)
- IMGUI_DEBUG_LOG_DOCKING(" - Tab '%s' Order %d\n", tab_bar->Tabs[tab_n].Window->Name, tab_bar->Tabs[tab_n].Window->DockOrder);
- if (tab_bar->Tabs.Size > tabs_unsorted_start + 1)
- ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder);
- }
-
- // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated
- if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabID) != NULL)
- tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabID;
- else if (tab_bar->Tabs.Size > tabs_count_old)
- tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->ID;
-
- // Begin tab bar
- ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons);
- tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;
- if (!host_window->Collapsed && is_focused)
- tab_bar_flags |= ImGuiTabBarFlags_IsFocused;
- BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags, node);
- //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255));
-
- // Submit actual tabs
- node->VisibleWindow = NULL;
- for (int window_n = 0; window_n < node->Windows.Size; window_n++)
- {
- ImGuiWindow* window = node->Windows[window_n];
- if ((closed_all || closed_one == window->ID) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument))
- continue;
- if (window->LastFrameActive + 1 >= g.FrameCount || !node_was_active)
- {
- ImGuiTabItemFlags tab_item_flags = 0;
- if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
- tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
- if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
- tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
-
- bool tab_open = true;
- TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window);
- if (!tab_open)
- node->WantCloseTabID = window->ID;
- if (tab_bar->VisibleTabId == window->ID)
- node->VisibleWindow = window;
-
- // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
- window->DockTabItemStatusFlags = host_window->DC.LastItemStatusFlags;
- window->DockTabItemRect = host_window->DC.LastItemRect;
-
- // Update navigation ID on menu layer
- if (g.NavWindow && g.NavWindow->RootWindowDockStop == window && (window->DC.NavLayerActiveMask & (1 << 1)) == 0)
- host_window->NavLastIds[1] = window->ID;
- }
- }
-
- // Notify root of visible window (used to display title in OS task bar)
- if (node->VisibleWindow)
- if (is_focused || root_node->VisibleWindow == NULL)
- root_node->VisibleWindow = node->VisibleWindow;
-
- // Close button (after VisibleWindow was updated)
- // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->ID may be != from tab_bar->SelectedTabId
- if (has_close_button && node->VisibleWindow)
- {
- if (!node->VisibleWindow->HasCloseButton)
- {
- PushItemFlag(ImGuiItemFlags_Disabled, true);
- PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.5f));
- }
- const float button_sz = g.FontSize;
- if (CloseButton(host_window->GetID("#CLOSE"), title_bar_rect.GetTR() + ImVec2(-style.FramePadding.x * 2.0f - button_sz, 0.0f)))
- if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->VisibleTabId))
- {
- node->WantCloseTabID = tab->ID;
- TabBarCloseTab(tab_bar, tab);
- }
- //if (IsItemActive())
- // focus_tab_id = tab_bar->SelectedTabId;
- if (!node->VisibleWindow->HasCloseButton)
- {
- PopStyleColor();
- PopItemFlag();
- }
- }
-
- // When clicking on the title bar outside of tabs, we still focus the selected tab for that node
- // FIXME: TabItem use AllowItemOverlap so we manually perform a more specific test for now (hovered || held)
- ImGuiID title_bar_id = host_window->GetID("#TITLEBAR");
- if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id)
- {
- bool held;
- ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held);
- if (held)
- {
- if (IsMouseClicked(0))
- focus_tab_id = tab_bar->SelectedTabId;
-
- // Forward moving request to selected window
- if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
- StartMouseDragFromTitleBar(tab->Window, node, false);
- }
- }
-
- // Forward focus from host node to selected window
- //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget)
- // focus_tab_id = tab_bar->SelectedTabId;
-
- // When clicked on a tab we requested focus to the docked child
- // This overrides the value set by "forward focus from host node to selected window".
- if (tab_bar->NextSelectedTabId)
- focus_tab_id = tab_bar->NextSelectedTabId;
-
- // Apply navigation focus
- if (focus_tab_id != 0)
- if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id))
- {
- FocusWindow(tab->Window);
- NavInitWindow(tab->Window, false);
- }
-
- EndTabBar();
- PopID();
-
- // Restore SkipItems flag
- if (!node->IsDockSpace())
- {
- host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
- host_window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
- host_window->SkipItems = backup_skip_item;
- }
-}
-
-static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node)
-{
- IM_ASSERT(node->TabBar == NULL);
- node->TabBar = IM_NEW(ImGuiTabBar);
-}
-
-static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node)
-{
- if (node->TabBar == NULL)
- return;
- IM_DELETE(node->TabBar);
- node->TabBar = NULL;
-}
-
-static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window)
-{
- if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext)
- return false;
-
- ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass;
- ImGuiWindowClass* payload_class = &payload->WindowClass;
- if (host_class->ClassId != payload_class->ClassId)
- {
- if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0)
- return true;
- if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0)
- return true;
- return false;
- }
-
- return true;
-}
-
-static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload)
-{
- if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode())
- return true;
-
- const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1;
- for (int payload_n = 0; payload_n < payload_count; payload_n++)
- {
- ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload;
- if (DockNodeIsDropAllowedOne(payload, host_window))
- return true;
- }
- return false;
-}
-
-// window menu button == collapse button when not in a dock node.
-// FIXME: This is similar to RenderWindowTitleBarContents, may want to share code.
-static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos)
-{
- ImGuiContext& g = *GImGui;
- ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + g.FontSize + g.Style.FramePadding.y * 2.0f);
- if (out_title_rect) { *out_title_rect = r; }
-
- ImVec2 window_menu_button_pos = r.Min;
- r.Min.x += g.Style.FramePadding.x;
- r.Max.x -= g.Style.FramePadding.x;
- if (node->HasCloseButton)
- {
- r.Max.x -= g.FontSize;// +1.0f; // In DockNodeUpdateTabBar() we currently display a disabled close button even if there is none.
- }
- if (node->HasWindowMenuButton && g.Style.WindowMenuButtonPosition == ImGuiDir_Left)
- {
- r.Min.x += g.FontSize; // + g.Style.ItemInnerSpacing.x; // <-- Adding ItemInnerSpacing makes the title text moves slightly when in a docking tab bar. Instead we adjusted RenderArrowDockMenu()
- }
- else if (node->HasWindowMenuButton && g.Style.WindowMenuButtonPosition == ImGuiDir_Right)
- {
- r.Max.x -= g.FontSize + g.Style.FramePadding.x;
- window_menu_button_pos = ImVec2(r.Max.x, r.Min.y);
- }
- if (out_tab_bar_rect) { *out_tab_bar_rect = r; }
- if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; }
-}
-
-void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired)
-{
- ImGuiContext& g = *GImGui;
- const float dock_spacing = g.Style.ItemInnerSpacing.x;
- const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
- pos_new[axis ^ 1] = pos_old[axis ^ 1];
- size_new[axis ^ 1] = size_old[axis ^ 1];
-
- // Distribute size on given axis (with a desired size or equally)
- const float w_avail = size_old[axis] - dock_spacing;
- if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f)
- {
- size_new[axis] = size_new_desired[axis];
- size_old[axis] = IM_FLOOR(w_avail - size_new[axis]);
- }
- else
- {
- size_new[axis] = IM_FLOOR(w_avail * 0.5f);
- size_old[axis] = IM_FLOOR(w_avail - size_new[axis]);
- }
-
- // Position each node
- if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
- {
- pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing;
- }
- else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up)
- {
- pos_new[axis] = pos_old[axis];
- pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing;
- }
-}
-
-// Retrieve the drop rectangles for a given direction or for the center + perform hit testing.
-bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos)
-{
- ImGuiContext& g = *GImGui;
-
- const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight());
- const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f));
- float hs_w; // Half-size, longer axis
- float hs_h; // Half-size, smaller axis
- ImVec2 off; // Distance from edge or center
- if (outer_docking)
- {
- //hs_w = ImFloor(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f));
- //hs_h = ImFloor(hs_w * 0.15f);
- //off = ImVec2(ImFloor(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImFloor(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h));
- hs_w = ImFloor(hs_for_central_nodes * 1.50f);
- hs_h = ImFloor(hs_for_central_nodes * 0.80f);
- off = ImVec2(ImFloor(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 0.0f - hs_h), ImFloor(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 0.0f - hs_h));
- }
- else
- {
- hs_w = ImFloor(hs_for_central_nodes);
- hs_h = ImFloor(hs_for_central_nodes * 0.90f);
- off = ImVec2(ImFloor(hs_w * 2.40f), ImFloor(hs_w * 2.40f));
- }
-
- ImVec2 c = ImFloor(parent.GetCenter());
- if (dir == ImGuiDir_None) { out_r = ImRect(c.x - hs_w, c.y - hs_w, c.x + hs_w, c.y + hs_w); }
- else if (dir == ImGuiDir_Up) { out_r = ImRect(c.x - hs_w, c.y - off.y - hs_h, c.x + hs_w, c.y - off.y + hs_h); }
- else if (dir == ImGuiDir_Down) { out_r = ImRect(c.x - hs_w, c.y + off.y - hs_h, c.x + hs_w, c.y + off.y + hs_h); }
- else if (dir == ImGuiDir_Left) { out_r = ImRect(c.x - off.x - hs_h, c.y - hs_w, c.x - off.x + hs_h, c.y + hs_w); }
- else if (dir == ImGuiDir_Right) { out_r = ImRect(c.x + off.x - hs_h, c.y - hs_w, c.x + off.x + hs_h, c.y + hs_w); }
-
- if (test_mouse_pos == NULL)
- return false;
-
- ImRect hit_r = out_r;
- if (!outer_docking)
- {
- // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides
- hit_r.Expand(ImFloor(hs_w * 0.30f));
- ImVec2 mouse_delta = (*test_mouse_pos - c);
- float mouse_delta_len2 = ImLengthSqr(mouse_delta);
- float r_threshold_center = hs_w * 1.4f;
- float r_threshold_sides = hs_w * (1.4f + 1.2f);
- if (mouse_delta_len2 < r_threshold_center * r_threshold_center)
- return (dir == ImGuiDir_None);
- if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides)
- return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y));
- }
- return hit_r.Contains(*test_mouse_pos);
-}
-
-// host_node may be NULL if the window doesn't have a DockNode already.
-static void ImGui::DockNodePreviewDockCalc(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking)
-{
- ImGuiContext& g = *GImGui;
-
- // There is an edge case when docking into a dockspace which only has inactive nodes.
- // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive.
- // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference.
- ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node;
- if (ref_node_for_rect)
- IM_ASSERT(ref_node_for_rect->IsVisible);
-
- // Build a tentative future node (reuse same structure because it is practical)
- data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (root_payload->HasCloseButton);
- data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0);
- data->FutureNode.Pos = host_node ? ref_node_for_rect->Pos : host_window->Pos;
- data->FutureNode.Size = host_node ? ref_node_for_rect->Size : host_window->Size;
-
- // Figure out here we are allowed to dock
- ImGuiDockNodeFlags host_node_flags = host_node ? host_node->GetMergedFlags() : 0;
- const bool src_is_visibly_splitted = root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode() && (root_payload->DockNodeAsHost->OnlyNodeWithWindows == NULL);
- data->IsCenterAvailable = !is_outer_docking;
- if (src_is_visibly_splitted && (!host_node || !host_node->IsEmpty()))
- data->IsCenterAvailable = false;
- if (host_node && (host_node_flags & ImGuiDockNodeFlags_NoDocking))
- data->IsCenterAvailable = false;
- if (host_node && (host_node_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) && host_node->IsCentralNode())
- data->IsCenterAvailable = false;
-
- data->IsSidesAvailable = true;
- if ((host_node && (host_node_flags & ImGuiDockNodeFlags_NoSplit)) || g.IO.ConfigDockingNoSplit)
- data->IsSidesAvailable = false;
- if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode())
- data->IsSidesAvailable = false;
-
- // Calculate drop shapes geometry for allowed splitting directions
- IM_ASSERT(ImGuiDir_None == -1);
- data->SplitNode = host_node;
- data->SplitDir = ImGuiDir_None;
- data->IsSplitDirExplicit = false;
- if (!host_window->Collapsed)
- for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
- {
- if (dir == ImGuiDir_None && !data->IsCenterAvailable)
- continue;
- if (dir != ImGuiDir_None && !data->IsSidesAvailable)
- continue;
- if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking, &g.IO.MousePos))
- {
- data->SplitDir = (ImGuiDir)dir;
- data->IsSplitDirExplicit = true;
- }
- }
-
- // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar
- data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable);
- if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift)
- data->IsDropAllowed = false;
-
- // Calculate split area
- data->SplitRatio = 0.0f;
- if (data->SplitDir != ImGuiDir_None)
- {
- ImGuiDir split_dir = data->SplitDir;
- ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
- ImVec2 pos_new, pos_old = data->FutureNode.Pos;
- ImVec2 size_new, size_old = data->FutureNode.Size;
- DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, root_payload->Size);
-
- // Calculate split ratio so we can pass it down the docking request
- float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]);
- data->FutureNode.Pos = pos_new;
- data->FutureNode.Size = size_new;
- data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio);
- }
-}
-
-static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data)
-{
- ImGuiContext& g = *GImGui;
- IM_ASSERT(g.CurrentWindow == host_window); // Because we rely on font size to calculate tab sizes
-
- // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent.
- // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes.
- const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload;
-
- // In case the two windows involved are on different viewports, we will draw the overlay on each of them.
- int overlay_draw_lists_count = 0;
- ImDrawList* overlay_draw_lists[2];
- overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(host_window->Viewport);
- if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload)
- overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(root_payload->Viewport);
-
- // Draw main preview rectangle
- const ImU32 overlay_col_tabs = GetColorU32(ImGuiCol_TabActive);
- const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f);
- const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f);
- const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f);
- const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f);
-
- // Display area preview
- const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0);
- if (data->IsDropAllowed)
- {
- ImRect overlay_rect = data->FutureNode.Rect();
- if (data->SplitDir == ImGuiDir_None && can_preview_tabs)
- overlay_rect.Min.y += GetFrameHeight();
- if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable)
- for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
- overlay_draw_lists[overlay_n]->AddRectFilled(overlay_rect.Min, overlay_rect.Max, overlay_col_main, host_window->WindowRounding);
- }
-
- // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read)
- if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable)
- {
- // Compute target tab bar geometry so we can locate our preview tabs
- ImRect tab_bar_rect;
- DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL);
- ImVec2 tab_pos = tab_bar_rect.Min;
- if (host_node && host_node->TabBar)
- {
- if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar())
- tab_pos.x += host_node->TabBar->OffsetMax + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission.
- else
- tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]->Name, host_node->Windows[0]->HasCloseButton).x;
- }
- else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost))
- {
- tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_window->Name, host_window->HasCloseButton).x; // Account for slight offset which will be added when changing from title bar to tab bar
- }
-
- // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows)
- if (root_payload->DockNodeAsHost)
- IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size == root_payload->DockNodeAsHost->TabBar->Tabs.Size);
- const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar->Tabs.Size : 1;
- for (int payload_n = 0; payload_n < payload_count; payload_n++)
- {
- // Calculate the tab bounding box for each payload window
- ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar->Tabs[payload_n].Window : root_payload;
- if (!DockNodeIsDropAllowedOne(payload, host_window))
- continue;
-
- ImVec2 tab_size = TabItemCalcSize(payload->Name, payload->HasCloseButton);
- ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y);
- tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x;
- for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
- {
- ImGuiTabItemFlags tab_flags = ImGuiTabItemFlags_Preview | ((payload->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0);
- if (!tab_bar_rect.Contains(tab_bb))
- overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max);
- TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs);
- TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload->Name, 0, 0);
- if (!tab_bar_rect.Contains(tab_bb))
- overlay_draw_lists[overlay_n]->PopClipRect();
- }
- }
- }
-
- // Display drop boxes
- const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding);
- for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
- {
- if (!data->DropRectsDraw[dir + 1].IsInverted())
- {
- ImRect draw_r = data->DropRectsDraw[dir + 1];
- ImRect draw_r_in = draw_r;
- draw_r_in.Expand(-2.0f);
- ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop;
- for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
- {
- ImVec2 center = ImFloor(draw_r_in.GetCenter());
- overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding);
- overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding);
- if (dir == ImGuiDir_Left || dir == ImGuiDir_Right)
- overlay_draw_lists[overlay_n]->AddLine(ImVec2(center.x, draw_r_in.Min.y), ImVec2(center.x, draw_r_in.Max.y), overlay_col_lines);
- if (dir == ImGuiDir_Up || dir == ImGuiDir_Down)
- overlay_draw_lists[overlay_n]->AddLine(ImVec2(draw_r_in.Min.x, center.y), ImVec2(draw_r_in.Max.x, center.y), overlay_col_lines);
- }
- }
-
- // Stop after ImGuiDir_None
- if ((host_node && (host_node->GetMergedFlags() & ImGuiDockNodeFlags_NoSplit)) || g.IO.ConfigDockingNoSplit)
- return;
- }
-}
-
-//-----------------------------------------------------------------------------
-// Docking: ImGuiDockNode Tree manipulation functions
-//-----------------------------------------------------------------------------
-// - DockNodeTreeSplit()
-// - DockNodeTreeMerge()
-// - DockNodeTreeUpdatePosSize()
-// - DockNodeTreeUpdateSplitterFindTouchingNode()
-// - DockNodeTreeUpdateSplitter()
-// - DockNodeTreeFindFallbackLeafNode()
-// - DockNodeTreeFindNodeByPos()
-//-----------------------------------------------------------------------------
-
-void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node)
-{
- ImGuiContext& g = *GImGui;
- IM_ASSERT(split_axis != ImGuiAxis_None);
-
- ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0);
- child_0->ParentNode = parent_node;
-
- ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0);
- child_1->ParentNode = parent_node;
-
- ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1;
- DockNodeMoveChildNodes(child_inheritor, parent_node);
- parent_node->ChildNodes[0] = child_0;
- parent_node->ChildNodes[1] = child_1;
- parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow;
- parent_node->SplitAxis = split_axis;
- parent_node->VisibleWindow = NULL;
- parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode;
-
- float size_avail = (parent_node->Size[split_axis] - IMGUI_DOCK_SPLITTER_SIZE);
- size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f);
- IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting.
- child_0->SizeRef = child_1->SizeRef = parent_node->Size;
- child_0->SizeRef[split_axis] = ImFloor(size_avail * split_ratio);
- child_1->SizeRef[split_axis] = ImFloor(size_avail - child_0->SizeRef[split_axis]);
-
- DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node);
- DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size);
-
- // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property)
- child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
- child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
- child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
- parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_;
- if (child_inheritor->IsCentralNode())
- DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor;
-}
-
-void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child)
-{
- // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL.
- ImGuiDockNode* child_0 = parent_node->ChildNodes[0];
- ImGuiDockNode* child_1 = parent_node->ChildNodes[1];
- IM_ASSERT(child_0 || child_1);
- IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1);
- if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0))
- {
- IM_ASSERT(parent_node->TabBar == NULL);
- IM_ASSERT(parent_node->Windows.Size == 0);
- }
- IMGUI_DEBUG_LOG_DOCKING("DockNodeTreeMerge 0x%08X & 0x%08X back into parent 0x%08X\n", child_0 ? child_0->ID : 0, child_1 ? child_1->ID : 0, parent_node->ID);
-
- ImVec2 backup_last_explicit_size = parent_node->SizeRef;
- DockNodeMoveChildNodes(parent_node, merge_lead_child);
- if (child_0)
- {
- DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows
- DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID);
- }
- if (child_1)
- {
- DockNodeMoveWindows(parent_node, child_1);
- DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID);
- }
- DockNodeApplyPosSizeToWindows(parent_node);
- parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto;
- parent_node->VisibleWindow = merge_lead_child->VisibleWindow;
- parent_node->SizeRef = backup_last_explicit_size;
-
- // Flags transfer
- parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag
- parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
- parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
-
- if (child_0)
- {
- ctx->DockContext->Nodes.SetVoidPtr(child_0->ID, NULL);
- IM_DELETE(child_0);
- }
- if (child_1)
- {
- ctx->DockContext->Nodes.SetVoidPtr(child_1->ID, NULL);
- IM_DELETE(child_1);
- }
-}
-
-// Update Pos/Size for a node hierarchy (don't affect child Windows yet)
-void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, bool only_write_to_marked_nodes)
-{
- // During the regular dock node update we write to all nodes.
- // 'only_write_to_marked_nodes' is only set when turning a node visible mid-frame and we need its size right-away.
- IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
- const bool write_to_node = (only_write_to_marked_nodes == false) || (node->MarkedForPosSizeWrite);
- if (write_to_node)
- {
- node->Pos = pos;
- node->Size = size;
- }
-
- if (node->IsLeafNode())
- return;
-
- ImGuiDockNode* child_0 = node->ChildNodes[0];
- ImGuiDockNode* child_1 = node->ChildNodes[1];
- ImVec2 child_0_pos = pos, child_1_pos = pos;
- ImVec2 child_0_size = size, child_1_size = size;
- if (child_0->IsVisible && child_1->IsVisible)
- {
- const float spacing = IMGUI_DOCK_SPLITTER_SIZE;
- const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
- const float size_avail = ImMax(size[axis] - spacing, 0.0f);
-
- // Size allocation policy
- // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows.
- ImGuiContext& g = *GImGui;
- const float size_min_each = ImFloor(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f);
-
- // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge)
- IM_ASSERT(!(child_0->WantLockSizeOnce && child_1->WantLockSizeOnce));
- if (child_0->WantLockSizeOnce)
- {
- child_0->WantLockSizeOnce = false;
- child_0_size[axis] = child_0->SizeRef[axis] = child_0->Size[axis];
- child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
- IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
-
- }
- else if (child_1->WantLockSizeOnce)
- {
- child_1->WantLockSizeOnce = false;
- child_1_size[axis] = child_1->SizeRef[axis] = child_1->Size[axis];
- child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]);
- IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
- }
-
- // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node
- else if (child_1->IsCentralNode() && child_0->SizeRef[axis] != 0.0f)
- {
- child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]);
- child_1_size[axis] = (size_avail - child_0_size[axis]);
- }
- else if (child_0->IsCentralNode() && child_1->SizeRef[axis] != 0.0f)
- {
- child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]);
- child_0_size[axis] = (size_avail - child_1_size[axis]);
- }
- else
- {
- // 4) Otherwise distribute according to the relative ratio of each SizeRef value
- float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]);
- child_0_size[axis] = ImMax(size_min_each, ImFloor(size_avail * split_ratio + 0.5F));
- child_1_size[axis] = (size_avail - child_0_size[axis]);
- }
- child_1_pos[axis] += spacing + child_0_size[axis];
- }
- if (child_0->IsVisible)
- DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size);
- if (child_1->IsVisible)
- DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size);
-}
-
-static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector* touching_nodes)
-{
- if (node->IsLeafNode())
- {
- touching_nodes->push_back(node);
- return;
- }
- if (node->ChildNodes[0]->IsVisible)
- if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible)
- DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes);
- if (node->ChildNodes[1]->IsVisible)
- if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible)
- DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes);
-}
-
-void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node)
-{
- if (node->IsLeafNode())
- return;
-
- ImGuiContext& g = *GImGui;
-
- ImGuiDockNode* child_0 = node->ChildNodes[0];
- ImGuiDockNode* child_1 = node->ChildNodes[1];
- if (child_0->IsVisible && child_1->IsVisible)
- {
- // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally)
- const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
- IM_ASSERT(axis != ImGuiAxis_None);
- ImRect bb;
- bb.Min = child_0->Pos;
- bb.Max = child_1->Pos;
- bb.Min[axis] += child_0->Size[axis];
- bb.Max[axis ^ 1] += child_1->Size[axis ^ 1];
- //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255));
-
- if ((child_0->GetMergedFlags() | child_1->GetMergedFlags()) & ImGuiDockNodeFlags_NoResize)
- {
- ImGuiWindow* window = g.CurrentWindow;
- window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding);
- }
- else
- {
- //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node.
- //bb.Max[axis] -= 1;
- PushID(node->ID);
-
- // Gather list of nodes that are touching the splitter line. Find resizing limits based on those nodes.
- ImVector touching_nodes[2];
- float min_size = g.Style.WindowMinSize[axis];
- float resize_limits[2];
- resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size;
- resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size;
-
- ImGuiID splitter_id = GetID("##Splitter");
- if (g.ActiveId == splitter_id)
- {
- // Only process when splitter is active
- DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]);
- DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]);
- for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++)
- resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size);
- for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++)
- resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size);
-
- /*
- // [DEBUG] Render limits
- ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList((ImGuiViewportP*)GetMainViewport());
- for (int n = 0; n < 2; n++)
- if (axis == ImGuiAxis_X)
- draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f);
- else
- draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f);
- */
- }
-
- // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters
- float cur_size_0 = child_0->Size[axis];
- float cur_size_1 = child_1->Size[axis];
- float min_size_0 = resize_limits[0] - child_0->Pos[axis];
- float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1];
- if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER))
- {
- if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0)
- {
- child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0;
- child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis];
- child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1;
-
- // Lock the size of every node that is a sibling of the node we are touching
- // This might be less desirable if we can merge sibling of a same axis into the same parental level.
- for (int side_n = 0; side_n < 2; side_n++)
- for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++)
- {
- ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n];
- //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList((ImGuiViewportP*)GetMainViewport());
- //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255));
- while (touching_node->ParentNode != node)
- {
- if (touching_node->ParentNode->SplitAxis == axis)
- {
- // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize().
- ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n];
- node_to_preserve->WantLockSizeOnce = true;
- //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255));
- //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100));
- }
- touching_node = touching_node->ParentNode;
- }
- }
-
- DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size);
- DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size);
- MarkIniSettingsDirty();
- }
- }
- PopID();
- }
- }
-
- if (child_0->IsVisible)
- DockNodeTreeUpdateSplitter(child_0);
- if (child_1->IsVisible)
- DockNodeTreeUpdateSplitter(child_1);
-}
-
-ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node)
-{
- if (node->IsLeafNode())
- return node;
- if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0]))
- return leaf_node;
- if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1]))
- return leaf_node;
- return NULL;
-}
-
-ImGuiDockNode* ImGui::DockNodeTreeFindNodeByPos(ImGuiDockNode* node, ImVec2 pos)
-{
- if (!node->IsVisible)
- return NULL;
-
- ImGuiContext& g = *GImGui;
- const float dock_spacing = g.Style.ItemInnerSpacing.x;
- ImRect r(node->Pos, node->Pos + node->Size);
- r.Expand(dock_spacing * 0.5f);
- bool inside = r.Contains(pos);
- if (!inside)
- return NULL;
-
- if (node->IsLeafNode())
- return node;
- if (ImGuiDockNode* hovered_node = DockNodeTreeFindNodeByPos(node->ChildNodes[0], pos))
- return hovered_node;
- if (ImGuiDockNode* hovered_node = DockNodeTreeFindNodeByPos(node->ChildNodes[1], pos))
- return hovered_node;
-
- // There is an edge case when docking into a dockspace which only has inactive nodes (because none of the windows are active)
- // In this case we need to fallback into any leaf mode, possibly the central node.
- if (node->IsDockSpace() && node->IsRootNode())
- {
- if (node->CentralNode && node->IsLeafNode()) // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first.
- return node->CentralNode;
- return DockNodeTreeFindFallbackLeafNode(node);
- }
-
- return NULL;
-}
-
-//-----------------------------------------------------------------------------
-// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
-//-----------------------------------------------------------------------------
-// - SetWindowDock() [Internal]
-// - DockSpace()
-// - DockSpaceOverViewport()
-//-----------------------------------------------------------------------------
-
-// [Internal] Called via SetNextWindowDockID()
-void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond)
-{
- // Test condition (NB: bit 0 is always true) and clear flags for next time
- if (cond && (window->SetWindowDockAllowFlags & cond) == 0)
- return;
- window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
-
- if (window->DockId == dock_id)
- return;
-
- // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot
- ImGuiContext* ctx = GImGui;
- if (ImGuiDockNode* new_node = DockContextFindNodeByID(ctx, dock_id))
- if (new_node->IsSplitNode())
- {
- // Policy: Find central node or latest focused node. We first move back to our root node.
- new_node = DockNodeGetRootNode(new_node);
- if (new_node->CentralNode)
- {
- IM_ASSERT(new_node->CentralNode->IsCentralNode());
- dock_id = new_node->CentralNode->ID;
- }
- else
- {
- dock_id = new_node->LastFocusedNodeID;
- }
- }
-
- if (window->DockId == dock_id)
- return;
-
- if (window->DockNode)
- DockNodeRemoveWindow(window->DockNode, window, 0);
- window->DockId = dock_id;
-}
-
-// Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default.
-// The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors.
-void ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class)
-{
- ImGuiContext* ctx = GImGui;
- ImGuiContext& g = *ctx;
- ImGuiWindow* window = GetCurrentWindow();
- if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
- return;
-
- IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0);
- ImGuiDockNode* node = DockContextFindNodeByID(ctx, id);
- if (!node)
- {
- IMGUI_DEBUG_LOG_DOCKING("DockSpace: dockspace node 0x%08X created\n", id);
- node = DockContextAddNode(ctx, id);
- node->LocalFlags |= ImGuiDockNodeFlags_CentralNode;
- }
- if (window_class && window_class->ClassId != node->WindowClass.ClassId)
- IMGUI_DEBUG_LOG_DOCKING("DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", id, node->WindowClass.ClassId, window_class->ClassId);
- node->SharedFlags = flags;
- node->WindowClass = window_class ? *window_class : ImGuiWindowClass();
-
- // When a DockSpace transitioned form implicit to explicit this may be called a second time
- // It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again.
- if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly))
- {
- IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID");
- node->LocalFlags |= ImGuiDockNodeFlags_DockSpace;
- return;
- }
- node->LocalFlags |= ImGuiDockNodeFlags_DockSpace;
-
- // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible
- if (flags & ImGuiDockNodeFlags_KeepAliveOnly)
- {
- node->LastFrameAlive = g.FrameCount;
- return;
- }
-
- const ImVec2 content_avail = GetContentRegionAvail();
- ImVec2 size = ImFloor(size_arg);
- if (size.x <= 0.0f)
- size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
- if (size.y <= 0.0f)
- size.y = ImMax(content_avail.y + size.y, 4.0f);
- IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
-
- node->Pos = window->DC.CursorPos;
- node->Size = node->SizeRef = size;
- SetNextWindowPos(node->Pos);
- SetNextWindowSize(node->Size);
- g.NextWindowData.PosUndock = false;
-
- // FIXME-DOCKING: Why do we need a child window to host a dockspace, could we host it in the existing window?
- ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost;
- window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar;
- window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
-
- char title[256];
- ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, id);
-
- if (node->Windows.Size > 0 || node->IsSplitNode())
- PushStyleColor(ImGuiCol_ChildBg, IM_COL32(0, 0, 0, 0));
- PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f);
- Begin(title, NULL, window_flags);
- PopStyleVar();
- if (node->Windows.Size > 0 || node->IsSplitNode())
- PopStyleColor();
-
- ImGuiWindow* host_window = g.CurrentWindow;
- host_window->DockNodeAsHost = node;
- host_window->ChildId = window->GetID(title);
- node->HostWindow = host_window;
- node->OnlyNodeWithWindows = NULL;
-
- IM_ASSERT(node->IsRootNode());
- DockNodeUpdate(node);
-
- End();
-}
-
-// Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode!
-// The limitation with this call is that your window won't have a menu bar.
-// Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function.
-// So if you want a menu bar you need to repeat this code manually ourselves. As with advanced other Docking API, we may change this function signature.
-ImGuiID ImGui::DockSpaceOverViewport(ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class)
-{
- if (viewport == NULL)
- viewport = GetMainViewport();
-
- SetNextWindowPos(viewport->Pos);
- SetNextWindowSize(viewport->Size);
- SetNextWindowViewport(viewport->ID);
-
- ImGuiWindowFlags host_window_flags = 0;
- host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
- host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
- if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
- host_window_flags |= ImGuiWindowFlags_NoBackground;
-
- char label[32];
- ImFormatString(label, IM_ARRAYSIZE(label), "DockSpaceViewport_%08X", viewport->ID);
-
- PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
- PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
- PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
- Begin(label, NULL, host_window_flags);
- PopStyleVar(3);
-
- ImGuiID dockspace_id = GetID("DockSpace");
- DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class);
- End();
-
- return dockspace_id;
-}
-
-//-----------------------------------------------------------------------------
-// Docking: Builder Functions
-//-----------------------------------------------------------------------------
-// Very early end-user API to manipulate dock nodes.
-// Only available in imgui_internal.h. Expect this API to change/break!
-// It is expected that those functions are all called _before_ the dockspace node submission.
-//-----------------------------------------------------------------------------
-// - DockBuilderDockWindow()
-// - DockBuilderGetNode()
-// - DockBuilderSetNodePos()
-// - DockBuilderSetNodeSize()
-// - DockBuilderAddNode()
-// - DockBuilderRemoveNode()
-// - DockBuilderRemoveNodeChildNodes()
-// - DockBuilderRemoveNodeDockedWindows()
-// - DockBuilderSplitNode()
-// - DockBuilderCopyNodeRec()
-// - DockBuilderCopyNode()
-// - DockBuilderCopyWindowSettings()
-// - DockBuilderCopyDockSpace()
-// - DockBuilderFinish()
-//-----------------------------------------------------------------------------
-
-void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id)
-{
- // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1)
- ImGuiID window_id = ImHashStr(window_name);
- if (ImGuiWindow* window = FindWindowByID(window_id))
- {
- // Apply to created window
- SetWindowDock(window, node_id, ImGuiCond_Always);
- window->DockOrder = -1;
- }
- else
- {
- // Apply to settings
- ImGuiWindowSettings* settings = FindWindowSettings(window_id);
- if (settings == NULL)
- settings = CreateNewWindowSettings(window_name);
- settings->DockId = node_id;
- settings->DockOrder = -1;
- }
-}
-
-ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id)
-{
- ImGuiContext* ctx = GImGui;
- return DockContextFindNodeByID(ctx, node_id);
-}
-
-void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos)
-{
- ImGuiContext* ctx = GImGui;
- ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
- if (node == NULL)
- return;
- node->Pos = pos;
- node->AuthorityForPos = ImGuiDataAuthority_DockNode;
-}
-
-void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size)
-{
- ImGuiContext* ctx = GImGui;
- ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
- if (node == NULL)
- return;
- IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
- node->Size = node->SizeRef = size;
- node->AuthorityForSize = ImGuiDataAuthority_DockNode;
-}
-
-// Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node!
-// - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node.
-// - Dockspace node: calling DockBuilderSetNodePos() is unnecessary.
-// - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand!
-// For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect.
-// - Use (id == 0) to let the system allocate a node identifier.
-ImGuiID ImGui::DockBuilderAddNode(ImGuiID id, ImGuiDockNodeFlags flags)
-{
- ImGuiContext* ctx = GImGui;
- ImGuiDockNode* node = NULL;
- if (flags & ImGuiDockNodeFlags_DockSpace)
- {
- DockSpace(id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly);
- node = DockContextFindNodeByID(ctx, id);
- }
- else
- {
- if (id != 0)
- node = DockContextFindNodeByID(ctx, id);
- if (!node)
- node = DockContextAddNode(ctx, id);
- node->LocalFlags = flags;
- }
- node->LastFrameAlive = ctx->FrameCount; // Set this otherwise BeginDocked will undock during the same frame.
- return node->ID;
-}
-
-void ImGui::DockBuilderRemoveNode(ImGuiID node_id)
-{
- ImGuiContext* ctx = GImGui;
- ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
- if (node == NULL)
- return;
- DockBuilderRemoveNodeDockedWindows(node_id, true);
- DockBuilderRemoveNodeChildNodes(node_id);
- if (node->IsCentralNode() && node->ParentNode)
- node->ParentNode->LocalFlags |= ImGuiDockNodeFlags_CentralNode;
- DockContextRemoveNode(ctx, node, true);
-}
-
-void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id)
-{
- ImGuiContext* ctx = GImGui;
- ImGuiDockContext* dc = ctx->DockContext;
-
- ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(ctx, root_id) : NULL;
- if (root_id && root_node == NULL)
- return;
- bool has_central_node = false;
-
- ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto;
- ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto;
-
- // Process active windows
- ImVector nodes_to_remove;
- for (int n = 0; n < dc->Nodes.Data.Size; n++)
- if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
- {
- bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id);
- if (want_removal)
- {
- if (node->IsCentralNode())
- has_central_node = true;
- if (root_id != 0)
- DockContextQueueNotifyRemovedNode(ctx, node);
- if (root_node)
- DockNodeMoveWindows(root_node, node);
- nodes_to_remove.push_back(node);
- }
- }
-
- // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge)
- // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead)
- if (root_node)
- {
- root_node->AuthorityForPos = backup_root_node_authority_for_pos;
- root_node->AuthorityForSize = backup_root_node_authority_for_size;
- }
-
- // Apply to settings
- for (int settings_n = 0; settings_n < ctx->SettingsWindows.Size; settings_n++)
- if (ImGuiID window_settings_dock_id = ctx->SettingsWindows[settings_n].DockId)
- for (int n = 0; n < nodes_to_remove.Size; n++)
- if (nodes_to_remove[n]->ID == window_settings_dock_id)
- {
- ctx->SettingsWindows[settings_n].DockId = root_id;
- break;
- }
-
- // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes
- if (nodes_to_remove.Size > 1)
- ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode*), DockNodeComparerDepthMostFirst);
- for (int n = 0; n < nodes_to_remove.Size; n++)
- DockContextRemoveNode(ctx, nodes_to_remove[n], false);
-
- if (root_id == 0)
- {
- dc->Nodes.Clear();
- dc->Requests.clear();
- }
- else if (has_central_node)
- {
- root_node->LocalFlags |= ImGuiDockNodeFlags_CentralNode;
- root_node->CentralNode = root_node;
- }
-}
-
-void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_persistent_docking_references)
-{
- // Clear references in settings
- ImGuiContext* ctx = GImGui;
- ImGuiContext& g = *ctx;
- if (clear_persistent_docking_references)
- {
- for (int n = 0; n < g.SettingsWindows.Size; n++)
- {
- ImGuiWindowSettings* settings = &g.SettingsWindows[n];
- bool want_removal = (root_id == 0) || (settings->DockId == root_id);
- if (!want_removal && settings->DockId != 0)
- if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, settings->DockId))
- if (DockNodeGetRootNode(node)->ID == root_id)
- want_removal = true;
- if (want_removal)
- settings->DockId = 0;
- }
- }
-
- // Clear references in windows
- for (int n = 0; n < g.Windows.Size; n++)
- {
- ImGuiWindow* window = g.Windows[n];
- bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id);
- if (want_removal)
- {
- const ImGuiID backup_dock_id = window->DockId;
- DockContextProcessUndockWindow(ctx, window, clear_persistent_docking_references);
- if (!clear_persistent_docking_references)
- IM_ASSERT(window->DockId == backup_dock_id);
- }
- }
-}
-
-// If 'out_id_at_dir' or 'out_id_at_opposite_dir' are non NULL, the function will write out the ID of the two new nodes created.
-// Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set.
-// FIXME-DOCK: We are not exposing nor using split_outer.
-ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir)
-{
- ImGuiContext* ctx = GImGui;
- IM_ASSERT(split_dir != ImGuiDir_None);
- IMGUI_DEBUG_LOG_DOCKING("DockBuilderSplitNode node 0x%08X, split_dir %d\n", id, split_dir);
-
- ImGuiDockNode* node = DockContextFindNodeByID(ctx, id);
- if (node == NULL)
- {
- IM_ASSERT(node != NULL);
- return 0;
- }
-
- IM_ASSERT(!node->IsSplitNode()); // Assert if already Split
-
- ImGuiDockRequest req;
- req.Type = ImGuiDockRequestType_Split;
- req.DockTargetWindow = NULL;
- req.DockTargetNode = node;
- req.DockPayload = NULL;
- req.DockSplitDir = split_dir;
- req.DockSplitRatio = ImSaturate((split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir);
- req.DockSplitOuter = false;
- DockContextProcessDock(ctx, &req);
-
- ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID;
- ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID;
- if (out_id_at_dir)
- *out_id_at_dir = id_at_dir;
- if (out_id_at_opposite_dir)
- *out_id_at_opposite_dir = id_at_opposite_dir;
- return id_at_dir;
-}
-
-static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector* out_node_remap_pairs)
-{
- ImGuiContext* ctx = GImGui;
- ImGuiDockNode* dst_node = ImGui::DockContextAddNode(ctx, dst_node_id_if_known);
- dst_node->SharedFlags = src_node->SharedFlags;
- dst_node->LocalFlags = src_node->LocalFlags;
- dst_node->Pos = src_node->Pos;
- dst_node->Size = src_node->Size;
- dst_node->SizeRef = src_node->SizeRef;
- dst_node->SplitAxis = src_node->SplitAxis;
-
- out_node_remap_pairs->push_back(src_node->ID);
- out_node_remap_pairs->push_back(dst_node->ID);
-
- for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++)
- if (src_node->ChildNodes[child_n])
- {
- dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs);
- dst_node->ChildNodes[child_n]->ParentNode = dst_node;
- }
-
- IMGUI_DEBUG_LOG_DOCKING("Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0);
- return dst_node;
-}
-
-void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector* out_node_remap_pairs)
-{
- ImGuiContext* ctx = GImGui;
- IM_ASSERT(src_node_id != 0);
- IM_ASSERT(dst_node_id != 0);
- IM_ASSERT(out_node_remap_pairs != NULL);
-
- ImGuiDockNode* src_node = DockContextFindNodeByID(ctx, src_node_id);
- IM_ASSERT(src_node != NULL);
-
- out_node_remap_pairs->clear();
- DockBuilderRemoveNode(dst_node_id);
- DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs);
-
- IM_ASSERT((out_node_remap_pairs->Size % 2) == 0);
-}
-
-void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name)
-{
- ImGuiWindow* src_window = FindWindowByName(src_name);
- if (src_window == NULL)
- return;
- if (ImGuiWindow* dst_window = FindWindowByName(dst_name))
- {
- dst_window->Pos = src_window->Pos;
- dst_window->Size = src_window->Size;
- dst_window->SizeFull = src_window->SizeFull;
- dst_window->Collapsed = src_window->Collapsed;
- }
- else if (ImGuiWindowSettings* dst_settings = FindOrCreateWindowSettings(dst_name))
- {
- ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos);
- if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID)
- {
- dst_settings->ViewportPos = window_pos_2ih;
- dst_settings->ViewportId = src_window->ViewportId;
- dst_settings->Pos = ImVec2ih(0, 0);
- }
- else
- {
- dst_settings->Pos = window_pos_2ih;
- }
- dst_settings->Size = ImVec2ih(src_window->SizeFull);
- dst_settings->Collapsed = src_window->Collapsed;
- }
-}
-
-// FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed.
-void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector* in_window_remap_pairs)
-{
- IM_ASSERT(src_dockspace_id != 0);
- IM_ASSERT(dst_dockspace_id != 0);
- IM_ASSERT(in_window_remap_pairs != NULL);
- IM_ASSERT((in_window_remap_pairs->Size % 2) == 0);
-
- // Duplicate entire dock
- // FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart,
- // whereas we could attempt to at least keep them together in a new, same floating node.
- ImVector node_remap_pairs;
- DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs);
-
- // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes
- // (The windows associated to src_dockspace_id are staying in place)
- ImVector src_windows;
- for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2)
- {
- const char* src_window_name = (*in_window_remap_pairs)[remap_window_n];
- const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1];
- ImGuiID src_window_id = ImHashStr(src_window_name);
- src_windows.push_back(src_window_id);
-
- // Search in the remapping tables
- ImGuiID src_dock_id = 0;
- if (ImGuiWindow* src_window = FindWindowByID(src_window_id))
- src_dock_id = src_window->DockId;
- else if (ImGuiWindowSettings* src_window_settings = FindWindowSettings(src_window_id))
- src_dock_id = src_window_settings->DockId;
- ImGuiID dst_dock_id = 0;
- for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
- if (node_remap_pairs[dock_remap_n] == src_dock_id)
- {
- dst_dock_id = node_remap_pairs[dock_remap_n + 1];
- //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear
- break;
- }
-
- if (dst_dock_id != 0)
- {
- // Docked windows gets redocked into the new node hierarchy.
- IMGUI_DEBUG_LOG_DOCKING("Remap live window '%s' 0x%08X -> '%s' 0x%08X\n", src_window_name, src_dock_id, dst_window_name, dst_dock_id);
- DockBuilderDockWindow(dst_window_name, dst_dock_id);
- }
- else
- {
- // Floating windows gets their settings transferred (regardless of whether the new window already exist or not)
- // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together?
- IMGUI_DEBUG_LOG_DOCKING("Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name);
- DockBuilderCopyWindowSettings(src_window_name, dst_window_name);
- }
- }
-
- // Anything else in the source nodes of 'node_remap_pairs' are windows that were docked in src_dockspace_id but are not owned by it (unaffiliated windows, e.g. "ImGui Demo")
- // Find those windows and move to them to the cloned dock node. This may be optional?
- for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
- if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n])
- {
- ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1];
- ImGuiDockNode* node = DockBuilderGetNode(src_dock_id);
- for (int window_n = 0; window_n < node->Windows.Size; window_n++)
- {
- ImGuiWindow* window = node->Windows[window_n];
- if (src_windows.contains(window->ID))
- continue;
-
- // Docked windows gets redocked into the new node hierarchy.
- IMGUI_DEBUG_LOG_DOCKING("Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id);
- DockBuilderDockWindow(window->Name, dst_dock_id);
- }
- }
-}
-
-void ImGui::DockBuilderFinish(ImGuiID root_id)
-{
- ImGuiContext* ctx = GImGui;
- //DockContextRebuild(ctx);
- DockContextBuildAddWindowsToNodes(ctx, root_id);
-}
-
-//-----------------------------------------------------------------------------
-// Docking: Begin/End Support Functions (called from Begin/End)
-//-----------------------------------------------------------------------------
-// - GetWindowAlwaysWantOwnTabBar()
-// - BeginDocked()
-// - BeginAsDockableDragDropSource()
-// - BeginAsDockableDragDropTarget()
-//-----------------------------------------------------------------------------
-
-bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window)
-{
- ImGuiContext& g = *GImGui;
- if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar)
- if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0)
- if (!window->IsFallbackWindow) // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise
- return true;
- return false;
-}
-
-static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window)
-{
- ImGuiContext& g = *ctx;
- ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
- IM_ASSERT(window->DockNode == NULL);
-
- // We should not be docking into a split node (SetWindowDock should avoid this)
- if (node && node->IsSplitNode())
- {
- DockContextProcessUndockWindow(ctx, window);
- return NULL;
- }
-
- // Create node
- if (node == NULL)
- {
- node = DockContextAddNode(ctx, window->DockId);
- node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
- node->LastFrameAlive = g.FrameCount;
- }
-
- // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet,
- // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node).
- // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout.
- // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame.
- if (!node->IsVisible)
- {
- ImGuiDockNode* ancestor_node = node;
- while (!ancestor_node->IsVisible)
- {
- ancestor_node->IsVisible = true;
- ancestor_node->MarkedForPosSizeWrite = true;
- if (ancestor_node->ParentNode)
- ancestor_node = ancestor_node->ParentNode;
- }
- IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f);
- DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, true);
- }
-
- // Add window to node
- DockNodeAddWindow(node, window, true);
- IM_ASSERT(node == window->DockNode);
- return node;
-}
-
-void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open)
-{
- ImGuiContext* ctx = GImGui;
- ImGuiContext& g = *ctx;
-
- const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window);
- if (auto_dock_node)
- {
- if (window->DockId == 0)
- {
- IM_ASSERT(window->DockNode == NULL);
- window->DockId = DockContextGenNodeID(ctx);
- }
- }
- else
- {
- // Calling SetNextWindowPos() undock windows by default (by setting PosUndock)
- bool want_undock = false;
- want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0;
- want_undock |= (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock;
- if (want_undock)
- {
- DockContextProcessUndockWindow(ctx, window);
- return;
- }
- }
-
- // Bind to our dock node
- ImGuiDockNode* node = window->DockNode;
- if (node != NULL)
- IM_ASSERT(window->DockId == node->ID);
- if (window->DockId != 0 && node == NULL)
- {
- node = DockContextBindNodeToWindow(ctx, window);
- if (node == NULL)
- return;
- }
-
-#if 0
- // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set
- if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode))
- {
- DockContextProcessUndockWindow(ctx, window);
- return;
- }
-#endif
-
- // Undock if our dockspace node disappeared
- // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly.
- if (node->LastFrameAlive < g.FrameCount)
- {
- // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextUpdateDocking()
- ImGuiDockNode* root_node = DockNodeGetRootNode(node);
- if (root_node->LastFrameAlive < g.FrameCount)
- {
- DockContextProcessUndockWindow(ctx, window);
- }
- else
- {
- window->DockIsActive = true;
- window->DockTabIsVisible = false;
- }
- return;
- }
-
- // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window,
- // and never create neither a host window neither a tab bar.
- // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test)
- if (node->HostWindow == NULL)
- {
- window->DockIsActive = (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing);
- window->DockTabIsVisible = false;
- return;
- }
-
- IM_ASSERT(node->HostWindow);
- IM_ASSERT(node->IsLeafNode());
- IM_ASSERT(node->Size.x > 0.0f && node->Size.y > 0.0f);
- node->State = ImGuiDockNodeState_HostWindowVisible;
-
- // Undock if we are submitted earlier than the host window
- if (window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext)
- {
- DockContextProcessUndockWindow(ctx, window);
- return;
- }
-
- // Position window
- SetNextWindowPos(node->Pos);
- SetNextWindowSize(node->Size);
- g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos()
- window->DockIsActive = true;
- window->DockTabIsVisible = false;
- if (node->SharedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
- return;
-
- // When the window is selected we mark it as visible.
- if (node->VisibleWindow == window)
- window->DockTabIsVisible = true;
-
- // Update window flag
- IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0);
- window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_NoResize;
- if (node->IsHiddenTabBar() || node->IsNoTabBar())
- window->Flags |= ImGuiWindowFlags_NoTitleBar;
- else
- window->Flags &= ~ImGuiWindowFlags_NoTitleBar; // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed!
-
- // Save new dock order only if the tab bar has been visible once.
- // This allows multiple windows to be created in the same frame and have their respective dock orders preserved.
- if (node->TabBar && node->TabBar->CurrFrameVisible != -1)
- window->DockOrder = (short)DockNodeGetTabOrder(window);
-
- if ((node->WantCloseAll || node->WantCloseTabID == window->ID) && p_open != NULL)
- *p_open = false;
-
- // Update ChildId to allow returning from Child to Parent with Escape
- ImGuiWindow* parent_window = window->DockNode->HostWindow;
- window->ChildId = parent_window->GetID(window->Name);
-}
-
-void ImGui::BeginAsDockableDragDropSource(ImGuiWindow* window)
-{
- ImGuiContext& g = *GImGui;
- IM_ASSERT(g.ActiveId == window->MoveId);
-
- window->DC.LastItemId = window->MoveId;
- window = window->RootWindow;
- IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
- bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(g.ActiveIdClickOffset);
- if (is_drag_docking && BeginDragDropSource(ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_SourceAutoExpirePayload))
- {
- SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window));
- EndDragDropSource();
- }
-}
-
-void ImGui::BeginAsDockableDragDropTarget(ImGuiWindow* window)
-{
- ImGuiContext* ctx = GImGui;
- ImGuiContext& g = *ctx;
-
- //IM_ASSERT(window->RootWindow == window); // May also be a DockSpace
- IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
- if (!g.DragDropActive)
- return;
- if (!BeginDragDropTargetCustom(window->Rect(), window->ID))
- return;
-
- // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering
- // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly)
- const ImGuiPayload* payload = &g.DragDropPayload;
- if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow**)payload->Data))
- {
- EndDragDropTarget();
- return;
- }
-
- ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data;
- if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
- {
- // Select target node
- ImGuiDockNode* node = NULL;
- bool allow_null_target_node = false;
- if (window->DockNodeAsHost)
- node = DockNodeTreeFindNodeByPos(window->DockNodeAsHost, g.IO.MousePos);
- else if (window->DockNode) // && window->DockIsActive)
- node = window->DockNode;
- else
- allow_null_target_node = true; // Dock into a regular window
-
- const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight()));
- const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max);
-
- // Preview docking request and find out split direction/ratio
- //const bool do_preview = true; // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window.
- const bool do_preview = payload->IsPreview() || payload->IsDelivery();
- if (do_preview && (node != NULL || allow_null_target_node))
- {
- ImGuiDockPreviewData split_inner, split_outer;
- ImGuiDockPreviewData* split_data = &split_inner;
- if (node && (node->ParentNode || node->IsCentralNode()))
- if (ImGuiDockNode* root_node = DockNodeGetRootNode(node))
- {
- DockNodePreviewDockCalc(window, root_node, payload_window, &split_outer, is_explicit_target, true);
- if (split_outer.IsSplitDirExplicit)
- split_data = &split_outer;
- }
- DockNodePreviewDockCalc(window, node, payload_window, &split_inner, is_explicit_target, false);
- if (split_data == &split_outer)
- split_inner.IsDropAllowed = false;
-
- // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes
- DockNodePreviewDockRender(window, node, payload_window, &split_inner);
- DockNodePreviewDockRender(window, node, payload_window, &split_outer);
-
- // Queue docking request
- if (split_data->IsDropAllowed && payload->IsDelivery())
- DockContextQueueDock(ctx, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer);
- }
- }
- EndDragDropTarget();
-}
-
-//-----------------------------------------------------------------------------
-// Docking: Settings
-//-----------------------------------------------------------------------------
-// - DockSettingsRenameNodeReferences()
-// - DockSettingsRemoveNodeReferences()
-// - DockSettingsFindNodeSettings()
-// - DockSettingsHandler_ReadOpen()
-// - DockSettingsHandler_ReadLine()
-// - DockSettingsHandler_DockNodeToSettings()
-// - DockSettingsHandler_WriteAll()
-//-----------------------------------------------------------------------------
-
-static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id)
-{
- ImGuiContext& g = *GImGui;
- IMGUI_DEBUG_LOG_DOCKING("DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id);
- for (int window_n = 0; window_n < g.Windows.Size; window_n++)
- {
- ImGuiWindow* window = g.Windows[window_n];
- if (window->DockId == old_node_id && window->DockNode == NULL)
- window->DockId = new_node_id;
- }
- for (int settings_n = 0; settings_n < g.SettingsWindows.Size; settings_n++) // FIXME-OPT: We could remove this loop by storing the index in the map
- {
- ImGuiWindowSettings* window_settings = &g.SettingsWindows[settings_n];
- if (window_settings->DockId == old_node_id)
- window_settings->DockId = new_node_id;
- }
-}
-
-// Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings
-static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count)
-{
- ImGuiContext& g = *GImGui;
- int found = 0;
- for (int settings_n = 0; settings_n < g.SettingsWindows.Size; settings_n++) // FIXME-OPT: We could remove this loop by storing the index in the map
- {
- ImGuiWindowSettings* window_settings = &g.SettingsWindows[settings_n];
- for (int node_n = 0; node_n < node_ids_count; node_n++)
- if (window_settings->DockId == node_ids[node_n])
- {
- window_settings->DockId = 0;
- window_settings->DockOrder = -1;
- if (++found < node_ids_count)
- break;
- return;
- }
- }
-}
-
-static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id)
-{
- // FIXME-OPT
- ImGuiDockContext* dc = ctx->DockContext;
- for (int n = 0; n < dc->SettingsNodes.Size; n++)
- if (dc->SettingsNodes[n].ID == id)
- return &dc->SettingsNodes[n];
- return NULL;
-}
-
-static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
-{
- if (strcmp(name, "Data") != 0)
- return NULL;
- return (void*)1;
-}
-
-static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line)
-{
- char c = 0;
- int x = 0, y = 0;
- int r = 0;
-
- // Parsing, e.g.
- // " DockNode ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 "
- // " DockNode ID=0x00000002 Parent=0x00000001 "
- // Important: this code expect currently fields in a fixed order.
- ImGuiDockNodeSettings node;
- line = ImStrSkipBlank(line);
- if (strncmp(line, "DockNode", 8) == 0) { line = ImStrSkipBlank(line + strlen("DockNode")); }
- else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; }
- else return;
- if (sscanf(line, "ID=0x%08X%n", &node.ID, &r) == 1) { line += r; } else return;
- if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeID, &r) == 1) { line += r; if (node.ParentNodeID == 0) return; }
- if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowID, &r) ==1) { line += r; if (node.ParentWindowID == 0) return; }
- if (node.ParentNodeID == 0)
- {
- if (sscanf(line, " Pos=%i,%i%n", &x, &y, &r) == 2) { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return;
- if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2) { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return;
- }
- else
- {
- if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2) { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); }
- }
- if (sscanf(line, " Split=%c%n", &c, &r) == 1) { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; }
- if (sscanf(line, " NoResize=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; }
- if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; }
- if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; }
- if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; }
- if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; }
- if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; }
- if (sscanf(line, " Selected=0x%08X%n", &node.SelectedWindowID,&r) == 1) { line += r; }
- ImGuiDockContext* dc = ctx->DockContext;
- if (node.ParentNodeID != 0)
- if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeID))
- node.Depth = parent_settings->Depth + 1;
- dc->SettingsNodes.push_back(node);
-}
-
-static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth)
-{
- ImGuiDockNodeSettings node_settings;
- IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3)));
- node_settings.ID = node->ID;
- node_settings.ParentNodeID = node->ParentNode ? node->ParentNode->ID : 0;
- node_settings.ParentWindowID = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0;
- node_settings.SelectedWindowID = node->SelectedTabID;
- node_settings.SplitAxis = node->IsSplitNode() ? (char)node->SplitAxis : ImGuiAxis_None;
- node_settings.Depth = (char)depth;
- node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_);
- node_settings.Pos = ImVec2ih(node->Pos);
- node_settings.Size = ImVec2ih(node->Size);
- node_settings.SizeRef = ImVec2ih(node->SizeRef);
- dc->SettingsNodes.push_back(node_settings);
- if (node->ChildNodes[0])
- DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1);
- if (node->ChildNodes[1])
- DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1);
-}
-
-static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
-{
- ImGuiContext& g = *ctx;
- ImGuiDockContext* dc = g.DockContext;
- if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
- return;
-
- // Gather settings data
- // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer)
- dc->SettingsNodes.resize(0);
- dc->SettingsNodes.reserve(dc->Nodes.Data.Size);
- for (int n = 0; n < dc->Nodes.Data.Size; n++)
- if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
- if (node->IsRootNode())
- DockSettingsHandler_DockNodeToSettings(dc, node, 0);
-
- int max_depth = 0;
- for (int node_n = 0; node_n < dc->SettingsNodes.Size; node_n++)
- max_depth = ImMax((int)dc->SettingsNodes[node_n].Depth, max_depth);
-
- // Write to text buffer
- buf->appendf("[%s][Data]\n", handler->TypeName);
- for (int node_n = 0; node_n < dc->SettingsNodes.Size; node_n++)
- {
- const int line_start_pos = buf->size(); (void)line_start_pos;
- const ImGuiDockNodeSettings* node_settings = &dc->SettingsNodes[node_n];
- buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, ""); // Text align nodes to facilitate looking at .ini file
- buf->appendf(" ID=0x%08X", node_settings->ID);
- if (node_settings->ParentNodeID)
- {
- buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeID, node_settings->SizeRef.x, node_settings->SizeRef.y);
- }
- else
- {
- if (node_settings->ParentWindowID)
- buf->appendf(" Window=0x%08X", node_settings->ParentWindowID);
- buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y);
- }
- if (node_settings->SplitAxis != ImGuiAxis_None)
- buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y');
- if (node_settings->Flags & ImGuiDockNodeFlags_NoResize)
- buf->appendf(" NoResize=1");
- if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode)
- buf->appendf(" CentralNode=1");
- if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar)
- buf->appendf(" NoTabBar=1");
- if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar)
- buf->appendf(" HiddenTabBar=1");
- if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton)
- buf->appendf(" NoWindowMenuButton=1");
- if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton)
- buf->appendf(" NoCloseButton=1");
- if (node_settings->SelectedWindowID)
- buf->appendf(" Selected=0x%08X", node_settings->SelectedWindowID);
-
-#if IMGUI_DEBUG_INI_SETTINGS
- // [DEBUG] Include comments in the .ini file to ease debugging
- if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID))
- {
- buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), ""); // Align everything
- if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow)
- buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name);
- int contains_window = 0;
- for (int window_n = 0; window_n < ctx->SettingsWindows.Size; window_n++) // Iterate settings so we can give info about windows that didn't exist during the session.
- if (ctx->SettingsWindows[window_n].DockId == node_settings->ID)
- {
- if (contains_window++ == 0)
- buf->appendf(" ; contains ");
- buf->appendf("'%s' ", ctx->SettingsWindows[window_n].Name);
- }
- }
-#endif
- buf->appendf("\n");
- }
- buf->appendf("\n");
-}
+// (this section is filled in the 'docking' branch)
//-----------------------------------------------------------------------------
// [SECTION] PLATFORM DEPENDENT HELPERS
//-----------------------------------------------------------------------------
-#if defined(_WIN32) && !defined(_WINDOWS_) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS))
-#ifndef WIN32_LEAN_AND_MEAN
-#define WIN32_LEAN_AND_MEAN
-#endif
-#ifndef __MINGW32__
-#include
-#else
-#include
-#endif
-#elif defined(__APPLE__)
-#include
-#endif
-
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
#ifdef _MSC_VER
#pragma comment(lib, "user32")
+#pragma comment(lib, "kernel32")
#endif
// Win32 clipboard implementation
+// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
static const char* GetClipboardTextFn_DefaultImpl(void*)
{
- static ImVector buf_local;
- buf_local.clear();
+ ImGuiContext& g = *GImGui;
+ g.ClipboardHandlerData.clear();
if (!::OpenClipboard(NULL))
return NULL;
HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
@@ -14498,30 +10387,30 @@ static const char* GetClipboardTextFn_DefaultImpl(void*)
::CloseClipboard();
return NULL;
}
- if (ImWchar* wbuf_global = (ImWchar*)::GlobalLock(wbuf_handle))
+ if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
{
- int buf_len = ImTextCountUtf8BytesFromStr(wbuf_global, NULL) + 1;
- buf_local.resize(buf_len);
- ImTextStrToUtf8(buf_local.Data, buf_len, wbuf_global, NULL);
+ int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
+ g.ClipboardHandlerData.resize(buf_len);
+ ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
}
::GlobalUnlock(wbuf_handle);
::CloseClipboard();
- return buf_local.Data;
+ return g.ClipboardHandlerData.Data;
}
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
{
if (!::OpenClipboard(NULL))
return;
- const int wbuf_length = ImTextCountCharsFromUtf8(text, NULL) + 1;
- HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(ImWchar));
+ const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
+ HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
if (wbuf_handle == NULL)
{
::CloseClipboard();
return;
}
- ImWchar* wbuf_global = (ImWchar*)::GlobalLock(wbuf_handle);
- ImTextStrFromUtf8(wbuf_global, wbuf_length, text, NULL);
+ WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
+ ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
::GlobalUnlock(wbuf_handle);
::EmptyClipboard();
if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
@@ -14568,13 +10457,14 @@ static const char* GetClipboardTextFn_DefaultImpl(void*)
CFDataRef cf_data;
if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
{
- static ImVector clipboard_text;
+ ImGuiContext& g = *GImGui;
+ g.ClipboardHandlerData.clear();
int length = (int)CFDataGetLength(cf_data);
- clipboard_text.resize(length + 1);
- CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)clipboard_text.Data);
- clipboard_text[length] = 0;
+ g.ClipboardHandlerData.resize(length + 1);
+ CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
+ g.ClipboardHandlerData[length] = 0;
CFRelease(cf_data);
- return clipboard_text.Data;
+ return g.ClipboardHandlerData.Data;
}
}
}
@@ -14587,123 +10477,135 @@ static const char* GetClipboardTextFn_DefaultImpl(void*)
static const char* GetClipboardTextFn_DefaultImpl(void*)
{
ImGuiContext& g = *GImGui;
- return g.PrivateClipboard.empty() ? NULL : g.PrivateClipboard.begin();
+ return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
}
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
{
ImGuiContext& g = *GImGui;
- g.PrivateClipboard.clear();
+ g.ClipboardHandlerData.clear();
const char* text_end = text + strlen(text);
- g.PrivateClipboard.resize((int)(text_end - text) + 1);
- memcpy(&g.PrivateClipboard[0], text, (size_t)(text_end - text));
- g.PrivateClipboard[(int)(text_end - text)] = 0;
+ g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
+ memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
+ g.ClipboardHandlerData[(int)(text_end - text)] = 0;
}
#endif
-//-----------------------------------------------------------------------------
-// [SECTION] METRICS/DEBUG WINDOW
-//-----------------------------------------------------------------------------
+// Win32 API IME support (for Asian languages, etc.)
+#if defined(_WIN32) && !defined(__GNUC__) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
-static void RenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
+#include
+#ifdef _MSC_VER
+#pragma comment(lib, "imm32")
+#endif
+
+static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y)
{
- ImGuiContext& g = *GImGui;
- ImGuiWindow* window = g.CurrentWindow;
-
- ImVec2 scale = bb.GetSize() / viewport->Size;
- ImVec2 off = bb.Min - viewport->Pos * scale;
- float alpha_mul = (viewport->Flags & ImGuiViewportFlags_Minimized) ? 0.30f : 1.00f;
- window->DrawList->AddRectFilled(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
- for (int i = 0; i != g.Windows.Size; i++)
- {
- ImGuiWindow* thumb_window = g.Windows[i];
- if (!thumb_window->WasActive || ((thumb_window->Flags & ImGuiWindowFlags_ChildWindow)))
- continue;
- if (thumb_window->SkipItems && (thumb_window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME-DOCK: Skip hidden docked windows. Identify those betters.
- continue;
- if (thumb_window->Viewport != viewport)
- continue;
-
- ImRect thumb_r = thumb_window->Rect();
- ImRect title_r = thumb_window->TitleBarRect();
- ImRect thumb_r_scaled = ImRect(ImFloor(off + thumb_r.Min * scale), ImFloor(off + thumb_r.Max * scale));
- ImRect title_r_scaled = ImRect(ImFloor(off + title_r.Min * scale), ImFloor(off + ImVec2(title_r.Max.x, title_r.Min.y) * scale) + ImVec2(0,5)); // Exaggerate title bar height
- thumb_r_scaled.ClipWithFull(bb);
- title_r_scaled.ClipWithFull(bb);
- const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
- window->DrawList->AddRectFilled(thumb_r_scaled.Min, thumb_r_scaled.Max, ImGui::GetColorU32(ImGuiCol_WindowBg, alpha_mul));
- window->DrawList->AddRectFilled(title_r_scaled.Min, title_r_scaled.Max, ImGui::GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
- window->DrawList->AddRect(thumb_r_scaled.Min, thumb_r_scaled.Max, ImGui::GetColorU32(ImGuiCol_Border, alpha_mul));
- if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(thumb_window))
- window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r_scaled.Min, ImGui::GetColorU32(ImGuiCol_Text, alpha_mul), window_for_title->Name, ImGui::FindRenderedTextEnd(window_for_title->Name));
- }
- draw_list->AddRect(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_Border, alpha_mul));
+ // Notify OS Input Method Editor of text input position
+ ImGuiIO& io = ImGui::GetIO();
+ if (HWND hwnd = (HWND)io.ImeWindowHandle)
+ if (HIMC himc = ::ImmGetContext(hwnd))
+ {
+ COMPOSITIONFORM cf;
+ cf.ptCurrentPos.x = x;
+ cf.ptCurrentPos.y = y;
+ cf.dwStyle = CFS_FORCE_POSITION;
+ ::ImmSetCompositionWindow(himc, &cf);
+ ::ImmReleaseContext(hwnd, himc);
+ }
}
-void ImGui::ShowViewportThumbnails()
-{
- ImGuiContext& g = *GImGui;
- ImGuiWindow* window = g.CurrentWindow;
+#else
- // We don't display full monitor bounds (we could, but it often looks awkward), instead we display just enough to cover all of our viewports.
- float SCALE = 1.0f / 8.0f;
- ImRect bb_full;
- //for (int n = 0; n < g.PlatformIO.Monitors.Size; n++)
- // bb_full.Add(GetPlatformMonitorMainRect(g.PlatformIO.Monitors[n]));
- for (int n = 0; n < g.Viewports.Size; n++)
- bb_full.Add(g.Viewports[n]->GetRect());
- ImVec2 p = window->DC.CursorPos;
- ImVec2 off = p - bb_full.Min * SCALE;
- //for (int n = 0; n < g.PlatformIO.Monitors.Size; n++)
- // window->DrawList->AddRect(off + g.PlatformIO.Monitors[n].MainPos * SCALE, off + (g.PlatformIO.Monitors[n].MainPos + g.PlatformIO.Monitors[n].MainSize) * SCALE, ImGui::GetColorU32(ImGuiCol_Border));
- for (int n = 0; n < g.Viewports.Size; n++)
- {
- ImGuiViewportP* viewport = g.Viewports[n];
- ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
- RenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
- }
- ImGui::Dummy(bb_full.GetSize() * SCALE);
-}
+static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {}
+
+#endif
+
+//-----------------------------------------------------------------------------
+// [SECTION] METRICS/DEBUGGER WINDOW
+//-----------------------------------------------------------------------------
+// - MetricsHelpMarker() [Internal]
+// - ShowMetricsWindow()
+// - DebugNodeColumns() [Internal]
+// - DebugNodeDrawList() [Internal]
+// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
+// - DebugNodeStorage() [Internal]
+// - DebugNodeTabBar() [Internal]
+// - DebugNodeWindow() [Internal]
+// - DebugNodeWindowSettings() [Internal]
+// - DebugNodeWindowsList() [Internal]
+//-----------------------------------------------------------------------------
#ifndef IMGUI_DISABLE_METRICS_WINDOW
+
+// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
+static void MetricsHelpMarker(const char* desc)
+{
+ ImGui::TextDisabled("(?)");
+ if (ImGui::IsItemHovered())
+ {
+ ImGui::BeginTooltip();
+ ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
+ ImGui::TextUnformatted(desc);
+ ImGui::PopTextWrapPos();
+ ImGui::EndTooltip();
+ }
+}
+
void ImGui::ShowMetricsWindow(bool* p_open)
{
- if (!ImGui::Begin("Dear ImGui Metrics", p_open))
+ if (!Begin("Dear ImGui Metrics/Debugger", p_open))
{
- ImGui::End();
+ End();
return;
}
- // State
- enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Contents, WRT_ContentsRegionRect, WRT_Count }; // Windows Rect Type
- const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Contents", "ContentsRegionRect" };
- static bool show_windows_rects = false;
- static int show_windows_rect_type = WRT_WorkRect;
- static bool show_windows_begin_order = false;
- static bool show_drawcmd_clip_rects = true;
- static bool show_docking_nodes = false;
+ ImGuiContext& g = *GImGui;
+ ImGuiIO& io = g.IO;
+ ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
// Basic info
- ImGuiContext& g = *GImGui;
- ImGuiIO& io = ImGui::GetIO();
- ImGui::Text("Dear ImGui %s", ImGui::GetVersion());
- ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
- ImGui::Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
- ImGui::Text("%d active windows (%d visible)", io.MetricsActiveWindows, io.MetricsRenderWindows);
- ImGui::Text("%d active allocations", io.MetricsActiveAllocations);
- ImGui::Separator();
+ Text("Dear ImGui %s", ImGui::GetVersion());
+ Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
+ Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
+ Text("%d active windows (%d visible)", io.MetricsActiveWindows, io.MetricsRenderWindows);
+ Text("%d active allocations", io.MetricsActiveAllocations);
+ //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
+
+ Separator();
+
+ // Debugging enums
+ enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
+ const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
+ enum { TRT_OuterRect, TRT_InnerRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsWorkRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentFrozen, TRT_ColumnsContentUnfrozen, TRT_Count }; // Tables Rect Type
+ const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
+ if (cfg->ShowWindowsRectsType < 0)
+ cfg->ShowWindowsRectsType = WRT_WorkRect;
+ if (cfg->ShowTablesRectsType < 0)
+ cfg->ShowTablesRectsType = TRT_WorkRect;
- // Helper functions to display common structures:
- // - NodeDrawList
- // - NodeColumns
- // - NodeWindow
- // - NodeWindows
- // - NodeViewport
- // - NodeDockNode
- // - NodeTabBar
struct Funcs
{
+ static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
+ {
+ if (rect_type == TRT_OuterRect) { return table->OuterRect; }
+ else if (rect_type == TRT_InnerRect) { return table->InnerRect; }
+ else if (rect_type == TRT_WorkRect) { return table->WorkRect; }
+ else if (rect_type == TRT_HostClipRect) { return table->HostClipRect; }
+ else if (rect_type == TRT_InnerClipRect) { return table->InnerClipRect; }
+ else if (rect_type == TRT_BackgroundClipRect) { return table->BgClipRect; }
+ else if (rect_type == TRT_ColumnsRect) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table->LastOuterHeight); }
+ else if (rect_type == TRT_ColumnsWorkRect) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->WorkRect.Min.y, c->WorkMaxX, table->WorkRect.Max.y); }
+ else if (rect_type == TRT_ColumnsClipRect) { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
+ else if (rect_type == TRT_ColumnsContentHeadersUsed){ ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersUsed, table->InnerClipRect.Min.y + table->LastFirstRowHeight); } // Note: y1/y2 not always accurate
+ else if (rect_type == TRT_ColumnsContentHeadersIdeal){ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersIdeal, table->InnerClipRect.Min.y + table->LastFirstRowHeight); }
+ else if (rect_type == TRT_ColumnsContentFrozen) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXFrozen, table->InnerClipRect.Min.y + table->LastFirstRowHeight); }
+ else if (rect_type == TRT_ColumnsContentUnfrozen) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table->LastFirstRowHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); }
+ IM_ASSERT(0);
+ return ImRect();
+ }
+
static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
{
if (rect_type == WRT_OuterRect) { return window->Rect(); }
@@ -14711,393 +10613,225 @@ void ImGui::ShowMetricsWindow(bool* p_open)
else if (rect_type == WRT_InnerRect) { return window->InnerRect; }
else if (rect_type == WRT_InnerClipRect) { return window->InnerClipRect; }
else if (rect_type == WRT_WorkRect) { return window->WorkRect; }
- else if (rect_type == WRT_Contents) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
- else if (rect_type == WRT_ContentsRegionRect) { return window->ContentsRegionRect; }
+ else if (rect_type == WRT_Content) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
+ else if (rect_type == WRT_ContentIdeal) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
+ else if (rect_type == WRT_ContentRegionRect) { return window->ContentRegionRect; }
IM_ASSERT(0);
return ImRect();
}
-
- static void NodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, ImDrawList* draw_list, const char* label)
- {
- bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, draw_list->CmdBuffer.Size);
- if (draw_list == ImGui::GetWindowDrawList())
- {
- ImGui::SameLine();
- ImGui::TextColored(ImVec4(1.0f,0.4f,0.4f,1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
- if (node_open) ImGui::TreePop();
- return;
- }
-
- ImDrawList* fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list
- if (window && fg_draw_list && ImGui::IsItemHovered())
- fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
- if (!node_open)
- return;
-
- if (window && !window->WasActive)
- ImGui::Text("(Note: owning Window is inactive: DrawList is not being rendered!)");
-
- int elem_offset = 0;
- for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.begin(); pcmd < draw_list->CmdBuffer.end(); elem_offset += pcmd->ElemCount, pcmd++)
- {
- if (pcmd->UserCallback == NULL && pcmd->ElemCount == 0)
- continue;
- if (pcmd->UserCallback)
- {
- ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
- continue;
- }
- ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
- char buf[300];
- ImFormatString(buf, IM_ARRAYSIZE(buf), "Draw %4d triangles, tex 0x%p, clip_rect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
- pcmd->ElemCount/3, (void*)(intptr_t)pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
- bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
- if (show_drawcmd_clip_rects && fg_draw_list && ImGui::IsItemHovered())
- {
- ImRect clip_rect = pcmd->ClipRect;
- ImRect vtxs_rect;
- for (int i = elem_offset; i < elem_offset + (int)pcmd->ElemCount; i++)
- vtxs_rect.Add(draw_list->VtxBuffer[idx_buffer ? idx_buffer[i] : i].pos);
- clip_rect.Floor(); fg_draw_list->AddRect(clip_rect.Min, clip_rect.Max, IM_COL32(255,0,255,255));
- vtxs_rect.Floor(); fg_draw_list->AddRect(vtxs_rect.Min, vtxs_rect.Max, IM_COL32(255,255,0,255));
- }
- if (!pcmd_node_open)
- continue;
-
- // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
- ImGui::Text("ElemCount: %d, ElemCount/3: %d, VtxOffset: +%d, IdxOffset: +%d", pcmd->ElemCount, pcmd->ElemCount/3, pcmd->VtxOffset, pcmd->IdxOffset);
- ImGuiListClipper clipper(pcmd->ElemCount/3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
- while (clipper.Step())
- for (int prim = clipper.DisplayStart, idx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++)
- {
- char *buf_p = buf, *buf_end = buf + IM_ARRAYSIZE(buf);
- ImVec2 triangles_pos[3];
- for (int n = 0; n < 3; n++, idx_i++)
- {
- int vtx_i = idx_buffer ? idx_buffer[idx_i] : idx_i;
- ImDrawVert& v = draw_list->VtxBuffer[vtx_i];
- triangles_pos[n] = v.pos;
- buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
- (n == 0) ? "elem" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
- }
- ImGui::Selectable(buf, false);
- if (fg_draw_list && ImGui::IsItemHovered())
- {
- ImDrawListFlags backup_flags = fg_draw_list->Flags;
- fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines at is more readable for very large and thin triangles.
- fg_draw_list->AddPolyline(triangles_pos, 3, IM_COL32(255,255,0,255), true, 1.0f);
- fg_draw_list->Flags = backup_flags;
- }
- }
- ImGui::TreePop();
- }
- ImGui::TreePop();
- }
-
- static void NodeColumns(const ImGuiColumns* columns)
- {
- if (!ImGui::TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
- return;
- ImGui::BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
- for (int column_n = 0; column_n < columns->Columns.Size; column_n++)
- ImGui::BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, GetColumnOffsetFromNorm(columns, columns->Columns[column_n].OffsetNorm));
- ImGui::TreePop();
- }
-
- static void NodeWindow(ImGuiWindow* window, const char* label)
- {
- if (window == NULL)
- {
- ImGui::BulletText("%s: NULL", label);
- return;
- }
- if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, (window->Active || window->WasActive), window))
- return;
- ImGuiWindowFlags flags = window->Flags;
- NodeDrawList(window, window->Viewport, window->DrawList, "DrawList");
- ImGui::BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y);
- ImGui::BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
- (flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
- (flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
- (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
- ImGui::BulletText("WindowClassId: 0x%08X", window->WindowClass.ClassId);
- ImGui::BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f)", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y);
- ImGui::BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
- ImGui::BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
- ImGui::BulletText("NavLastIds: 0x%08X,0x%08X, NavLayerActiveMask: %X", window->NavLastIds[0], window->NavLastIds[1], window->DC.NavLayerActiveMask);
- ImGui::BulletText("NavLastChildNavWindow: %s", window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
- if (!window->NavRectRel[0].IsInverted())
- 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]: ");
- ImGui::BulletText("Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y);
- ImGui::BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1);
- ImGui::BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible);
- if (window->DockNode || window->DockNodeAsHost)
- NodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode");
- if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow");
- if (window->RootWindowDockStop != window->RootWindow) NodeWindow(window->RootWindowDockStop, "RootWindowDockStop");
- if (window->ParentWindow != NULL) NodeWindow(window->ParentWindow, "ParentWindow");
- 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++)
- NodeColumns(&window->ColumnsStorage[n]);
- ImGui::TreePop();
- }
- ImGui::BulletText("Storage: %d bytes", window->StateStorage.Data.size_in_bytes());
- ImGui::TreePop();
- }
-
- static void NodeWindows(ImVector& windows, const char* label)
- {
- if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size))
- return;
- for (int i = 0; i < windows.Size; i++)
- Funcs::NodeWindow(windows[i], "Window");
- ImGui::TreePop();
- }
-
- static void NodeViewport(ImGuiViewportP* viewport)
- {
- ImGui::SetNextItemOpen(true, ImGuiCond_Once);
- if (ImGui::TreeNode((void*)(intptr_t)viewport->ID, "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A"))
- {
- ImGuiWindowFlags flags = viewport->Flags;
- ImGui::BulletText("Pos: (%.0f,%.0f), Size: (%.0f,%.0f), Monitor: %d, DpiScale: %.0f%%", viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y, viewport->PlatformMonitor, viewport->DpiScale * 100.0f);
- if (viewport->Idx > 0) { ImGui::SameLine(); if (ImGui::SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200,200); if (viewport->Window) viewport->Window->Pos = ImVec2(200,200); } }
- ImGui::BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s", viewport->Flags,
- (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "", (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "",
- (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "", (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "",
- (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "", (flags & ImGuiViewportFlags_Minimized) ? " Minimized" : "",
- (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "");
- for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
- for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
- Funcs::NodeDrawList(NULL, viewport, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
- ImGui::TreePop();
- }
- }
-
- static void NodeDockNode(ImGuiDockNode* node, const char* label)
- {
- ImGuiContext& g = *GImGui;
- bool open;
- if (node->Windows.Size > 0)
- open = ImGui::TreeNode((void*)(intptr_t)node->ID, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
- else
- open = ImGui::TreeNode((void*)(intptr_t)node->ID, "%s 0x%04X%s: %s split (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical" : "n/a", node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
- if (open)
- {
- IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node);
- IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node);
- ImGui::BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)",
- node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y);
- NodeWindow(node->HostWindow, "HostWindow");
- NodeWindow(node->VisibleWindow, "VisibleWindow");
- ImGui::BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabID, node->LastFocusedNodeID);
- ImGui::BulletText("Misc:%s%s%s%s", node->IsDockSpace() ? " IsDockSpace" : "", node->IsCentralNode() ? " IsCentralNode" : "", (g.FrameCount - node->LastFrameAlive < 2) ? " IsAlive" : "", (g.FrameCount - node->LastFrameActive < 2) ? " IsActive" : "");
- if (ImGui::TreeNode("flags", "LocalFlags: 0x%04X SharedFlags: 0x%04X", node->LocalFlags, node->SharedFlags))
- {
- ImGui::CheckboxFlags("LocalFlags: NoDocking", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoDocking);
- ImGui::CheckboxFlags("LocalFlags: NoSplit", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoSplit);
- ImGui::CheckboxFlags("LocalFlags: NoResize", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoResize);
- ImGui::CheckboxFlags("LocalFlags: NoTabBar", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoTabBar);
- ImGui::CheckboxFlags("LocalFlags: HiddenTabBar", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_HiddenTabBar);
- ImGui::CheckboxFlags("LocalFlags: NoWindowMenuButton", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoWindowMenuButton);
- ImGui::CheckboxFlags("LocalFlags: NoCloseButton", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoCloseButton);
- ImGui::TreePop();
- }
- if (node->ParentNode)
- NodeDockNode(node->ParentNode, "ParentNode");
- if (node->ChildNodes[0])
- NodeDockNode(node->ChildNodes[0], "Child[0]");
- if (node->ChildNodes[1])
- NodeDockNode(node->ChildNodes[1], "Child[1]");
- if (node->TabBar)
- NodeTabBar(node->TabBar);
- ImGui::TreePop();
- }
- }
-
- static void NodeTabBar(ImGuiTabBar* tab_bar)
- {
- // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
- char buf[256];
- char* p = buf;
- const char* buf_end = buf + IM_ARRAYSIZE(buf);
- p += ImFormatString(p, buf_end - p, "TabBar (%d tabs)%s",
- tab_bar->Tabs.Size, (tab_bar->PrevFrameVisible < ImGui::GetFrameCount() - 2) ? " *Inactive*" : "");
- if (tab_bar->Flags & ImGuiTabBarFlags_DockNode)
- {
- p += ImFormatString(p, buf_end - p, " { ");
- for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
- p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", tab_bar->Tabs[tab_n].Window->Name);
- p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
- }
- if (ImGui::TreeNode(tab_bar, "%s", buf))
- {
- for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
- {
- const ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
- ImGui::PushID(tab);
- if (ImGui::SmallButton("<")) { TabBarQueueChangeTabOrder(tab_bar, tab, -1); } ImGui::SameLine(0, 2);
- if (ImGui::SmallButton(">")) { TabBarQueueChangeTabOrder(tab_bar, tab, +1); } ImGui::SameLine();
- ImGui::Text("%02d%c Tab 0x%08X '%s'", tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, tab->Window ? tab->Window->Name : "N/A");
- ImGui::PopID();
- }
- ImGui::TreePop();
- }
- }
};
- Funcs::NodeWindows(g.Windows, "Windows");
- if (ImGui::TreeNode("Viewport", "Viewports (%d)", g.Viewports.Size))
+ // Tools
+ if (TreeNode("Tools"))
{
- ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing());
- ImGui::ShowViewportThumbnails();
- ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing());
- if (g.PlatformIO.Monitors.Size > 0 && ImGui::TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size))
+ // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
+ if (Button("Item Picker.."))
+ DebugStartItemPicker();
+ SameLine();
+ MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
+
+ Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
+ Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
+ SameLine();
+ SetNextItemWidth(GetFontSize() * 12);
+ cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
+ if (cfg->ShowWindowsRects && g.NavWindow != NULL)
{
- ImGui::TextWrapped("(When viewports are enabled, imgui needs uses monitor data to position popup/tooltips so they don't straddle monitors.)");
- for (int i = 0; i < g.PlatformIO.Monitors.Size; i++)
+ BulletText("'%s':", g.NavWindow->Name);
+ Indent();
+ for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
{
- const ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[i];
- ImGui::BulletText("Monitor #%d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)",
- i, mon.DpiScale * 100.0f,
- mon.MainPos.x, mon.MainPos.y, mon.MainPos.x + mon.MainSize.x, mon.MainPos.y + mon.MainSize.y, mon.MainSize.x, mon.MainSize.y,
- mon.WorkPos.x, mon.WorkPos.y, mon.WorkPos.x + mon.WorkSize.x, mon.WorkPos.y + mon.WorkSize.y, mon.WorkSize.x, mon.WorkSize.y);
+ ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
+ Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
}
- ImGui::TreePop();
+ Unindent();
}
- for (int i = 0; i < g.Viewports.Size; i++)
- Funcs::NodeViewport(g.Viewports[i]);
- ImGui::TreePop();
+ Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
+ Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
+
+ Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
+ SameLine();
+ SetNextItemWidth(GetFontSize() * 12);
+ cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
+ if (cfg->ShowTablesRects && g.NavWindow != NULL)
+ {
+ for (int table_n = 0; table_n < g.Tables.GetSize(); table_n++)
+ {
+ ImGuiTable* table = g.Tables.GetByIndex(table_n);
+ if (table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
+ continue;
+
+ BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
+ if (IsItemHovered())
+ GetForegroundDrawList()->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, ~0, 2.0f);
+ Indent();
+ char buf[128];
+ for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
+ {
+ if (rect_n >= TRT_ColumnsRect)
+ {
+ if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
+ continue;
+ for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
+ {
+ ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
+ ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]);
+ Selectable(buf);
+ if (IsItemHovered())
+ GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, ~0, 2.0f);
+ }
+ }
+ else
+ {
+ ImRect r = Funcs::GetTableRect(table, rect_n, -1);
+ ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]);
+ Selectable(buf);
+ if (IsItemHovered())
+ GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, ~0, 2.0f);
+ }
+ }
+ Unindent();
+ }
+ }
+
+ TreePop();
}
- if (ImGui::TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
+ // Contents
+ DebugNodeWindowsList(&g.Windows, "Windows");
+ //DebugNodeWindowList(&g.WindowsFocusOrder, "WindowsFocusOrder");
+ if (TreeNode("DrawLists", "Active DrawLists (%d)", g.DrawDataBuilder.Layers[0].Size))
+ {
+ for (int i = 0; i < g.DrawDataBuilder.Layers[0].Size; i++)
+ DebugNodeDrawList(NULL, g.DrawDataBuilder.Layers[0][i], "DrawList");
+ TreePop();
+ }
+
+ // Details for Popups
+ if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
{
for (int i = 0; i < g.OpenPopupStack.Size; i++)
{
ImGuiWindow* window = g.OpenPopupStack[i].Window;
- ImGui::BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenPopupStack[i].PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : "");
+ BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenPopupStack[i].PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : "");
}
- ImGui::TreePop();
+ TreePop();
}
- if (ImGui::TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.Data.Size))
+ // Details for TabBars
+ if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetSize()))
{
- for (int n = 0; n < g.TabBars.Data.Size; n++)
- Funcs::NodeTabBar(g.TabBars.GetByIndex(n));
- ImGui::TreePop();
+ for (int n = 0; n < g.TabBars.GetSize(); n++)
+ DebugNodeTabBar(g.TabBars.GetByIndex(n), "TabBar");
+ TreePop();
}
- if (ImGui::TreeNode("Docking"))
+ // Details for Tables
+#ifdef IMGUI_HAS_TABLE
+ if (TreeNode("Tables", "Tables (%d)", g.Tables.GetSize()))
{
- ImGuiDockContext* dc = g.DockContext;
- ImGui::Checkbox("Ctrl shows window dock info", &show_docking_nodes);
+ for (int n = 0; n < g.Tables.GetSize(); n++)
+ DebugNodeTable(g.Tables.GetByIndex(n));
+ TreePop();
+ }
+#endif // #ifdef IMGUI_HAS_TABLE
- if (ImGui::TreeNode("Dock nodes"))
+ // Details for Docking
+#ifdef IMGUI_HAS_DOCK
+ if (TreeNode("Docking"))
+ {
+ TreePop();
+ }
+#endif // #ifdef IMGUI_HAS_DOCK
+
+ // Settings
+ if (TreeNode("Settings"))
+ {
+ if (SmallButton("Clear"))
+ ClearIniSettings();
+ SameLine();
+ if (SmallButton("Save to memory"))
+ SaveIniSettingsToMemory();
+ SameLine();
+ if (SmallButton("Save to disk"))
+ SaveIniSettingsToDisk(g.IO.IniFilename);
+ SameLine();
+ if (g.IO.IniFilename)
+ Text("\"%s\"", g.IO.IniFilename);
+ else
+ TextUnformatted("");
+ Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
+ if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
{
- if (ImGui::SmallButton("Clear settings")) { DockContextClearNodes(&g, 0, true); }
- ImGui::SameLine();
- if (ImGui::SmallButton("Rebuild all")) { dc->WantFullRebuild = true; }
- for (int n = 0; n < dc->Nodes.Data.Size; n++)
- if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
- if (node->IsRootNode())
- Funcs::NodeDockNode(node, "Node");
- ImGui::TreePop();
+ for (int n = 0; n < g.SettingsHandlers.Size; n++)
+ BulletText("%s", g.SettingsHandlers[n].TypeName);
+ TreePop();
}
-
- if (ImGui::TreeNode("Settings"))
+ if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
{
- if (ImGui::SmallButton("Refresh"))
- SaveIniSettingsToMemory();
- ImGui::SameLine();
- if (ImGui::SmallButton("Save to disk"))
- SaveIniSettingsToDisk(g.IO.IniFilename);
- ImGui::Separator();
- ImGui::Text("Docked Windows:");
- for (int n = 0; n < g.SettingsWindows.Size; n++)
- if (g.SettingsWindows[n].DockId != 0)
- ImGui::BulletText("Window '%s' -> DockId %08X", g.SettingsWindows[n].Name, g.SettingsWindows[n].DockId);
- ImGui::Separator();
- ImGui::Text("Dock Nodes:");
- for (int n = 0; n < dc->SettingsNodes.Size; n++)
- {
- ImGuiDockNodeSettings* settings = &dc->SettingsNodes[n];
- const char* selected_tab_name = NULL;
- if (settings->SelectedWindowID)
- {
- if (ImGuiWindow* window = FindWindowByID(settings->SelectedWindowID))
- selected_tab_name = window->Name;
- else if (ImGuiWindowSettings* window_settings = FindWindowSettings(settings->SelectedWindowID))
- selected_tab_name = window_settings->Name;
- }
- ImGui::BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeID, settings->SelectedWindowID, selected_tab_name ? selected_tab_name : settings->SelectedWindowID ? "N/A" : "");
- }
- ImGui::TreePop();
+ for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
+ DebugNodeWindowSettings(settings);
+ TreePop();
}
- ImGui::TreePop();
+#ifdef IMGUI_HAS_TABLE
+ if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
+ {
+ for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
+ DebugNodeTableSettings(settings);
+ TreePop();
+ }
+#endif // #ifdef IMGUI_HAS_TABLE
+
+#ifdef IMGUI_HAS_DOCK
+#endif // #ifdef IMGUI_HAS_DOCK
+
+ if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
+ {
+ InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
+ TreePop();
+ }
+ TreePop();
}
-#if 0
- if (ImGui::TreeNode("Tables", "Tables (%d)", g.Tables.Data.Size))
- {
- ImGui::TreePop();
- }
-#endif
-
- if (ImGui::TreeNode("Internal state"))
+ // Misc Details
+ if (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("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
- ImGui::Text("HoveredId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredId, g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // 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), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, 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("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
- ImGui::Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
- ImGui::Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
- ImGui::TreePop();
+
+ Text("WINDOWING");
+ Indent();
+ Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
+ Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL");
+ Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
+ Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
+ Unindent();
+
+ Text("ITEMS");
+ Indent();
+ Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, input_source_names[g.ActiveIdSource]);
+ Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
+ Text("HoveredId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredId, g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not
+ Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
+ Unindent();
+
+ Text("NAV,FOCUS");
+ Indent();
+ Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
+ Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
+ Text("NavInputSource: %s", input_source_names[g.NavInputSource]);
+ Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
+ Text("NavActivateId: 0x%08X, NavInputId: 0x%08X", g.NavActivateId, g.NavInputId);
+ Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
+ Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
+ Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
+ Unindent();
+
+ TreePop();
}
- if (ImGui::TreeNode("Tools"))
- {
- // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
- if (ImGui::Button("Item Picker.."))
- ImGui::DebugStartItemPicker();
-
- ImGui::Checkbox("Show windows begin order", &show_windows_begin_order);
- ImGui::Checkbox("Show windows rectangles", &show_windows_rects);
- ImGui::SameLine();
- ImGui::SetNextItemWidth(ImGui::GetFontSize() * 12);
- show_windows_rects |= ImGui::Combo("##show_windows_rect_type", &show_windows_rect_type, wrt_rects_names, WRT_Count);
- if (show_windows_rects && g.NavWindow)
- {
- ImGui::BulletText("'%s':", g.NavWindow->Name);
- ImGui::Indent();
- for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
- {
- ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
- ImGui::Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
- }
- ImGui::Unindent();
- }
- ImGui::Checkbox("Show clipping rectangle when hovering ImDrawCmd node", &show_drawcmd_clip_rects);
- ImGui::TreePop();
- }
-
- // Tool: Display windows Rectangles and Begin Order
- if (show_windows_rects || show_windows_begin_order)
+ // Overlay: Display windows Rectangles and Begin Order
+ if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
{
for (int n = 0; n < g.Windows.Size; n++)
{
@@ -15105,52 +10839,328 @@ void ImGui::ShowMetricsWindow(bool* p_open)
if (!window->WasActive)
continue;
ImDrawList* draw_list = GetForegroundDrawList(window);
- if (show_windows_rects)
+ if (cfg->ShowWindowsRects)
{
- ImRect r = Funcs::GetWindowRect(window, show_windows_rect_type);
+ ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
}
- if (show_windows_begin_order && !(window->Flags & ImGuiWindowFlags_ChildWindow))
+ if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
{
char buf[32];
ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
- float font_size = ImGui::GetFontSize();
+ float font_size = GetFontSize();
draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
}
}
}
+#ifdef IMGUI_HAS_TABLE
+ // Overlay: Display Tables Rectangles
+ if (cfg->ShowTablesRects)
+ {
+ for (int table_n = 0; table_n < g.Tables.GetSize(); table_n++)
+ {
+ ImGuiTable* table = g.Tables.GetByIndex(table_n);
+ if (table->LastFrameActive < g.FrameCount - 1)
+ continue;
+ ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
+ if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
+ {
+ for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
+ {
+ ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
+ ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
+ float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
+ draw_list->AddRect(r.Min, r.Max, col, 0.0f, ~0, thickness);
+ }
+ }
+ else
+ {
+ ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
+ draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
+ }
+ }
+ }
+#endif // #ifdef IMGUI_HAS_TABLE
+
+#ifdef IMGUI_HAS_DOCK
+ // Overlay: Display Docking info
if (show_docking_nodes && g.IO.KeyCtrl)
{
- for (int n = 0; n < g.DockContext->Nodes.Data.Size; n++)
- if (ImGuiDockNode* node = (ImGuiDockNode*)g.DockContext->Nodes.Data[n].val_p)
- {
- ImGuiDockNode* root_node = DockNodeGetRootNode(node);
- if (ImGuiDockNode* hovered_node = DockNodeTreeFindNodeByPos(root_node, g.IO.MousePos))
- if (hovered_node != node)
- continue;
- char buf[64] = "";
- char* p = buf;
- ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList((ImGuiViewportP*)GetMainViewport());
- p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : "");
- p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId);
- p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y);
- p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y);
- int depth = DockNodeGetDepth(node);
- overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255));
- ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth;
- overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255));
- overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf);
- }
+ }
+#endif // #ifdef IMGUI_HAS_DOCK
+
+ End();
+}
+
+// [DEBUG] Display contents of Columns
+void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
+{
+ if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
+ return;
+ BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
+ for (int column_n = 0; column_n < columns->Columns.Size; column_n++)
+ BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, GetColumnOffsetFromNorm(columns, columns->Columns[column_n].OffsetNorm));
+ TreePop();
+}
+
+// [DEBUG] Display contents of ImDrawList
+void ImGui::DebugNodeDrawList(ImGuiWindow* window, const ImDrawList* draw_list, const char* label)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
+ int cmd_count = draw_list->CmdBuffer.Size;
+ if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
+ cmd_count--;
+ bool node_open = TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count);
+ if (draw_list == GetWindowDrawList())
+ {
+ SameLine();
+ TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
+ if (node_open)
+ TreePop();
+ return;
}
- ImGui::End();
+ ImDrawList* fg_draw_list = GetForegroundDrawList(window); // Render additional visuals into the top-most draw list
+ if (window && IsItemHovered())
+ fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
+ if (!node_open)
+ return;
+
+ if (window && !window->WasActive)
+ TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
+
+ for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
+ {
+ if (pcmd->UserCallback)
+ {
+ BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
+ continue;
+ }
+
+ char buf[300];
+ ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
+ pcmd->ElemCount / 3, (void*)(intptr_t)pcmd->TextureId,
+ pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
+ bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
+ if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
+ DebugNodeDrawCmdShowMeshAndBoundingBox(window, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
+ if (!pcmd_node_open)
+ continue;
+
+ // Calculate approximate coverage area (touched pixel count)
+ // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
+ const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
+ const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
+ float total_area = 0.0f;
+ for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
+ {
+ ImVec2 triangle[3];
+ for (int n = 0; n < 3; n++, idx_n++)
+ triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
+ total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
+ }
+
+ // Display vertex information summary. Hover to get all triangles drawn in wire-frame
+ ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
+ Selectable(buf);
+ if (IsItemHovered() && fg_draw_list)
+ DebugNodeDrawCmdShowMeshAndBoundingBox(window, draw_list, pcmd, true, false);
+
+ // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
+ ImGuiListClipper clipper;
+ clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
+ while (clipper.Step())
+ for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
+ {
+ char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
+ ImVec2 triangle[3];
+ for (int n = 0; n < 3; n++, idx_i++)
+ {
+ const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
+ triangle[n] = v.pos;
+ buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
+ (n == 0) ? "Vert:" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
+ }
+
+ Selectable(buf, false);
+ if (fg_draw_list && IsItemHovered())
+ {
+ ImDrawListFlags backup_flags = fg_draw_list->Flags;
+ fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
+ fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), true, 1.0f);
+ fg_draw_list->Flags = backup_flags;
+ }
+ }
+ TreePop();
+ }
+ TreePop();
+}
+
+// [DEBUG] Display mesh/aabb of a ImDrawCmd
+void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImGuiWindow* window, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
+{
+ IM_ASSERT(show_mesh || show_aabb);
+ ImDrawList* fg_draw_list = GetForegroundDrawList(window); // Render additional visuals into the top-most draw list
+ ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
+ ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
+
+ // Draw wire-frame version of all triangles
+ ImRect clip_rect = draw_cmd->ClipRect;
+ ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
+ ImDrawListFlags backup_flags = fg_draw_list->Flags;
+ fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
+ for (unsigned int idx_n = draw_cmd->IdxOffset; idx_n < draw_cmd->IdxOffset + draw_cmd->ElemCount; )
+ {
+ ImVec2 triangle[3];
+ for (int n = 0; n < 3; n++, idx_n++)
+ vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
+ if (show_mesh)
+ fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), true, 1.0f); // In yellow: mesh triangles
+ }
+ // Draw bounding boxes
+ if (show_aabb)
+ {
+ fg_draw_list->AddRect(ImFloor(clip_rect.Min), ImFloor(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
+ fg_draw_list->AddRect(ImFloor(vtxs_rect.Min), ImFloor(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
+ }
+ fg_draw_list->Flags = backup_flags;
+}
+
+// [DEBUG] Display contents of ImGuiStorage
+void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
+{
+ if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
+ return;
+ for (int n = 0; n < storage->Data.Size; n++)
+ {
+ const ImGuiStorage::ImGuiStoragePair& p = storage->Data[n];
+ BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
+ }
+ TreePop();
+}
+
+// [DEBUG] Display contents of ImGuiTabBar
+void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
+{
+ // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
+ char buf[256];
+ char* p = buf;
+ const char* buf_end = buf + IM_ARRAYSIZE(buf);
+ const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
+ p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
+ IM_UNUSED(p);
+ if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
+ bool open = TreeNode(tab_bar, "%s", buf);
+ if (!is_active) { PopStyleColor(); }
+ if (is_active && IsItemHovered())
+ {
+ ImDrawList* draw_list = GetForegroundDrawList();
+ draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
+ draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
+ draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
+ }
+ if (open)
+ {
+ for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
+ {
+ const ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
+ PushID(tab);
+ if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
+ if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
+ Text("%02d%c Tab 0x%08X '%s' Offset: %.1f, Width: %.1f/%.1f",
+ tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, (tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "", tab->Offset, tab->Width, tab->ContentWidth);
+ PopID();
+ }
+ TreePop();
+ }
+}
+
+void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
+{
+ if (window == NULL)
+ {
+ BulletText("%s: NULL", label);
+ return;
+ }
+
+ ImGuiContext& g = *GImGui;
+ const bool is_active = window->WasActive;
+ ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
+ if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
+ const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
+ if (!is_active) { PopStyleColor(); }
+ if (IsItemHovered() && is_active)
+ GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
+ if (!open)
+ return;
+
+ if (window->MemoryCompacted)
+ TextDisabled("Note: some memory buffers have been compacted/freed.");
+
+ ImGuiWindowFlags flags = window->Flags;
+ DebugNodeDrawList(window, window->DrawList, "DrawList");
+ BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y);
+ BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
+ (flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
+ (flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
+ (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
+ BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
+ BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
+ BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
+ BulletText("NavLastIds: 0x%08X,0x%08X, NavLayerActiveMask: %X", window->NavLastIds[0], window->NavLastIds[1], window->DC.NavLayerActiveMask);
+ BulletText("NavLastChildNavWindow: %s", window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
+ if (!window->NavRectRel[0].IsInverted())
+ 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
+ BulletText("NavRectRel[0]: ");
+ if (window->RootWindow != window) { DebugNodeWindow(window->RootWindow, "RootWindow"); }
+ if (window->ParentWindow != NULL) { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
+ if (window->DC.ChildWindows.Size > 0) { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
+ if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
+ {
+ for (int n = 0; n < window->ColumnsStorage.Size; n++)
+ DebugNodeColumns(&window->ColumnsStorage[n]);
+ TreePop();
+ }
+ DebugNodeStorage(&window->StateStorage, "Storage");
+ TreePop();
+}
+
+void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
+{
+ Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
+ settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
+}
+
+
+void ImGui::DebugNodeWindowsList(ImVector* windows, const char* label)
+{
+ if (!TreeNode(label, "%s (%d)", label, windows->Size))
+ return;
+ Text("(In front-to-back order:)");
+ for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
+ {
+ PushID((*windows)[i]);
+ DebugNodeWindow((*windows)[i], "Window");
+ PopID();
+ }
+ TreePop();
}
#else
-void ImGui::ShowMetricsWindow(bool*) { }
+void ImGui::ShowMetricsWindow(bool*) {}
+void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
+void ImGui::DebugNodeDrawList(ImGuiWindow*, const ImDrawList*, const char*) {}
+void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImGuiWindow*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
+void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
+void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
+void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
+void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
+void ImGui::DebugNodeWindowsList(ImVector*, const char*) {}
#endif
@@ -15163,3 +11173,5 @@ void ImGui::ShowMetricsWindow(bool*) { }
#endif
//-----------------------------------------------------------------------------
+
+#endif // #ifndef IMGUI_DISABLE
diff --git a/dep/imgui/src/imgui_demo.cpp b/dep/imgui/src/imgui_demo.cpp
index 6fc55cf63..8d52ea356 100644
--- a/dep/imgui/src/imgui_demo.cpp
+++ b/dep/imgui/src/imgui_demo.cpp
@@ -1,34 +1,46 @@
-// dear imgui, v1.74 WIP
+// dear imgui, v1.81 WIP
// (demo code)
+// Help:
+// - Read FAQ at http://dearimgui.org/faq
+// - Newcomers, read 'Programmer guide' in imgui.cpp for notes on how to setup Dear ImGui in your codebase.
+// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
+// Read imgui.cpp for more details, documentation and comments.
+// Get latest version at https://github.com/ocornut/imgui
+
// Message to the person tempted to delete this file when integrating Dear ImGui into their code base:
-// Do NOT remove this file from your project! Think again! It is the most useful reference code that you and other coders
-// will want to refer to and call. Have the ImGui::ShowDemoWindow() function wired in an always-available debug menu of
-// your game/app! Removing this file from your project is hindering access to documentation for everyone in your team,
-// likely leading you to poorer usage of the library.
+// Do NOT remove this file from your project! Think again! It is the most useful reference code that you and other
+// coders will want to refer to and call. Have the ImGui::ShowDemoWindow() function wired in an always-available
+// debug menu of your game/app! Removing this file from your project is hindering access to documentation for everyone
+// in your team, likely leading you to poorer usage of the library.
// Everything in this file will be stripped out by the linker if you don't call ImGui::ShowDemoWindow().
-// If you want to link core Dear ImGui in your shipped builds but want an easy guarantee that the demo will not be linked,
-// you can setup your imconfig.h with #define IMGUI_DISABLE_DEMO_WINDOWS and those functions will be empty.
+// If you want to link core Dear ImGui in your shipped builds but want a thorough guarantee that the demo will not be
+// linked, you can setup your imconfig.h with #define IMGUI_DISABLE_DEMO_WINDOWS and those functions will be empty.
// In other situation, whenever you have Dear ImGui available you probably want this to be available for reference.
// Thank you,
-// -Your beloved friend, imgui_demo.cpp (that you won't delete)
+// -Your beloved friend, imgui_demo.cpp (which you won't delete)
// Message to beginner C/C++ programmers about the meaning of the 'static' keyword:
-// In this demo code, we frequently we use 'static' variables inside functions. A static variable persist across calls, so it is
-// essentially like a global variable but declared inside the scope of the function. We do this as a way to gather code and data
-// in the same place, to make the demo source code faster to read, faster to write, and smaller in size.
-// It also happens to be a convenient way of storing simple UI related information as long as your function doesn't need to be
-// reentrant or used in multiple threads. This might be a pattern you will want to use in your code, but most of the real data
-// you would be editing is likely going to be stored outside your functions.
+// In this demo code, we frequently we use 'static' variables inside functions. A static variable persist across calls,
+// so it is essentially like a global variable but declared inside the scope of the function. We do this as a way to
+// gather code and data in the same place, to make the demo source code faster to read, faster to write, and smaller
+// in size. It also happens to be a convenient way of storing simple UI related information as long as your function
+// doesn't need to be reentrant or used in multiple threads. This might be a pattern you will want to use in your code,
+// but most of the real data you would be editing is likely going to be stored outside your functions.
-// The Demo code is this file is designed to be easy to copy-and-paste in into your application!
+// The Demo code in this file is designed to be easy to copy-and-paste in into your application!
// Because of this:
-// - We never omit the ImGui:: namespace when calling functions, even though most of our code is already in the same namespace.
+// - We never omit the ImGui:: prefix when calling functions, even though most code here is in the same namespace.
// - We try to declare static variables in the local scope, as close as possible to the code using them.
-// - We never use any of the helpers/facilities used internally by dear imgui, unless it has been exposed in the public API (imgui.h).
-// - We never use maths operators on ImVec2/ImVec4. For other imgui sources files, they are provided by imgui_internal.h w/ IMGUI_DEFINE_MATH_OPERATORS,
-// for your own sources file they are optional and require you either enable those, either provide your own via IM_VEC2_CLASS_EXTRA in imconfig.h.
-// Because we don't want to assume anything about your support of maths operators, we don't use them in imgui_demo.cpp.
+// - We never use any of the helpers/facilities used internally by Dear ImGui, unless available in the public API.
+// - We never use maths operators on ImVec2/ImVec4. For our other sources files we use them, and they are provided
+// by imgui_internal.h using the IMGUI_DEFINE_MATH_OPERATORS define. For your own sources file they are optional
+// and require you either enable those, either provide your own via IM_VEC2_CLASS_EXTRA in imconfig.h.
+// Because we can't assume anything about your support of maths operators, we cannot use them in imgui_demo.cpp.
+
+// Navigating this file:
+// - In Visual Studio IDE: CTRL+comma ("Edit.NavigateTo") can follow symbols in comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot.
+// - With Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols in comments.
/*
@@ -36,6 +48,11 @@ Index of this file:
// [SECTION] Forward Declarations, Helpers
// [SECTION] Demo Window / ShowDemoWindow()
+// - sub section: ShowDemoWindowWidgets()
+// - sub section: ShowDemoWindowLayout()
+// - sub section: ShowDemoWindowPopups()
+// - sub section: ShowDemoWindowTables()
+// - sub section: ShowDemoWindowMisc()
// [SECTION] About Window / ShowAboutWindow()
// [SECTION] Style Editor / ShowStyleEditor()
// [SECTION] Example App: Main Menu Bar / ShowExampleAppMainMenuBar()
@@ -49,7 +66,6 @@ Index of this file:
// [SECTION] Example App: Simple Overlay / ShowExampleAppSimpleOverlay()
// [SECTION] Example App: Manipulating Window Titles / ShowExampleAppWindowTitles()
// [SECTION] Example App: Custom Rendering using ImDrawList API / ShowExampleAppCustomRendering()
-// [SECTION] Example App: Docking, DockSpace / ShowExampleAppDockSpace()
// [SECTION] Example App: Documents Handling / ShowExampleAppDocuments()
*/
@@ -59,6 +75,9 @@ Index of this file:
#endif
#include "imgui.h"
+#ifndef IMGUI_DISABLE
+
+// System includes
#include // toupper
#include // INT_MIN, INT_MAX
#include // sqrtf, powf, cosf, sinf, floorf, ceilf
@@ -70,55 +89,75 @@ Index of this file:
#include // intptr_t
#endif
+// Visual Studio warnings
#ifdef _MSC_VER
#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
#endif
+
+// Clang/GCC warnings with -Weverything
#if defined(__clang__)
-#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse.
-#pragma clang diagnostic ignored "-Wdeprecated-declarations" // warning : 'xx' is deprecated: The POSIX name for this item.. // for strdup used in demo code (so user can copy & paste the code)
-#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int'
-#pragma clang diagnostic ignored "-Wformat-security" // warning : warning: format string is not a string literal
-#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
-#pragma clang diagnostic ignored "-Wunused-macros" // warning : warning: macro is not used // we define snprintf/vsnprintf on Windows so they are available, but not always used.
-#if __has_warning("-Wzero-as-null-pointer-constant")
-#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning : zero as null pointer constant // some standard header variations use #define NULL 0
-#endif
-#if __has_warning("-Wdouble-promotion")
-#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
-#endif
-#if __has_warning("-Wreserved-id-macro")
-#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning : macro name is a reserved identifier //
+#if __has_warning("-Wunknown-warning-option")
+#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
#endif
+#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
+#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
+#pragma clang diagnostic ignored "-Wdeprecated-declarations" // warning: 'xx' is deprecated: The POSIX name for this.. // for strdup used in demo code (so user can copy & paste the code)
+#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type
+#pragma clang diagnostic ignored "-Wformat-security" // warning: format string is not a string literal
+#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning: declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
+#pragma clang diagnostic ignored "-Wunused-macros" // warning: macro is not used // we define snprintf/vsnprintf on Windows so they are available, but not always used.
+#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
+#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
+#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning: macro name is a reserved identifier
+#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
#elif defined(__GNUC__)
-#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
-#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
-#pragma GCC diagnostic ignored "-Wformat-security" // warning : format string is not a string literal (potentially insecure)
-#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 "-Wmisleading-indentation" // [__GNUC__ >= 6] warning: this 'if' clause does not guard this statement // GCC 6.0+ only. See #883 on GitHub.
+#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
+#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
+#pragma GCC diagnostic ignored "-Wformat-security" // warning: format string is not a string literal (potentially insecure)
+#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 "-Wmisleading-indentation" // [__GNUC__ >= 6] warning: this 'if' clause does not guard this statement // GCC 6.0+ only. See #883 on GitHub.
#endif
-// Play it nice with Windows users. Notepad in 2017 still doesn't display text data with Unix-style \n.
+// Play it nice with Windows users (Update: May 2018, Notepad now supports Unix-style carriage returns!)
#ifdef _WIN32
#define IM_NEWLINE "\r\n"
-#define snprintf _snprintf
-#define vsnprintf _vsnprintf
#else
#define IM_NEWLINE "\n"
#endif
+// Helpers
+#if defined(_MSC_VER) && !defined(snprintf)
+#define snprintf _snprintf
+#endif
+#if defined(_MSC_VER) && !defined(vsnprintf)
+#define vsnprintf _vsnprintf
+#endif
+
+// Helpers macros
+// We normally try to not use many helpers in imgui_demo.cpp in order to make code easier to copy and paste,
+// but making an exception here as those are largely simplifying code...
+// In other imgui sources we can use nicer internal functions from imgui_internal.h (ImMin/ImMax) but not in the demo.
+#define IM_MIN(A, B) (((A) < (B)) ? (A) : (B))
+#define IM_MAX(A, B) (((A) >= (B)) ? (A) : (B))
+#define IM_CLAMP(V, MN, MX) ((V) < (MN) ? (MN) : (V) > (MX) ? (MX) : (V))
+
+// Enforce cdecl calling convention for functions called by the standard library, in case compilation settings changed the default to e.g. __vectorcall
+#ifndef IMGUI_CDECL
+#ifdef _MSC_VER
+#define IMGUI_CDECL __cdecl
+#else
+#define IMGUI_CDECL
+#endif
+#endif
+
//-----------------------------------------------------------------------------
// [SECTION] Forward Declarations, Helpers
//-----------------------------------------------------------------------------
-#if !defined(IMGUI_DISABLE_OBSOLETE_FUNCTIONS) && defined(IMGUI_DISABLE_TEST_WINDOWS) && !defined(IMGUI_DISABLE_DEMO_WINDOWS) // Obsolete name since 1.53, TEST->DEMO
-#define IMGUI_DISABLE_DEMO_WINDOWS
-#endif
-
#if !defined(IMGUI_DISABLE_DEMO_WINDOWS)
// Forward Declarations
-static void ShowExampleAppDockSpace(bool* p_open);
static void ShowExampleAppDocuments(bool* p_open);
static void ShowExampleAppMainMenuBar();
static void ShowExampleAppConsole(bool* p_open);
@@ -134,7 +173,7 @@ static void ShowExampleAppCustomRendering(bool* p_open);
static void ShowExampleMenuFile();
// Helper to display a little (?) mark which shows a tooltip when hovered.
-// In your own code you may want to display an actual icon if you are using a merged icon fonts (see misc/fonts/README.txt)
+// In your own code you may want to display an actual icon if you are using a merged icon fonts (see docs/FONTS.md)
static void HelpMarker(const char* desc)
{
ImGui::TextDisabled("(?)");
@@ -148,41 +187,36 @@ static void HelpMarker(const char* desc)
}
}
-static void ShowDockingDisabledMessage()
-{
- ImGuiIO& io = ImGui::GetIO();
- ImGui::Text("ERROR: Docking is not enabled! See Demo > Configuration.");
- ImGui::Text("Set io.ConfigFlags |= ImGuiConfigFlags_DockingEnable in your code, or ");
- ImGui::SameLine(0.0f, 0.0f);
- if (ImGui::SmallButton("click here"))
- io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;
-}
-
// Helper to display basic user controls.
void ImGui::ShowUserGuide()
{
ImGuiIO& io = ImGui::GetIO();
ImGui::BulletText("Double-click on title bar to collapse window.");
- ImGui::BulletText("Click and drag on lower corner to resize window\n(double-click to auto fit window to its contents).");
- if (io.ConfigWindowsMoveFromTitleBarOnly)
- ImGui::BulletText("Click and drag on title bar to move window.");
- else
- ImGui::BulletText("Click and drag on any empty space to move window.");
- ImGui::BulletText("TAB/SHIFT+TAB to cycle through keyboard editable fields.");
+ ImGui::BulletText(
+ "Click and drag on lower corner to resize window\n"
+ "(double-click to auto fit window to its contents).");
ImGui::BulletText("CTRL+Click on a slider or drag box to input value as text.");
+ ImGui::BulletText("TAB/SHIFT+TAB to cycle through keyboard editable fields.");
if (io.FontAllowUserScaling)
ImGui::BulletText("CTRL+Mouse Wheel to zoom window contents.");
- ImGui::BulletText("Mouse Wheel to scroll.");
- ImGui::BulletText("While editing text:\n");
+ ImGui::BulletText("While inputing text:\n");
ImGui::Indent();
- ImGui::BulletText("Hold SHIFT or use mouse to select text.");
ImGui::BulletText("CTRL+Left/Right to word jump.");
ImGui::BulletText("CTRL+A or double-click to select all.");
- ImGui::BulletText("CTRL+X,CTRL+C,CTRL+V to use clipboard.");
+ ImGui::BulletText("CTRL+X/C/V to use clipboard cut/copy/paste.");
ImGui::BulletText("CTRL+Z,CTRL+Y to undo/redo.");
ImGui::BulletText("ESCAPE to revert.");
ImGui::BulletText("You can apply arithmetic operators +,*,/ on numerical values.\nUse +- to subtract.");
ImGui::Unindent();
+ ImGui::BulletText("With keyboard navigation enabled:");
+ ImGui::Indent();
+ ImGui::BulletText("Arrow keys to navigate.");
+ ImGui::BulletText("Space to activate a widget.");
+ ImGui::BulletText("Return to input text into a widget.");
+ ImGui::BulletText("Escape to deactivate a widget, close popup, exit child window.");
+ ImGui::BulletText("Alt to jump to the menu layer of a window.");
+ ImGui::BulletText("CTRL+Tab to select a window.");
+ ImGui::Unindent();
}
//-----------------------------------------------------------------------------
@@ -191,27 +225,32 @@ void ImGui::ShowUserGuide()
// - ShowDemoWindowWidgets()
// - ShowDemoWindowLayout()
// - ShowDemoWindowPopups()
+// - ShowDemoWindowTables()
// - ShowDemoWindowColumns()
// - ShowDemoWindowMisc()
//-----------------------------------------------------------------------------
-// We split the contents of the big ShowDemoWindow() function into smaller functions (because the link time of very large functions grow non-linearly)
+// We split the contents of the big ShowDemoWindow() function into smaller functions
+// (because the link time of very large functions grow non-linearly)
static void ShowDemoWindowWidgets();
static void ShowDemoWindowLayout();
static void ShowDemoWindowPopups();
+static void ShowDemoWindowTables();
static void ShowDemoWindowColumns();
static void ShowDemoWindowMisc();
// Demonstrate most Dear ImGui features (this is big function!)
-// You may execute this function to experiment with the UI and understand what it does. You may then search for keywords in the code when you are interested by a specific feature.
+// You may execute this function to experiment with the UI and understand what it does.
+// You may then search for keywords in the code when you are interested by a specific feature.
void ImGui::ShowDemoWindow(bool* p_open)
{
- IM_ASSERT(ImGui::GetCurrentContext() != NULL && "Missing dear imgui context. Refer to examples app!"); // Exceptionally add an extra assert here for people confused with initial dear imgui setup
+ // Exceptionally add an extra assert here for people confused about initial Dear ImGui setup
+ // Most ImGui functions would normally just crash if the context is missing.
+ IM_ASSERT(ImGui::GetCurrentContext() != NULL && "Missing dear imgui context. Refer to examples app!");
// Examples Apps (accessible from the "Examples" menu)
- static bool show_app_dockspace = false;
- static bool show_app_documents = false;
static bool show_app_main_menu_bar = false;
+ static bool show_app_documents = false;
static bool show_app_console = false;
static bool show_app_log = false;
static bool show_app_layout = false;
@@ -223,9 +262,9 @@ void ImGui::ShowDemoWindow(bool* p_open)
static bool show_app_window_titles = false;
static bool show_app_custom_rendering = false;
- if (show_app_dockspace) ShowExampleAppDockSpace(&show_app_dockspace); // Process the Docking app first, as explicit DockSpace() nodes needs to be submitted early (read comments near the DockSpace function)
- if (show_app_documents) ShowExampleAppDocuments(&show_app_documents); // Process the Document app next, as it may also use a DockSpace()
if (show_app_main_menu_bar) ShowExampleAppMainMenuBar();
+ if (show_app_documents) ShowExampleAppDocuments(&show_app_documents);
+
if (show_app_console) ShowExampleAppConsole(&show_app_console);
if (show_app_log) ShowExampleAppLog(&show_app_log);
if (show_app_layout) ShowExampleAppLayout(&show_app_layout);
@@ -242,9 +281,14 @@ void ImGui::ShowDemoWindow(bool* p_open)
static bool show_app_style_editor = false;
static bool show_app_about = false;
- if (show_app_metrics) { ImGui::ShowMetricsWindow(&show_app_metrics); }
- if (show_app_style_editor) { ImGui::Begin("Style Editor", &show_app_style_editor); ImGui::ShowStyleEditor(); ImGui::End(); }
- if (show_app_about) { ImGui::ShowAboutWindow(&show_app_about); }
+ if (show_app_metrics) { ImGui::ShowMetricsWindow(&show_app_metrics); }
+ if (show_app_about) { ImGui::ShowAboutWindow(&show_app_about); }
+ if (show_app_style_editor)
+ {
+ ImGui::Begin("Dear ImGui Style Editor", &show_app_style_editor);
+ ImGui::ShowStyleEditor();
+ ImGui::End();
+ }
// Demonstrate the various window flags. Typically you would just use the default!
static bool no_titlebar = false;
@@ -257,7 +301,6 @@ void ImGui::ShowDemoWindow(bool* p_open)
static bool no_nav = false;
static bool no_background = false;
static bool no_bring_to_front = false;
- static bool no_docking = false;
ImGuiWindowFlags window_flags = 0;
if (no_titlebar) window_flags |= ImGuiWindowFlags_NoTitleBar;
@@ -269,12 +312,11 @@ void ImGui::ShowDemoWindow(bool* p_open)
if (no_nav) window_flags |= ImGuiWindowFlags_NoNav;
if (no_background) window_flags |= ImGuiWindowFlags_NoBackground;
if (no_bring_to_front) window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus;
- if (no_docking) window_flags |= ImGuiWindowFlags_NoDocking;
if (no_close) p_open = NULL; // Don't pass our bool* to Begin
- // We specify a default position/size in case there's no data in the .ini file. Typically this isn't required! We only do it to make the Demo applications a little more welcoming.
- ImVec2 main_viewport_pos = ImGui::GetMainViewport()->Pos;
- ImGui::SetNextWindowPos(ImVec2(main_viewport_pos.x + 650, main_viewport_pos.y + 20), ImGuiCond_FirstUseEver);
+ // We specify a default position/size in case there's no data in the .ini file.
+ // We only do it to make the demo applications a little more welcoming, but typically this isn't required.
+ ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize(ImVec2(550, 680), ImGuiCond_FirstUseEver);
// Main body of the Demo window starts here.
@@ -285,9 +327,13 @@ void ImGui::ShowDemoWindow(bool* p_open)
return;
}
- // Most "big" widgets share a common width settings by default.
- //ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.65f); // Use 2/3 of the space for widgets and 1/3 for labels (default)
- ImGui::PushItemWidth(ImGui::GetFontSize() * -12); // Use fixed width for labels (by passing a negative value), the rest goes to widgets. We choose a width proportional to our font size.
+ // Most "big" widgets share a common width settings by default. See 'Demo->Layout->Widgets Width' for details.
+
+ // e.g. Use 2/3 of the space for widgets and 1/3 for labels (right align)
+ //ImGui::PushItemWidth(-ImGui::GetWindowWidth() * 0.35f);
+
+ // e.g. Leave a fixed amount of width for labels (by passing a negative value), the rest goes to widgets.
+ ImGui::PushItemWidth(ImGui::GetFontSize() * -12);
// Menu Bar
if (ImGui::BeginMenuBar())
@@ -310,13 +356,12 @@ void ImGui::ShowDemoWindow(bool* p_open)
ImGui::MenuItem("Simple overlay", NULL, &show_app_simple_overlay);
ImGui::MenuItem("Manipulating window titles", NULL, &show_app_window_titles);
ImGui::MenuItem("Custom rendering", NULL, &show_app_custom_rendering);
- ImGui::MenuItem("Dockspace", NULL, &show_app_dockspace);
ImGui::MenuItem("Documents", NULL, &show_app_documents);
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Tools"))
{
- ImGui::MenuItem("Metrics", NULL, &show_app_metrics);
+ ImGui::MenuItem("Metrics/Debugger", NULL, &show_app_metrics);
ImGui::MenuItem("Style Editor", NULL, &show_app_style_editor);
ImGui::MenuItem("About Dear ImGui", NULL, &show_app_about);
ImGui::EndMenu();
@@ -329,12 +374,20 @@ void ImGui::ShowDemoWindow(bool* p_open)
if (ImGui::CollapsingHeader("Help"))
{
+ ImGui::Text("ABOUT THIS DEMO:");
+ ImGui::BulletText("Sections below are demonstrating many aspects of the library.");
+ ImGui::BulletText("The \"Examples\" menu above leads to more demo contents.");
+ ImGui::BulletText("The \"Tools\" menu above gives access to: About Box, Style Editor,\n"
+ "and Metrics/Debugger (general purpose Dear ImGui debugging tool).");
+ ImGui::Separator();
+
ImGui::Text("PROGRAMMER GUIDE:");
- ImGui::BulletText("Please see the ShowDemoWindow() code in imgui_demo.cpp. <- you are here!");
- ImGui::BulletText("Please see the comments in imgui.cpp.");
- ImGui::BulletText("Please see the examples/ application.");
- ImGui::BulletText("Enable 'io.ConfigFlags |= NavEnableKeyboard' for keyboard controls.");
- ImGui::BulletText("Enable 'io.ConfigFlags |= NavEnableGamepad' for gamepad controls.");
+ ImGui::BulletText("See the ShowDemoWindow() code in imgui_demo.cpp. <- you are here!");
+ ImGui::BulletText("See comments in imgui.cpp.");
+ ImGui::BulletText("See example applications in the examples/ folder.");
+ ImGui::BulletText("Read the FAQ at http://www.dearimgui.org/faq/");
+ ImGui::BulletText("Set 'io.ConfigFlags |= NavEnableKeyboard' for keyboard controls.");
+ ImGui::BulletText("Set 'io.ConfigFlags |= NavEnableGamepad' for gamepad controls.");
ImGui::Separator();
ImGui::Text("USER GUIDE:");
@@ -347,14 +400,16 @@ void ImGui::ShowDemoWindow(bool* p_open)
if (ImGui::TreeNode("Configuration##2"))
{
- ImGui::CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard);
- ImGui::CheckboxFlags("io.ConfigFlags: NavEnableGamepad", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NavEnableGamepad);
- ImGui::SameLine(); HelpMarker("Required back-end to feed in gamepad inputs in io.NavInputs[] and set io.BackendFlags |= ImGuiBackendFlags_HasGamepad.\n\nRead instructions in imgui.cpp for details.");
- ImGui::CheckboxFlags("io.ConfigFlags: NavEnableSetMousePos", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NavEnableSetMousePos);
+ ImGui::CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", &io.ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard);
+ ImGui::SameLine(); HelpMarker("Enable keyboard controls.");
+ ImGui::CheckboxFlags("io.ConfigFlags: NavEnableGamepad", &io.ConfigFlags, ImGuiConfigFlags_NavEnableGamepad);
+ ImGui::SameLine(); HelpMarker("Enable gamepad controls. Require backend to set io.BackendFlags |= ImGuiBackendFlags_HasGamepad.\n\nRead instructions in imgui.cpp for details.");
+ ImGui::CheckboxFlags("io.ConfigFlags: NavEnableSetMousePos", &io.ConfigFlags, ImGuiConfigFlags_NavEnableSetMousePos);
ImGui::SameLine(); HelpMarker("Instruct navigation to move the mouse cursor. See comment for ImGuiConfigFlags_NavEnableSetMousePos.");
- ImGui::CheckboxFlags("io.ConfigFlags: NoMouse", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NoMouse);
- if (io.ConfigFlags & ImGuiConfigFlags_NoMouse) // Create a way to restore this flag otherwise we could be stuck completely!
+ ImGui::CheckboxFlags("io.ConfigFlags: NoMouse", &io.ConfigFlags, ImGuiConfigFlags_NoMouse);
+ if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
{
+ // The "NoMouse" option can get us stuck with a disabled mouse! Let's provide an alternative way to fix it:
if (fmodf((float)ImGui::GetTime(), 0.40f) < 0.20f)
{
ImGui::SameLine();
@@ -363,69 +418,41 @@ void ImGui::ShowDemoWindow(bool* p_open)
if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Space)))
io.ConfigFlags &= ~ImGuiConfigFlags_NoMouse;
}
- ImGui::CheckboxFlags("io.ConfigFlags: NoMouseCursorChange", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NoMouseCursorChange);
- ImGui::SameLine(); HelpMarker("Instruct back-end to not alter mouse cursor shape and visibility.");
-
- ImGui::CheckboxFlags("io.ConfigFlags: DockingEnable", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_DockingEnable);
- ImGui::SameLine(); HelpMarker(io.ConfigDockingWithShift ? "[beta] Use SHIFT to dock window into each others." : "[beta] Drag from title bar to dock windows into each others.");
- if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable)
- {
- ImGui::Indent();
- ImGui::Checkbox("io.ConfigDockingNoSplit", &io.ConfigDockingNoSplit);
- ImGui::SameLine(); HelpMarker("Simplified docking mode: disable window splitting, so docking is limited to merging multiple windows together into tab-bars.");
- ImGui::Checkbox("io.ConfigDockingWithShift", &io.ConfigDockingWithShift);
- ImGui::SameLine(); HelpMarker("Enable docking when holding Shift only (allows to drop in wider space, reduce visual noise)");
- ImGui::Checkbox("io.ConfigDockingAlwaysTabBar", &io.ConfigDockingAlwaysTabBar);
- ImGui::SameLine(); HelpMarker("Create a docking node and tab-bar on single floating windows.");
- ImGui::Checkbox("io.ConfigDockingTransparentPayload", &io.ConfigDockingTransparentPayload);
- ImGui::SameLine(); HelpMarker("Make window or viewport transparent when docking and only display docking boxes on the target viewport. Useful if rendering of multiple viewport cannot be synced. Best used with ConfigViewportsNoAutoMerge.");
- ImGui::Unindent();
- }
-
- ImGui::CheckboxFlags("io.ConfigFlags: ViewportsEnable", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_ViewportsEnable);
- ImGui::SameLine(); HelpMarker("[beta] Enable beta multi-viewports support. See ImGuiPlatformIO for details.");
- if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
- {
- ImGui::Indent();
- ImGui::Checkbox("io.ConfigViewportsNoAutoMerge", &io.ConfigViewportsNoAutoMerge);
- ImGui::SameLine(); HelpMarker("Set to make all floating imgui windows always create their own viewport. Otherwise, they are merged into the main host viewports when overlapping it.");
- ImGui::Checkbox("io.ConfigViewportsNoTaskBarIcon", &io.ConfigViewportsNoTaskBarIcon);
- ImGui::SameLine(); HelpMarker("Toggling this at runtime is normally unsupported (most platform back-ends won't refresh the task bar icon state right away).");
- ImGui::Checkbox("io.ConfigViewportsNoDecoration", &io.ConfigViewportsNoDecoration);
- ImGui::SameLine(); HelpMarker("Toggling this at runtime is normally unsupported (most platform back-ends won't refresh the decoration right away).");
- ImGui::Checkbox("io.ConfigViewportsNoDefaultParent", &io.ConfigViewportsNoDefaultParent);
- ImGui::SameLine(); HelpMarker("Toggling this at runtime is normally unsupported (most platform back-ends won't refresh the parenting right away).");
- ImGui::Unindent();
- }
-
+ ImGui::CheckboxFlags("io.ConfigFlags: NoMouseCursorChange", &io.ConfigFlags, ImGuiConfigFlags_NoMouseCursorChange);
+ ImGui::SameLine(); HelpMarker("Instruct backend to not alter mouse cursor shape and visibility.");
ImGui::Checkbox("io.ConfigInputTextCursorBlink", &io.ConfigInputTextCursorBlink);
- ImGui::SameLine(); HelpMarker("Set to false to disable blinking cursor, for users who consider it distracting");
+ ImGui::SameLine(); HelpMarker("Enable blinking cursor (optional as some users consider it to be distracting)");
+ ImGui::Checkbox("io.ConfigDragClickToInputText", &io.ConfigDragClickToInputText);
+ ImGui::SameLine(); HelpMarker("Enable turning DragXXX widgets into text input with a simple mouse click-release (without moving).");
ImGui::Checkbox("io.ConfigWindowsResizeFromEdges", &io.ConfigWindowsResizeFromEdges);
ImGui::SameLine(); HelpMarker("Enable resizing of windows from their edges and from the lower-left corner.\nThis requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback.");
ImGui::Checkbox("io.ConfigWindowsMoveFromTitleBarOnly", &io.ConfigWindowsMoveFromTitleBarOnly);
ImGui::Checkbox("io.MouseDrawCursor", &io.MouseDrawCursor);
- ImGui::SameLine(); HelpMarker("Instruct Dear ImGui to render a mouse cursor for you. 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::SameLine(); HelpMarker("Instruct Dear ImGui to render a mouse cursor itself. 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("Also see Style->Rendering for rendering options.");
ImGui::TreePop();
ImGui::Separator();
}
if (ImGui::TreeNode("Backend Flags"))
{
- HelpMarker("Those flags are set by the back-ends (imgui_impl_xxx files) to specify their capabilities.");
- ImGuiBackendFlags backend_flags = io.BackendFlags; // Make a local copy to avoid modifying actual back-end flags.
- ImGui::CheckboxFlags("io.BackendFlags: HasGamepad", (unsigned int *)&backend_flags, ImGuiBackendFlags_HasGamepad);
- ImGui::CheckboxFlags("io.BackendFlags: HasMouseCursors", (unsigned int *)&backend_flags, ImGuiBackendFlags_HasMouseCursors);
- ImGui::CheckboxFlags("io.BackendFlags: HasSetMousePos", (unsigned int *)&backend_flags, ImGuiBackendFlags_HasSetMousePos);
- ImGui::CheckboxFlags("io.BackendFlags: PlatformHasViewports", (unsigned int *)&backend_flags, ImGuiBackendFlags_PlatformHasViewports);
- ImGui::CheckboxFlags("io.BackendFlags: HasMouseHoveredViewport", (unsigned int *)&backend_flags, ImGuiBackendFlags_HasMouseHoveredViewport);
- ImGui::CheckboxFlags("io.BackendFlags: RendererHasVtxOffset", (unsigned int *)&backend_flags, ImGuiBackendFlags_RendererHasVtxOffset);
- ImGui::CheckboxFlags("io.BackendFlags: RendererHasViewports", (unsigned int *)&backend_flags, ImGuiBackendFlags_RendererHasViewports);
+ HelpMarker(
+ "Those flags are set by the backends (imgui_impl_xxx files) to specify their capabilities.\n"
+ "Here we expose then as read-only fields to avoid breaking interactions with your backend.");
+
+ // Make a local copy to avoid modifying actual backend flags.
+ ImGuiBackendFlags backend_flags = io.BackendFlags;
+ ImGui::CheckboxFlags("io.BackendFlags: HasGamepad", &backend_flags, ImGuiBackendFlags_HasGamepad);
+ ImGui::CheckboxFlags("io.BackendFlags: HasMouseCursors", &backend_flags, ImGuiBackendFlags_HasMouseCursors);
+ ImGui::CheckboxFlags("io.BackendFlags: HasSetMousePos", &backend_flags, ImGuiBackendFlags_HasSetMousePos);
+ ImGui::CheckboxFlags("io.BackendFlags: RendererHasVtxOffset", &backend_flags, ImGuiBackendFlags_RendererHasVtxOffset);
ImGui::TreePop();
ImGui::Separator();
}
if (ImGui::TreeNode("Style"))
{
+ HelpMarker("The same contents can be accessed in 'Tools->Style Editor' or by calling the ShowStyleEditor() function.");
ImGui::ShowStyleEditor();
ImGui::TreePop();
ImGui::Separator();
@@ -433,10 +460,13 @@ void ImGui::ShowDemoWindow(bool* p_open)
if (ImGui::TreeNode("Capture/Logging"))
{
- ImGui::TextWrapped("The logging API redirects all text output so you can easily capture the content of a window or a block. Tree nodes can be automatically expanded.");
- HelpMarker("Try opening any of the contents below in this window and then click one of the \"Log To\" button.");
+ HelpMarker(
+ "The logging API redirects all text output so you can easily capture the content of "
+ "a window or a block. Tree nodes can be automatically expanded.\n"
+ "Try opening any of the contents below in this window and then click one of the \"Log To\" button.");
ImGui::LogButtons();
- ImGui::TextWrapped("You can also call ImGui::LogText() to output directly to the log without a visual output.");
+
+ HelpMarker("You can also call ImGui::LogText() to output directly to the log without a visual output.");
if (ImGui::Button("Copy \"Hello, world!\" to clipboard"))
{
ImGui::LogToClipboard();
@@ -449,27 +479,31 @@ void ImGui::ShowDemoWindow(bool* p_open)
if (ImGui::CollapsingHeader("Window options"))
{
- ImGui::Checkbox("No titlebar", &no_titlebar); ImGui::SameLine(150);
- ImGui::Checkbox("No scrollbar", &no_scrollbar); ImGui::SameLine(300);
- ImGui::Checkbox("No menu", &no_menu);
- 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::SameLine(150);
- ImGui::Checkbox("No nav", &no_nav); ImGui::SameLine(300);
- ImGui::Checkbox("No background", &no_background);
- ImGui::Checkbox("No bring to front", &no_bring_to_front);
- ImGui::Checkbox("No docking", &no_docking);
+ if (ImGui::BeginTable("split", 3))
+ {
+ ImGui::TableNextColumn(); ImGui::Checkbox("No titlebar", &no_titlebar);
+ ImGui::TableNextColumn(); ImGui::Checkbox("No scrollbar", &no_scrollbar);
+ ImGui::TableNextColumn(); ImGui::Checkbox("No menu", &no_menu);
+ ImGui::TableNextColumn(); ImGui::Checkbox("No move", &no_move);
+ ImGui::TableNextColumn(); ImGui::Checkbox("No resize", &no_resize);
+ ImGui::TableNextColumn(); ImGui::Checkbox("No collapse", &no_collapse);
+ ImGui::TableNextColumn(); ImGui::Checkbox("No close", &no_close);
+ ImGui::TableNextColumn(); ImGui::Checkbox("No nav", &no_nav);
+ ImGui::TableNextColumn(); ImGui::Checkbox("No background", &no_background);
+ ImGui::TableNextColumn(); ImGui::Checkbox("No bring to front", &no_bring_to_front);
+ ImGui::EndTable();
+ }
}
// All demo contents
ShowDemoWindowWidgets();
ShowDemoWindowLayout();
ShowDemoWindowPopups();
- ShowDemoWindowColumns();
+ ShowDemoWindowTables();
ShowDemoWindowMisc();
// End of ShowDemoWindow()
+ ImGui::PopItemWidth();
ImGui::End();
}
@@ -503,15 +537,17 @@ static void ShowDemoWindowWidgets()
if (i > 0)
ImGui::SameLine();
ImGui::PushID(i);
- ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(i/7.0f, 0.6f, 0.6f));
- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(i/7.0f, 0.7f, 0.7f));
- ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(i/7.0f, 0.8f, 0.8f));
+ ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(i / 7.0f, 0.6f, 0.6f));
+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(i / 7.0f, 0.7f, 0.7f));
+ ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(i / 7.0f, 0.8f, 0.8f));
ImGui::Button("Click");
ImGui::PopStyleColor(3);
ImGui::PopID();
}
- // Use AlignTextToFramePadding() to align text baseline to the baseline of framed elements (otherwise a Text+SameLine+Button sequence will have the text a little too high by default)
+ // Use AlignTextToFramePadding() to align text baseline to the baseline of framed widgets elements
+ // (otherwise a Text+SameLine+Button sequence will have the text a little too high by default!)
+ // See 'Demo->Layout->Text Baseline Alignment' for details.
ImGui::AlignTextToFramePadding();
ImGui::Text("Hold to repeat:");
ImGui::SameLine();
@@ -549,23 +585,41 @@ static void ShowDemoWindowWidgets()
{
// Using the _simplified_ one-liner Combo() api here
// See "Combo" section for examples of how to use the more complete BeginCombo()/EndCombo() api.
- const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" };
+ const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIIIIII", "JJJJ", "KKKKKKK" };
static int item_current = 0;
ImGui::Combo("combo", &item_current, items, IM_ARRAYSIZE(items));
- ImGui::SameLine(); HelpMarker("Refer to the \"Combo\" section below for an explanation of the full BeginCombo/EndCombo API, and demonstration of various flags.\n");
+ ImGui::SameLine(); HelpMarker(
+ "Refer to the \"Combo\" section below for an explanation of the full BeginCombo/EndCombo API, "
+ "and demonstration of various flags.\n");
}
{
+ // To wire InputText() with std::string or any other custom string type,
+ // see the "Text Input > Resize Callback" section of this demo, and the misc/cpp/imgui_stdlib.h file.
static char str0[128] = "Hello, world!";
ImGui::InputText("input text", str0, IM_ARRAYSIZE(str0));
- ImGui::SameLine(); HelpMarker("USER:\nHold 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\nPROGRAMMER:\nYou can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputText() to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example (this is not demonstrated in imgui_demo.cpp).");
+ ImGui::SameLine(); HelpMarker(
+ "USER:\n"
+ "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\n"
+ "PROGRAMMER:\n"
+ "You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputText() "
+ "to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example (this is not demonstrated "
+ "in imgui_demo.cpp).");
static char str1[128] = "";
ImGui::InputTextWithHint("input text (w/ hint)", "enter text here", str1, IM_ARRAYSIZE(str1));
static int i0 = 123;
ImGui::InputInt("input int", &i0);
- ImGui::SameLine(); HelpMarker("You can apply arithmetic operators +,*,/ on numerical values.\n e.g. [ 100 ], input \'*2\', result becomes [ 200 ]\nUse +- to subtract.\n");
+ ImGui::SameLine(); HelpMarker(
+ "You can apply arithmetic operators +,*,/ on numerical values.\n"
+ " e.g. [ 100 ], input \'*2\', result becomes [ 200 ]\n"
+ "Use +- to subtract.");
static float f0 = 0.001f;
ImGui::InputFloat("input float", &f0, 0.01f, 1.0f, "%.3f");
@@ -575,7 +629,9 @@ static void ShowDemoWindowWidgets()
static float f1 = 1.e10f;
ImGui::InputFloat("input scientific", &f1, 0.0f, 0.0f, "%e");
- ImGui::SameLine(); HelpMarker("You can input value using the scientific notation,\n e.g. \"1e+8\" becomes \"100000000\".\n");
+ ImGui::SameLine(); HelpMarker(
+ "You can input value using the scientific notation,\n"
+ " e.g. \"1e+8\" becomes \"100000000\".");
static float vec4a[4] = { 0.10f, 0.20f, 0.30f, 0.44f };
ImGui::InputFloat3("input float3", vec4a);
@@ -584,23 +640,26 @@ static void ShowDemoWindowWidgets()
{
static int i1 = 50, i2 = 42;
ImGui::DragInt("drag int", &i1, 1);
- ImGui::SameLine(); HelpMarker("Click and drag to edit value.\nHold SHIFT/ALT for faster/slower edit.\nDouble-click or CTRL+click to input value.");
+ ImGui::SameLine(); HelpMarker(
+ "Click and drag to edit value.\n"
+ "Hold SHIFT/ALT for faster/slower edit.\n"
+ "Double-click or CTRL+click to input value.");
- ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%d%%");
+ ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%d%%", ImGuiSliderFlags_AlwaysClamp);
- static float f1=1.00f, f2=0.0067f;
+ static float f1 = 1.00f, f2 = 0.0067f;
ImGui::DragFloat("drag float", &f1, 0.005f);
ImGui::DragFloat("drag small float", &f2, 0.0001f, 0.0f, 0.0f, "%.06f ns");
}
{
- static int i1=0;
+ static int i1 = 0;
ImGui::SliderInt("slider int", &i1, -1, 3);
ImGui::SameLine(); HelpMarker("CTRL+click to input value.");
- static float f1=0.123f, f2=0.0f;
+ static float f1 = 0.123f, f2 = 0.0f;
ImGui::SliderFloat("slider float", &f1, 0.0f, 1.0f, "ratio = %.3f");
- ImGui::SliderFloat("slider float (curve)", &f2, -10.0f, 10.0f, "%.4f", 2.0f);
+ ImGui::SliderFloat("slider float (log)", &f2, -10.0f, 10.0f, "%.4f", ImGuiSliderFlags_Logarithmic);
static float angle = 0.0f;
ImGui::SliderAngle("slider angle", &angle);
@@ -609,27 +668,31 @@ static void ShowDemoWindowWidgets()
// Here we completely omit '%d' from the format string, so it'll only display a name.
// This technique can also be used with DragInt().
enum Element { Element_Fire, Element_Earth, Element_Air, Element_Water, Element_COUNT };
- const char* element_names[Element_COUNT] = { "Fire", "Earth", "Air", "Water" };
- static int current_element = Element_Fire;
- const char* current_element_name = (current_element >= 0 && current_element < Element_COUNT) ? element_names[current_element] : "Unknown";
- ImGui::SliderInt("slider enum", ¤t_element, 0, Element_COUNT - 1, current_element_name);
+ static int elem = Element_Fire;
+ const char* elems_names[Element_COUNT] = { "Fire", "Earth", "Air", "Water" };
+ const char* elem_name = (elem >= 0 && elem < Element_COUNT) ? elems_names[elem] : "Unknown";
+ ImGui::SliderInt("slider enum", &elem, 0, Element_COUNT - 1, elem_name);
ImGui::SameLine(); HelpMarker("Using the format string parameter to display a name instead of the underlying integer.");
}
{
- static float col1[3] = { 1.0f,0.0f,0.2f };
- static float col2[4] = { 0.4f,0.7f,0.0f,0.5f };
+ 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(); HelpMarker("Click on the colored square to open a color picker.\nClick and hold to use drag and drop.\nRight-click on the colored square to show options.\nCTRL+click on individual component to input value.\n");
+ ImGui::SameLine(); HelpMarker(
+ "Click on the color square to open a color picker.\n"
+ "Click and hold to use drag and drop.\n"
+ "Right-click on the color square to show options.\n"
+ "CTRL+click on individual component to input value.\n");
ImGui::ColorEdit4("color 2", col2);
}
{
// 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);
+ const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" };
+ static int item_current = 1;
+ ImGui::ListBox("listbox\n(single select)", &item_current, items, IM_ARRAYSIZE(items), 4);
//static int listbox_item_current2 = 2;
//ImGui::SetNextItemWidth(-1);
@@ -651,8 +714,8 @@ static void ShowDemoWindowWidgets()
{
for (int i = 0; i < 5; i++)
{
- // Use SetNextItemOpen() so set the default state of a node to be open.
- // We could also use TreeNodeEx() with the ImGuiTreeNodeFlags_DefaultOpen flag to achieve the same thing!
+ // Use SetNextItemOpen() so set the default state of a node to be open. We could
+ // also use TreeNodeEx() with the ImGuiTreeNodeFlags_DefaultOpen flag to achieve the same thing!
if (i == 0)
ImGui::SetNextItemOpen(true, ImGuiCond_Once);
@@ -660,7 +723,7 @@ static void ShowDemoWindowWidgets()
{
ImGui::Text("blah blah");
ImGui::SameLine();
- if (ImGui::SmallButton("button")) {};
+ if (ImGui::SmallButton("button")) {}
ImGui::TreePop();
}
}
@@ -669,23 +732,31 @@ static void ShowDemoWindowWidgets()
if (ImGui::TreeNode("Advanced, with Selectable nodes"))
{
- HelpMarker("This is a more typical looking tree with selectable nodes.\nClick to select, CTRL+Click to toggle, click on arrows or double-click to open.");
+ HelpMarker(
+ "This is a more typical looking tree with selectable nodes.\n"
+ "Click to select, CTRL+Click to toggle, click on arrows or double-click to open.");
static ImGuiTreeNodeFlags base_flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_SpanAvailWidth;
static bool align_label_with_current_x_position = false;
- ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnArrow", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_OpenOnArrow);
- ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnDoubleClick", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_OpenOnDoubleClick);
- ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAvailWidth", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_SpanAvailWidth);
- ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanFullWidth", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_SpanFullWidth);
- ImGui::Checkbox("Align label with current X position)", &align_label_with_current_x_position);
+ static bool test_drag_and_drop = false;
+ ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnArrow", &base_flags, ImGuiTreeNodeFlags_OpenOnArrow);
+ ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnDoubleClick", &base_flags, ImGuiTreeNodeFlags_OpenOnDoubleClick);
+ ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAvailWidth", &base_flags, ImGuiTreeNodeFlags_SpanAvailWidth); ImGui::SameLine(); HelpMarker("Extend hit area to all available width instead of allowing more items to be laid out after the node.");
+ ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanFullWidth", &base_flags, ImGuiTreeNodeFlags_SpanFullWidth);
+ ImGui::Checkbox("Align label with current X position", &align_label_with_current_x_position);
+ ImGui::Checkbox("Test tree node as drag source", &test_drag_and_drop);
ImGui::Text("Hello!");
if (align_label_with_current_x_position)
ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing());
- static int selection_mask = (1 << 2); // Dumb representation of what may be user-side selection state. You may carry selection state inside or outside your objects in whatever format you see fit.
- int node_clicked = -1; // Temporary storage of what node we have clicked to process selection at the end of the loop. May be a pointer to your own node type, etc.
+ // 'selection_mask' is dumb representation of what may be user-side selection state.
+ // You may retain selection state inside or outside your objects in whatever format you see fit.
+ // 'node_clicked' is temporary storage of what node we have clicked to process selection at the end
+ /// of the loop. May be a pointer to your own node type, etc.
+ static int selection_mask = (1 << 2);
+ int node_clicked = -1;
for (int i = 0; i < 6; i++)
{
- // Disable the default open on single-click behavior and pass in Selected flag according to our selection state.
+ // Disable the default "open on single-click behavior" + set Selected flag according to our selection.
ImGuiTreeNodeFlags node_flags = base_flags;
const bool is_selected = (selection_mask & (1 << i)) != 0;
if (is_selected)
@@ -696,6 +767,12 @@ static void ShowDemoWindowWidgets()
bool node_open = ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Selectable Node %d", i);
if (ImGui::IsItemClicked())
node_clicked = i;
+ if (test_drag_and_drop && ImGui::BeginDragDropSource())
+ {
+ ImGui::SetDragDropPayload("_TREENODE", NULL, 0);
+ ImGui::Text("This is a drag and drop source");
+ ImGui::EndDragDropSource();
+ }
if (node_open)
{
ImGui::BulletText("Blah blah\nBlah Blah");
@@ -705,20 +782,27 @@ static void ShowDemoWindowWidgets()
else
{
// Items 3..5 are Tree Leaves
- // The only reason we use TreeNode at all is to allow selection of the leaf.
- // Otherwise we can use BulletText() or advance the cursor by GetTreeNodeToLabelSpacing() and call Text().
+ // The only reason we use TreeNode at all is to allow selection of the leaf. Otherwise we can
+ // use BulletText() or advance the cursor by GetTreeNodeToLabelSpacing() and call Text().
node_flags |= ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen; // ImGuiTreeNodeFlags_Bullet
ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Selectable Leaf %d", i);
if (ImGui::IsItemClicked())
node_clicked = i;
+ if (test_drag_and_drop && ImGui::BeginDragDropSource())
+ {
+ ImGui::SetDragDropPayload("_TREENODE", NULL, 0);
+ ImGui::Text("This is a drag and drop source");
+ ImGui::EndDragDropSource();
+ }
}
}
if (node_clicked != -1)
{
- // Update selection state. Process outside of tree loop to avoid visual inconsistencies during the clicking-frame.
+ // Update selection state
+ // (process outside of tree loop to avoid visual inconsistencies during the clicking frame)
if (ImGui::GetIO().KeyCtrl)
selection_mask ^= (1 << node_clicked); // CTRL+click to toggle
- else //if (!(selection_mask & (1 << node_clicked))) // Depending on selection behavior you want, this commented bit preserve selection when clicking on item that is part of the selection
+ else //if (!(selection_mask & (1 << node_clicked))) // Depending on selection behavior you want, may want to preserve selection when clicking on item that is part of the selection
selection_mask = (1 << node_clicked); // Click to single-select
}
if (align_label_with_current_x_position)
@@ -767,11 +851,11 @@ static void ShowDemoWindowWidgets()
if (ImGui::TreeNode("Text"))
{
- if (ImGui::TreeNode("Colored Text"))
+ if (ImGui::TreeNode("Colorful Text"))
{
// Using shortcut. You can use PushStyleColor()/PopStyleColor() for more flexibility.
- ImGui::TextColored(ImVec4(1.0f,0.0f,1.0f,1.0f), "Pink");
- ImGui::TextColored(ImVec4(1.0f,1.0f,0.0f,1.0f), "Yellow");
+ ImGui::TextColored(ImVec4(1.0f, 0.0f, 1.0f, 1.0f), "Pink");
+ ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "Yellow");
ImGui::TextDisabled("Disabled");
ImGui::SameLine(); HelpMarker("The TextDisabled color is stored in ImGuiStyle.");
ImGui::TreePop();
@@ -780,27 +864,32 @@ static void ShowDemoWindowWidgets()
if (ImGui::TreeNode("Word Wrapping"))
{
// Using shortcut. You can use PushTextWrapPos()/PopTextWrapPos() for more flexibility.
- ImGui::TextWrapped("This text should automatically wrap on the edge of the window. The current implementation for text wrapping follows simple rules suitable for English and possibly other languages.");
+ ImGui::TextWrapped(
+ "This text should automatically wrap on the edge of the window. The current implementation "
+ "for text wrapping follows simple rules suitable for English and possibly other languages.");
ImGui::Spacing();
static float wrap_width = 200.0f;
ImGui::SliderFloat("Wrap width", &wrap_width, -20, 600, "%.0f");
- ImGui::Text("Test paragraph 1:");
- ImVec2 pos = ImGui::GetCursorScreenPos();
- ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(pos.x + wrap_width, pos.y), ImVec2(pos.x + wrap_width + 10, pos.y + ImGui::GetTextLineHeight()), IM_COL32(255,0,255,255));
- ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width);
- ImGui::Text("The lazy dog is a good dog. This paragraph is made to fit within %.0f pixels. Testing a 1 character word. The quick brown fox jumps over the lazy dog.", wrap_width);
- ImGui::GetWindowDrawList()->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), IM_COL32(255,255,0,255));
- ImGui::PopTextWrapPos();
+ ImDrawList* draw_list = ImGui::GetWindowDrawList();
+ for (int n = 0; n < 2; n++)
+ {
+ ImGui::Text("Test paragraph %d:", n);
+ ImVec2 pos = ImGui::GetCursorScreenPos();
+ ImVec2 marker_min = ImVec2(pos.x + wrap_width, pos.y);
+ ImVec2 marker_max = ImVec2(pos.x + wrap_width + 10, pos.y + ImGui::GetTextLineHeight());
+ ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width);
+ if (n == 0)
+ ImGui::Text("The lazy dog is a good dog. This paragraph should fit within %.0f pixels. Testing a 1 character word. The quick brown fox jumps over the lazy dog.", wrap_width);
+ else
+ ImGui::Text("aaaaaaaa bbbbbbbb, c cccccccc,dddddddd. d eeeeeeee ffffffff. gggggggg!hhhhhhhh");
- ImGui::Text("Test paragraph 2:");
- pos = ImGui::GetCursorScreenPos();
- ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(pos.x + wrap_width, pos.y), ImVec2(pos.x + wrap_width + 10, pos.y + ImGui::GetTextLineHeight()), IM_COL32(255,0,255,255));
- ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width);
- ImGui::Text("aaaaaaaa bbbbbbbb, c cccccccc,dddddddd. d eeeeeeee ffffffff. gggggggg!hhhhhhhh");
- ImGui::GetWindowDrawList()->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), IM_COL32(255,255,0,255));
- ImGui::PopTextWrapPos();
+ // Draw actual text bounding box, following by marker of our expected limit (should not overlap!)
+ draw_list->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), IM_COL32(255, 255, 0, 255));
+ draw_list->AddRectFilled(marker_min, marker_max, IM_COL32(255, 0, 255, 255));
+ ImGui::PopTextWrapPos();
+ }
ImGui::TreePop();
}
@@ -808,14 +897,19 @@ static void ShowDemoWindowWidgets()
if (ImGui::TreeNode("UTF-8 Text"))
{
// UTF-8 test with Japanese characters
- // (Needs a suitable font, try Noto, or Arial Unicode, or M+ fonts. Read misc/fonts/README.txt for details.)
+ // (Needs a suitable font? Try "Google Noto" or "Arial Unicode". See docs/FONTS.md for details.)
// - From C++11 you can use the u8"my text" syntax to encode literal strings as UTF-8
- // - For earlier compiler, you may be able to encode your sources as UTF-8 (e.g. Visual Studio save your file as 'UTF-8 without signature')
- // - FOR THIS DEMO FILE ONLY, BECAUSE WE WANT TO SUPPORT OLD COMPILERS, WE ARE *NOT* INCLUDING RAW UTF-8 CHARACTERS IN THIS SOURCE FILE.
- // Instead we are encoding a few strings with hexadecimal constants. Don't do this in your application!
- // Please use u8"text in any language" in your application!
- // Note that characters values are preserved even by InputText() if the font cannot be displayed, so you can safely copy & paste garbled characters into another application.
- ImGui::TextWrapped("CJK text will only appears if the font was loaded with the appropriate CJK character ranges. Call io.Font->AddFontFromFileTTF() manually to load extra character ranges. Read misc/fonts/README.txt for details.");
+ // - For earlier compiler, you may be able to encode your sources as UTF-8 (e.g. in Visual Studio, you
+ // can save your source files as 'UTF-8 without signature').
+ // - FOR THIS DEMO FILE ONLY, BECAUSE WE WANT TO SUPPORT OLD COMPILERS, WE ARE *NOT* INCLUDING RAW UTF-8
+ // CHARACTERS IN THIS SOURCE FILE. Instead we are encoding a few strings with hexadecimal constants.
+ // Don't do this in your application! Please use u8"text in any language" in your application!
+ // Note that characters values are preserved even by InputText() if the font cannot be displayed,
+ // so you can safely copy & paste garbled characters into another application.
+ ImGui::TextWrapped(
+ "CJK text will only appears if the font was loaded with the appropriate CJK character ranges. "
+ "Call io.Font->AddFontFromFileTTF() manually to load extra character ranges. "
+ "Read docs/FONTS.md for details.");
ImGui::Text("Hiragana: \xe3\x81\x8b\xe3\x81\x8d\xe3\x81\x8f\xe3\x81\x91\xe3\x81\x93 (kakikukeko)"); // Normally we would use u8"blah blah" with the proper characters directly in the string.
ImGui::Text("Kanjis: \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e (nihongo)");
static char buf[32] = "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e";
@@ -829,43 +923,68 @@ static void ShowDemoWindowWidgets()
if (ImGui::TreeNode("Images"))
{
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!");
+ 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.
- // If you use one of the default imgui_impl_XXXX.cpp renderer, they all have comments at the top of their file to specify what they expect to be stored in ImTextureID.
- // (for example, the imgui_impl_dx11.cpp renderer expect a 'ID3D11ShaderResourceView*' pointer. The imgui_impl_opengl3.cpp renderer expect a GLuint OpenGL texture identifier etc.)
- // If you decided that ImTextureID = MyEngineTexture*, then you can pass your MyEngineTexture* pointers to ImGui::Image(), and gather width/height through your own functions, etc.
- // Using ShowMetricsWindow() as a "debugger" to inspect the draw data that are being passed to your render will help you debug issues if you are confused about this.
- // Consider using the lower-level ImDrawList::AddImage() API, via ImGui::GetWindowDrawList()->AddImage().
+ // Below we are displaying the font texture because it is the only texture we have access to inside the demo!
+ // Remember that ImTextureID is just storage for whatever you want it to be. It is essentially a value that
+ // will be passed to the rendering backend via the ImDrawCmd structure.
+ // If you use one of the default imgui_impl_XXXX.cpp rendering backend, they all have comments at the top
+ // of their respective source file to specify what they expect to be stored in ImTextureID, for example:
+ // - The imgui_impl_dx11.cpp renderer expect a 'ID3D11ShaderResourceView*' pointer
+ // - The imgui_impl_opengl3.cpp renderer expect a GLuint OpenGL texture identifier, etc.
+ // More:
+ // - If you decided that ImTextureID = MyEngineTexture*, then you can pass your MyEngineTexture* pointers
+ // to ImGui::Image(), and gather width/height through your own functions, etc.
+ // - You can use ShowMetricsWindow() to inspect the draw data that are being passed to your renderer,
+ // it will help you debug issues if you are confused about it.
+ // - Consider using the lower-level ImDrawList::AddImage() API, via ImGui::GetWindowDrawList()->AddImage().
+ // - Read https://github.com/ocornut/imgui/blob/master/docs/FAQ.md
+ // - Read https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples
ImTextureID my_tex_id = io.Fonts->TexID;
float my_tex_w = (float)io.Fonts->TexWidth;
float my_tex_h = (float)io.Fonts->TexHeight;
-
- ImGui::Text("%.0fx%.0f", my_tex_w, my_tex_h);
- ImVec2 pos = ImGui::GetCursorScreenPos();
- ImGui::Image(my_tex_id, ImVec2(my_tex_w, my_tex_h), ImVec2(0,0), ImVec2(1,1), ImVec4(1.0f,1.0f,1.0f,1.0f), ImVec4(1.0f,1.0f,1.0f,0.5f));
- if (ImGui::IsItemHovered())
{
- ImGui::BeginTooltip();
- 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, ImVec4(1.0f, 1.0f, 1.0f, 1.0f), ImVec4(1.0f, 1.0f, 1.0f, 0.5f));
- ImGui::EndTooltip();
+ ImGui::Text("%.0fx%.0f", my_tex_w, my_tex_h);
+ ImVec2 pos = ImGui::GetCursorScreenPos();
+ ImVec2 uv_min = ImVec2(0.0f, 0.0f); // Top-left
+ ImVec2 uv_max = ImVec2(1.0f, 1.0f); // Lower-right
+ ImVec4 tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); // No tint
+ ImVec4 border_col = ImVec4(1.0f, 1.0f, 1.0f, 0.5f); // 50% opaque white
+ ImGui::Image(my_tex_id, ImVec2(my_tex_w, my_tex_h), uv_min, uv_max, tint_col, border_col);
+ if (ImGui::IsItemHovered())
+ {
+ ImGui::BeginTooltip();
+ float region_sz = 32.0f;
+ float region_x = io.MousePos.x - pos.x - region_sz * 0.5f;
+ float region_y = io.MousePos.y - pos.y - region_sz * 0.5f;
+ float zoom = 4.0f;
+ 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; }
+ 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; }
+ 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, tint_col, border_col);
+ ImGui::EndTooltip();
+ }
}
ImGui::TextWrapped("And now some textured buttons..");
static int pressed_count = 0;
for (int i = 0; i < 8; i++)
{
ImGui::PushID(i);
- int frame_padding = -1 + i; // -1 = uses default padding
- if (ImGui::ImageButton(my_tex_id, ImVec2(32,32), ImVec2(0,0), ImVec2(32.0f/my_tex_w,32/my_tex_h), frame_padding, ImVec4(0.0f,0.0f,0.0f,1.0f)))
+ int frame_padding = -1 + i; // -1 == uses default padding (style.FramePadding)
+ ImVec2 size = ImVec2(32.0f, 32.0f); // Size of the image we want to make visible
+ ImVec2 uv0 = ImVec2(0.0f, 0.0f); // UV coordinates for lower-left
+ ImVec2 uv1 = ImVec2(32.0f / my_tex_w, 32.0f / my_tex_h);// UV coordinates for (32,32) in our texture
+ ImVec4 bg_col = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); // Black background
+ ImVec4 tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); // No tint
+ if (ImGui::ImageButton(my_tex_id, size, uv0, uv1, frame_padding, bg_col, tint_col))
pressed_count += 1;
ImGui::PopID();
ImGui::SameLine();
@@ -879,26 +998,30 @@ static void ShowDemoWindowWidgets()
{
// Expose flags as checkbox for the demo
static ImGuiComboFlags flags = 0;
- ImGui::CheckboxFlags("ImGuiComboFlags_PopupAlignLeft", (unsigned int*)&flags, ImGuiComboFlags_PopupAlignLeft);
+ ImGui::CheckboxFlags("ImGuiComboFlags_PopupAlignLeft", &flags, ImGuiComboFlags_PopupAlignLeft);
ImGui::SameLine(); HelpMarker("Only makes a difference if the popup is larger than the combo");
- if (ImGui::CheckboxFlags("ImGuiComboFlags_NoArrowButton", (unsigned int*)&flags, ImGuiComboFlags_NoArrowButton))
+ if (ImGui::CheckboxFlags("ImGuiComboFlags_NoArrowButton", &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))
+ if (ImGui::CheckboxFlags("ImGuiComboFlags_NoPreview", &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.)
+ // Using the generic BeginCombo() API, you have full control over how to display the combo contents.
+ // (your selection data could be an index, a pointer to the object, an id for the object, a flag intrusively
+ // 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.
+ static int item_current_idx = 0; // Here our selection data is an index.
+ const char* combo_label = items[item_current_idx]; // Label to preview before opening the combo (technically it could be anything)
+ if (ImGui::BeginCombo("combo 1", combo_label, flags))
{
for (int n = 0; n < IM_ARRAYSIZE(items); n++)
{
- bool is_selected = (item_current == items[n]);
+ const bool is_selected = (item_current_idx == n);
if (ImGui::Selectable(items[n], is_selected))
- item_current = items[n];
+ item_current_idx = n;
+
+ // Set the initial focus when opening the combo (scrolling + keyboard navigation focus)
if (is_selected)
- ImGui::SetItemDefaultFocus(); // Set the initial focus when opening the combo (scrolling + for keyboard navigation support in the upcoming navigation branch)
+ ImGui::SetItemDefaultFocus();
}
ImGui::EndCombo();
}
@@ -912,9 +1035,9 @@ static void ShowDemoWindowWidgets()
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; } };
+ struct Funcs { static bool ItemGetter(void* data, int n, const char** out_str) { *out_str = ((const char**)data)[n]; return true; } };
static int item_current_4 = 0;
- ImGui::Combo("combo 4 (function)", &item_current_4, &FuncHolder::ItemGetter, items, IM_ARRAYSIZE(items));
+ ImGui::Combo("combo 4 (function)", &item_current_4, &Funcs::ItemGetter, items, IM_ARRAYSIZE(items));
ImGui::TreePop();
}
@@ -922,9 +1045,11 @@ static void ShowDemoWindowWidgets()
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 selected" as a read-only selection information.
+ // When Selectable() has been clicked it 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).
+ // The earlier is more flexible, as in real application your selection may be stored in many different ways
+ // and not necessarily inside a bool value (e.g. in flags within objects, as an external list, etc).
if (ImGui::TreeNode("Basic"))
{
static bool selection[5] = { false, true, false, false, false };
@@ -968,7 +1093,8 @@ static void ShowDemoWindowWidgets()
}
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.
+ // Using the Selectable() override that takes "bool* p_selected" parameter,
+ // this function toggle your bool value automatically.
static bool selected[3] = { false, false, false };
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");
@@ -977,42 +1103,77 @@ static void ShowDemoWindowWidgets()
}
if (ImGui::TreeNode("In columns"))
{
- ImGui::Columns(3, NULL, false);
- static bool selected[16] = {};
- for (int i = 0; i < 16; i++)
+ static bool selected[10] = {};
+
+ if (ImGui::BeginTable("split1", 3, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings))
{
- char label[32]; sprintf(label, "Item %d", i);
- if (ImGui::Selectable(label, &selected[i])) {}
- ImGui::NextColumn();
+ for (int i = 0; i < 10; i++)
+ {
+ char label[32];
+ sprintf(label, "Item %d", i);
+ ImGui::TableNextColumn();
+ ImGui::Selectable(label, &selected[i]); // FIXME-TABLE: Selection overlap
+ }
+ ImGui::EndTable();
+ }
+ ImGui::Separator();
+ if (ImGui::BeginTable("split2", 3, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings))
+ {
+ for (int i = 0; i < 10; i++)
+ {
+ char label[32];
+ sprintf(label, "Item %d", i);
+ ImGui::TableNextRow();
+ ImGui::TableNextColumn();
+ ImGui::Selectable(label, &selected[i], ImGuiSelectableFlags_SpanAllColumns);
+ ImGui::TableNextColumn();
+ ImGui::Text("Some other contents");
+ ImGui::TableNextColumn();
+ ImGui::Text("123456");
+ }
+ ImGui::EndTable();
}
- ImGui::Columns(1);
ImGui::TreePop();
}
if (ImGui::TreeNode("Grid"))
{
- static bool selected[4*4] = { true, false, false, false, false, true, false, false, false, false, true, false, false, false, false, true };
- for (int i = 0; i < 4*4; i++)
- {
- ImGui::PushID(i);
- if (ImGui::Selectable("Sailor", &selected[i], 0, ImVec2(50,50)))
+ static char selected[4][4] = { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } };
+
+ // Add in a bit of silly fun...
+ const float time = (float)ImGui::GetTime();
+ const bool winning_state = memchr(selected, 0, sizeof(selected)) == NULL; // If all cells are selected...
+ if (winning_state)
+ ImGui::PushStyleVar(ImGuiStyleVar_SelectableTextAlign, ImVec2(0.5f + 0.5f * cosf(time * 2.0f), 0.5f + 0.5f * sinf(time * 3.0f)));
+
+ for (int y = 0; y < 4; y++)
+ for (int x = 0; x < 4; x++)
{
- // Note: We _unnecessarily_ test for both x/y and i here only to silence some static analyzer. The second part of each test is unnecessary.
- int x = i % 4;
- int y = i / 4;
- if (x > 0) { selected[i - 1] ^= 1; }
- if (x < 3 && i < 15) { selected[i + 1] ^= 1; }
- if (y > 0 && i > 3) { selected[i - 4] ^= 1; }
- if (y < 3 && i < 12) { selected[i + 4] ^= 1; }
+ if (x > 0)
+ ImGui::SameLine();
+ ImGui::PushID(y * 4 + x);
+ if (ImGui::Selectable("Sailor", selected[y][x] != 0, 0, ImVec2(50, 50)))
+ {
+ // Toggle clicked cell + toggle neighbors
+ selected[y][x] ^= 1;
+ if (x > 0) { selected[y][x - 1] ^= 1; }
+ if (x < 3) { selected[y][x + 1] ^= 1; }
+ if (y > 0) { selected[y - 1][x] ^= 1; }
+ if (y < 3) { selected[y + 1][x] ^= 1; }
+ }
+ ImGui::PopID();
}
- if ((i % 4) < 3) ImGui::SameLine();
- ImGui::PopID();
- }
+
+ if (winning_state)
+ ImGui::PopStyleVar();
ImGui::TreePop();
}
if (ImGui::TreeNode("Alignment"))
{
- HelpMarker("Alignment applies when a selectable is larger than its text content.\nBy default, Selectables uses style.SelectableTextAlign but it can be overriden on a per-item basis using PushStyleVar().");
- static bool selected[3*3] = { true, false, true, false, true, false, true, false, true };
+ HelpMarker(
+ "By default, Selectables uses style.SelectableTextAlign but it can be overridden on a per-item "
+ "basis using PushStyleVar(). You'll probably want to always keep your default situation to "
+ "left-align otherwise it becomes difficult to layout multiple items on a same line");
+ static bool selected[3 * 3] = { true, false, true, false, true, false, true, false, true };
for (int y = 0; y < 3; y++)
{
for (int x = 0; x < 3; x++)
@@ -1022,7 +1183,7 @@ static void ShowDemoWindowWidgets()
sprintf(name, "(%.1f,%.1f)", alignment.x, alignment.y);
if (x > 0) ImGui::SameLine();
ImGui::PushStyleVar(ImGuiStyleVar_SelectableTextAlign, alignment);
- ImGui::Selectable(name, &selected[3*y+x], ImGuiSelectableFlags_None, ImVec2(80,80));
+ ImGui::Selectable(name, &selected[3 * y + x], ImGuiSelectableFlags_None, ImVec2(80, 80));
ImGui::PopStyleVar();
}
}
@@ -1031,6 +1192,8 @@ static void ShowDemoWindowWidgets()
ImGui::TreePop();
}
+ // To wire InputText() with std::string or any other custom string type,
+ // see the "Text Input > Resize Callback" section of this demo, and the misc/cpp/imgui_stdlib.h file.
if (ImGui::TreeNode("Text Input"))
{
if (ImGui::TreeNode("Multi-line Text Input"))
@@ -1050,38 +1213,110 @@ static void ShowDemoWindowWidgets()
"\tlock cmpxchg8b eax\n";
static ImGuiInputTextFlags flags = ImGuiInputTextFlags_AllowTabInput;
- HelpMarker("You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputTextMultiline() to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example. (This is not demonstrated in imgui_demo.cpp)");
- ImGui::CheckboxFlags("ImGuiInputTextFlags_ReadOnly", (unsigned int*)&flags, ImGuiInputTextFlags_ReadOnly);
- ImGui::CheckboxFlags("ImGuiInputTextFlags_AllowTabInput", (unsigned int*)&flags, ImGuiInputTextFlags_AllowTabInput);
- ImGui::CheckboxFlags("ImGuiInputTextFlags_CtrlEnterForNewLine", (unsigned int*)&flags, ImGuiInputTextFlags_CtrlEnterForNewLine);
+ HelpMarker("You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputTextMultiline() to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example. (This is not demonstrated in imgui_demo.cpp because we don't want to include in here)");
+ ImGui::CheckboxFlags("ImGuiInputTextFlags_ReadOnly", &flags, ImGuiInputTextFlags_ReadOnly);
+ ImGui::CheckboxFlags("ImGuiInputTextFlags_AllowTabInput", &flags, ImGuiInputTextFlags_AllowTabInput);
+ ImGui::CheckboxFlags("ImGuiInputTextFlags_CtrlEnterForNewLine", &flags, ImGuiInputTextFlags_CtrlEnterForNewLine);
ImGui::InputTextMultiline("##source", text, IM_ARRAYSIZE(text), ImVec2(-FLT_MIN, ImGui::GetTextLineHeight() * 16), flags);
ImGui::TreePop();
}
if (ImGui::TreeNode("Filtered Text Input"))
{
- static char buf1[64] = ""; ImGui::InputText("default", buf1, 64);
- static char buf2[64] = ""; ImGui::InputText("decimal", buf2, 64, ImGuiInputTextFlags_CharsDecimal);
- static char buf3[64] = ""; ImGui::InputText("hexadecimal", buf3, 64, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase);
- static char buf4[64] = ""; ImGui::InputText("uppercase", buf4, 64, ImGuiInputTextFlags_CharsUppercase);
- static char buf5[64] = ""; ImGui::InputText("no blank", buf5, 64, ImGuiInputTextFlags_CharsNoBlank);
- struct TextFilters { static int FilterImGuiLetters(ImGuiInputTextCallbackData* data) { if (data->EventChar < 256 && strchr("imgui", (char)data->EventChar)) return 0; return 1; } };
- static char buf6[64] = ""; ImGui::InputText("\"imgui\" letters", buf6, 64, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters);
+ struct TextFilters
+ {
+ // Return 0 (pass) if the character is 'i' or 'm' or 'g' or 'u' or 'i'
+ static int FilterImGuiLetters(ImGuiInputTextCallbackData* data)
+ {
+ if (data->EventChar < 256 && strchr("imgui", (char)data->EventChar))
+ return 0;
+ return 1;
+ }
+ };
- ImGui::Text("Password input");
- static char bufpass[64] = "password123";
- ImGui::InputText("password", bufpass, 64, ImGuiInputTextFlags_Password | ImGuiInputTextFlags_CharsNoBlank);
+ static char buf1[64] = ""; ImGui::InputText("default", buf1, 64);
+ static char buf2[64] = ""; ImGui::InputText("decimal", buf2, 64, ImGuiInputTextFlags_CharsDecimal);
+ static char buf3[64] = ""; ImGui::InputText("hexadecimal", buf3, 64, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase);
+ static char buf4[64] = ""; ImGui::InputText("uppercase", buf4, 64, ImGuiInputTextFlags_CharsUppercase);
+ static char buf5[64] = ""; ImGui::InputText("no blank", buf5, 64, ImGuiInputTextFlags_CharsNoBlank);
+ static char buf6[64] = ""; ImGui::InputText("\"imgui\" letters", buf6, 64, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters);
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Password Input"))
+ {
+ static char password[64] = "password123";
+ ImGui::InputText("password", password, IM_ARRAYSIZE(password), ImGuiInputTextFlags_Password);
ImGui::SameLine(); HelpMarker("Display all characters as '*'.\nDisable clipboard cut and copy.\nDisable logging.\n");
- ImGui::InputTextWithHint("password (w/ hint)", "", bufpass, 64, ImGuiInputTextFlags_Password | ImGuiInputTextFlags_CharsNoBlank);
- ImGui::InputText("password (clear)", bufpass, 64, ImGuiInputTextFlags_CharsNoBlank);
+ ImGui::InputTextWithHint("password (w/ hint)", "", password, IM_ARRAYSIZE(password), ImGuiInputTextFlags_Password);
+ ImGui::InputText("password (clear)", password, IM_ARRAYSIZE(password));
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Completion, History, Edit Callbacks"))
+ {
+ struct Funcs
+ {
+ static int MyCallback(ImGuiInputTextCallbackData* data)
+ {
+ if (data->EventFlag == ImGuiInputTextFlags_CallbackCompletion)
+ {
+ data->InsertChars(data->CursorPos, "..");
+ }
+ else if (data->EventFlag == ImGuiInputTextFlags_CallbackHistory)
+ {
+ if (data->EventKey == ImGuiKey_UpArrow)
+ {
+ data->DeleteChars(0, data->BufTextLen);
+ data->InsertChars(0, "Pressed Up!");
+ data->SelectAll();
+ }
+ else if (data->EventKey == ImGuiKey_DownArrow)
+ {
+ data->DeleteChars(0, data->BufTextLen);
+ data->InsertChars(0, "Pressed Down!");
+ data->SelectAll();
+ }
+ }
+ else if (data->EventFlag == ImGuiInputTextFlags_CallbackEdit)
+ {
+ // Toggle casing of first character
+ char c = data->Buf[0];
+ if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) data->Buf[0] ^= 32;
+ data->BufDirty = true;
+
+ // Increment a counter
+ int* p_int = (int*)data->UserData;
+ *p_int = *p_int + 1;
+ }
+ return 0;
+ }
+ };
+ static char buf1[64];
+ ImGui::InputText("Completion", buf1, 64, ImGuiInputTextFlags_CallbackCompletion, Funcs::MyCallback);
+ ImGui::SameLine(); HelpMarker("Here we append \"..\" each time Tab is pressed. See 'Examples>Console' for a more meaningful demonstration of using this callback.");
+
+ static char buf2[64];
+ ImGui::InputText("History", buf2, 64, ImGuiInputTextFlags_CallbackHistory, Funcs::MyCallback);
+ ImGui::SameLine(); HelpMarker("Here we replace and select text each time Up/Down are pressed. See 'Examples>Console' for a more meaningful demonstration of using this callback.");
+
+ static char buf3[64];
+ static int edit_count = 0;
+ ImGui::InputText("Edit", buf3, 64, ImGuiInputTextFlags_CallbackEdit, Funcs::MyCallback, (void*)&edit_count);
+ ImGui::SameLine(); HelpMarker("Here we toggle the casing of the first character on every edits + count edits.");
+ ImGui::SameLine(); ImGui::Text("(%d)", edit_count);
+
ImGui::TreePop();
}
if (ImGui::TreeNode("Resize Callback"))
{
- // If you have a custom string type you would typically create a ImGui::InputText() wrapper than takes your type as input.
- // See misc/cpp/imgui_stdlib.h and .cpp for an implementation of this using std::string.
- HelpMarker("Demonstrate using ImGuiInputTextFlags_CallbackResize to wire your resizable string type to InputText().\n\nSee misc/cpp/imgui_stdlib.h for an implementation of this for std::string.");
+ // To wire InputText() with std::string or any other custom string type,
+ // you can use the ImGuiInputTextFlags_CallbackResize flag + create a custom ImGui::InputText() wrapper
+ // using your preferred type. See misc/cpp/imgui_stdlib.h for an implementation of this using std::string.
+ HelpMarker(
+ "Using ImGuiInputTextFlags_CallbackResize to wire your custom string type to InputText().\n\n"
+ "See misc/cpp/imgui_stdlib.h for an implementation of this for std::string.");
struct Funcs
{
static int MyResizeCallback(ImGuiInputTextCallbackData* data)
@@ -1090,14 +1325,14 @@ static void ShowDemoWindowWidgets()
{
ImVector* my_str = (ImVector*)data->UserData;
IM_ASSERT(my_str->begin() == data->Buf);
- my_str->resize(data->BufSize); // NB: On resizing calls, generally data->BufSize == data->BufTextLen + 1
+ my_str->resize(data->BufSize); // NB: On resizing calls, generally data->BufSize == data->BufTextLen + 1
data->Buf = my_str->begin();
}
return 0;
}
- // Tip: Because ImGui:: is a namespace you would typicall add your own function into the namespace in your own source files.
- // For example, you may add a function called ImGui::InputText(const char* label, MyString* my_str).
+ // Note: Because ImGui:: is a namespace you would typically add your own function into the namespace.
+ // For example, you code may declare a function 'ImGui::InputText(const char* label, MyString* my_str)'
static bool MyInputTextMultiline(const char* label, ImVector* my_str, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0)
{
IM_ASSERT((flags & ImGuiInputTextFlags_CallbackResize) == 0);
@@ -1106,7 +1341,8 @@ static void ShowDemoWindowWidgets()
};
// For this demo we are using ImVector as a string container.
- // Note that because we need to store a terminating zero character, our size/capacity are 1 more than usually reported by a typical string class.
+ // Note that because we need to store a terminating zero character, our size/capacity are 1 more
+ // than usually reported by a typical string class.
static ImVector my_str;
if (my_str.empty())
my_str.push_back(0);
@@ -1118,8 +1354,149 @@ static void ShowDemoWindowWidgets()
ImGui::TreePop();
}
- // Plot/Graph widgets are currently fairly limited.
- // Consider writing your own plotting widget, or using a third-party one (see "Wiki->Useful Widgets", or github.com/ocornut/imgui/issues/2747)
+ // Tabs
+ if (ImGui::TreeNode("Tabs"))
+ {
+ if (ImGui::TreeNode("Basic"))
+ {
+ ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_None;
+ if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags))
+ {
+ if (ImGui::BeginTabItem("Avocado"))
+ {
+ ImGui::Text("This is the Avocado tab!\nblah blah blah blah blah");
+ ImGui::EndTabItem();
+ }
+ if (ImGui::BeginTabItem("Broccoli"))
+ {
+ ImGui::Text("This is the Broccoli tab!\nblah blah blah blah blah");
+ ImGui::EndTabItem();
+ }
+ if (ImGui::BeginTabItem("Cucumber"))
+ {
+ ImGui::Text("This is the Cucumber tab!\nblah blah blah blah blah");
+ ImGui::EndTabItem();
+ }
+ ImGui::EndTabBar();
+ }
+ ImGui::Separator();
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Advanced & Close Button"))
+ {
+ // Expose a couple of the available flags. In most cases you may just call BeginTabBar() with no flags (0).
+ static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable;
+ ImGui::CheckboxFlags("ImGuiTabBarFlags_Reorderable", &tab_bar_flags, ImGuiTabBarFlags_Reorderable);
+ ImGui::CheckboxFlags("ImGuiTabBarFlags_AutoSelectNewTabs", &tab_bar_flags, ImGuiTabBarFlags_AutoSelectNewTabs);
+ ImGui::CheckboxFlags("ImGuiTabBarFlags_TabListPopupButton", &tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton);
+ ImGui::CheckboxFlags("ImGuiTabBarFlags_NoCloseWithMiddleMouseButton", &tab_bar_flags, ImGuiTabBarFlags_NoCloseWithMiddleMouseButton);
+ if ((tab_bar_flags & ImGuiTabBarFlags_FittingPolicyMask_) == 0)
+ tab_bar_flags |= ImGuiTabBarFlags_FittingPolicyDefault_;
+ if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyResizeDown", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyResizeDown))
+ tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyResizeDown);
+ if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyScroll", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyScroll))
+ tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyScroll);
+
+ // Tab Bar
+ const char* names[4] = { "Artichoke", "Beetroot", "Celery", "Daikon" };
+ static bool opened[4] = { true, true, true, true }; // Persistent user state
+ for (int n = 0; n < IM_ARRAYSIZE(opened); n++)
+ {
+ if (n > 0) { ImGui::SameLine(); }
+ ImGui::Checkbox(names[n], &opened[n]);
+ }
+
+ // Passing a bool* to BeginTabItem() is similar to passing one to Begin():
+ // the underlying bool will be set to false when the tab is closed.
+ if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags))
+ {
+ for (int n = 0; n < IM_ARRAYSIZE(opened); n++)
+ if (opened[n] && ImGui::BeginTabItem(names[n], &opened[n], ImGuiTabItemFlags_None))
+ {
+ ImGui::Text("This is the %s tab!", names[n]);
+ if (n & 1)
+ ImGui::Text("I am an odd tab.");
+ ImGui::EndTabItem();
+ }
+ ImGui::EndTabBar();
+ }
+ ImGui::Separator();
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("TabItemButton & Leading/Trailing flags"))
+ {
+ static ImVector active_tabs;
+ static int next_tab_id = 0;
+ if (next_tab_id == 0) // Initialize with some default tabs
+ for (int i = 0; i < 3; i++)
+ active_tabs.push_back(next_tab_id++);
+
+ // TabItemButton() and Leading/Trailing flags are distinct features which we will demo together.
+ // (It is possible to submit regular tabs with Leading/Trailing flags, or TabItemButton tabs without Leading/Trailing flags...
+ // but they tend to make more sense together)
+ static bool show_leading_button = true;
+ static bool show_trailing_button = true;
+ ImGui::Checkbox("Show Leading TabItemButton()", &show_leading_button);
+ ImGui::Checkbox("Show Trailing TabItemButton()", &show_trailing_button);
+
+ // Expose some other flags which are useful to showcase how they interact with Leading/Trailing tabs
+ static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_AutoSelectNewTabs | ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_FittingPolicyResizeDown;
+ ImGui::CheckboxFlags("ImGuiTabBarFlags_TabListPopupButton", &tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton);
+ if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyResizeDown", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyResizeDown))
+ tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyResizeDown);
+ if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyScroll", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyScroll))
+ tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyScroll);
+
+ if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags))
+ {
+ // Demo a Leading TabItemButton(): click the "?" button to open a menu
+ if (show_leading_button)
+ if (ImGui::TabItemButton("?", ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_NoTooltip))
+ ImGui::OpenPopup("MyHelpMenu");
+ if (ImGui::BeginPopup("MyHelpMenu"))
+ {
+ ImGui::Selectable("Hello!");
+ ImGui::EndPopup();
+ }
+
+ // Demo Trailing Tabs: click the "+" button to add a new tab (in your app you may want to use a font icon instead of the "+")
+ // Note that we submit it before the regular tabs, but because of the ImGuiTabItemFlags_Trailing flag it will always appear at the end.
+ if (show_trailing_button)
+ if (ImGui::TabItemButton("+", ImGuiTabItemFlags_Trailing | ImGuiTabItemFlags_NoTooltip))
+ active_tabs.push_back(next_tab_id++); // Add new tab
+
+ // Submit our regular tabs
+ for (int n = 0; n < active_tabs.Size; )
+ {
+ bool open = true;
+ char name[16];
+ snprintf(name, IM_ARRAYSIZE(name), "%04d", active_tabs[n]);
+ if (ImGui::BeginTabItem(name, &open, ImGuiTabItemFlags_None))
+ {
+ ImGui::Text("This is the %s tab!", name);
+ ImGui::EndTabItem();
+ }
+
+ if (!open)
+ active_tabs.erase(active_tabs.Data + n);
+ else
+ n++;
+ }
+
+ ImGui::EndTabBar();
+ }
+ ImGui::Separator();
+ ImGui::TreePop();
+ }
+ ImGui::TreePop();
+ }
+
+ // Plot/Graph widgets are not very good.
+ // Consider writing your own, or using a third-party one, see:
+ // - ImPlot https://github.com/epezent/implot
+ // - others https://github.com/ocornut/imgui/wiki/Useful-Widgets
if (ImGui::TreeNode("Plots Widgets"))
{
static bool animate = true;
@@ -1128,20 +1505,21 @@ static void ShowDemoWindowWidgets()
static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f };
ImGui::PlotLines("Frame Times", arr, IM_ARRAYSIZE(arr));
- // Create a dummy array of contiguous float values to plot
- // Tip: If your float aren't contiguous but part of a structure, you can pass a pointer to your first float and the sizeof() of your structure in the Stride parameter.
+ // Fill an array of contiguous float values to plot
+ // Tip: If your float aren't contiguous but part of a structure, you can pass a pointer to your first float
+ // and the sizeof() of your structure in the "stride" parameter.
static float values[90] = {};
static int values_offset = 0;
static double refresh_time = 0.0;
if (!animate || refresh_time == 0.0)
refresh_time = ImGui::GetTime();
- while (refresh_time < ImGui::GetTime()) // Create dummy data at fixed 60 hz rate for the demo
+ while (refresh_time < ImGui::GetTime()) // Create data at fixed 60 Hz rate for the demo
{
static float phase = 0.0f;
values[values_offset] = cosf(phase);
- values_offset = (values_offset+1) % IM_ARRAYSIZE(values);
- phase += 0.10f*values_offset;
- refresh_time += 1.0f/60.0f;
+ values_offset = (values_offset + 1) % IM_ARRAYSIZE(values);
+ phase += 0.10f * values_offset;
+ refresh_time += 1.0f / 60.0f;
}
// Plots can display overlay texts
@@ -1153,12 +1531,13 @@ static void ShowDemoWindowWidgets()
average /= (float)IM_ARRAYSIZE(values);
char overlay[32];
sprintf(overlay, "avg %f", average);
- ImGui::PlotLines("Lines", values, IM_ARRAYSIZE(values), values_offset, overlay, -1.0f, 1.0f, ImVec2(0,80));
+ ImGui::PlotLines("Lines", values, IM_ARRAYSIZE(values), values_offset, overlay, -1.0f, 1.0f, ImVec2(0, 80.0f));
}
- ImGui::PlotHistogram("Histogram", arr, IM_ARRAYSIZE(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0,80));
+ ImGui::PlotHistogram("Histogram", arr, IM_ARRAYSIZE(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0, 80.0f));
// Use functions to generate output
- // FIXME: This is rather awkward because current plot API only pass in indices. We probably want an API passing floats and user provide sample rate/count.
+ // FIXME: This is rather awkward because current plot API only pass in indices.
+ // We probably want an API passing floats and user provide sample rate/count.
struct Funcs
{
static float Sin(void*, int i) { return sinf(i * 0.1f); }
@@ -1171,8 +1550,8 @@ static void ShowDemoWindowWidgets()
ImGui::SameLine();
ImGui::SliderInt("Sample count", &display_count, 1, 400);
float (*func)(void*, int) = (func_type == 0) ? Funcs::Sin : Funcs::Saw;
- ImGui::PlotLines("Lines", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0,80));
- ImGui::PlotHistogram("Histogram", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0,80));
+ ImGui::PlotLines("Lines", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80));
+ ImGui::PlotHistogram("Histogram", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80));
ImGui::Separator();
// Animate a simple progress bar
@@ -1186,20 +1565,20 @@ static void ShowDemoWindowWidgets()
// Typically we would use ImVec2(-1.0f,0.0f) or ImVec2(-FLT_MIN,0.0f) to use all available width,
// or ImVec2(width,0.0f) for a specified width. ImVec2(0.0f,0.0f) uses ItemWidth.
- ImGui::ProgressBar(progress, ImVec2(0.0f,0.0f));
+ ImGui::ProgressBar(progress, ImVec2(0.0f, 0.0f));
ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x);
ImGui::Text("Progress Bar");
- float progress_saturated = (progress < 0.0f) ? 0.0f : (progress > 1.0f) ? 1.0f : progress;
+ float progress_saturated = IM_CLAMP(progress, 0.0f, 1.0f);
char buf[32];
- sprintf(buf, "%d/%d", (int)(progress_saturated*1753), 1753);
- ImGui::ProgressBar(progress, ImVec2(0.f,0.f), buf);
+ sprintf(buf, "%d/%d", (int)(progress_saturated * 1753), 1753);
+ ImGui::ProgressBar(progress, ImVec2(0.f, 0.f), buf);
ImGui::TreePop();
}
if (ImGui::TreeNode("Color/Picker Widgets"))
{
- static ImVec4 color = ImVec4(114.0f/255.0f, 144.0f/255.0f, 154.0f/255.0f, 200.0f/255.0f);
+ static ImVec4 color = ImVec4(114.0f / 255.0f, 144.0f / 255.0f, 154.0f / 255.0f, 200.0f / 255.0f);
static bool alpha_preview = true;
static bool alpha_half_preview = false;
@@ -1214,7 +1593,9 @@ static void ShowDemoWindowWidgets()
ImGuiColorEditFlags misc_flags = (hdr ? ImGuiColorEditFlags_HDR : 0) | (drag_and_drop ? 0 : ImGuiColorEditFlags_NoDragDrop) | (alpha_half_preview ? ImGuiColorEditFlags_AlphaPreviewHalf : (alpha_preview ? ImGuiColorEditFlags_AlphaPreview : 0)) | (options_menu ? 0 : ImGuiColorEditFlags_NoOptions);
ImGui::Text("Color widget:");
- ImGui::SameLine(); HelpMarker("Click on the colored square to open a color picker.\nCTRL+click on individual component to input value.\n");
+ ImGui::SameLine(); HelpMarker(
+ "Click on the color square to open a color picker.\n"
+ "CTRL+click on individual component to input value.\n");
ImGui::ColorEdit3("MyColor##1", (float*)&color, misc_flags);
ImGui::Text("Color widget HSV with Alpha:");
@@ -1224,19 +1605,23 @@ static void ShowDemoWindowWidgets()
ImGui::ColorEdit4("MyColor##2f", (float*)&color, ImGuiColorEditFlags_Float | misc_flags);
ImGui::Text("Color button with Picker:");
- ImGui::SameLine(); HelpMarker("With the ImGuiColorEditFlags_NoInputs flag you can hide all the slider/text inputs.\nWith the ImGuiColorEditFlags_NoLabel flag you can pass a non-empty label which will only be used for the tooltip and picker popup.");
+ ImGui::SameLine(); HelpMarker(
+ "With the ImGuiColorEditFlags_NoInputs flag you can hide all the slider/text inputs.\n"
+ "With the ImGuiColorEditFlags_NoLabel flag you can pass a non-empty label which will only "
+ "be used for the tooltip and picker popup.");
ImGui::ColorEdit4("MyColor##3", (float*)&color, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | misc_flags);
ImGui::Text("Color button with Custom Picker Popup:");
- // Generate a dummy default palette. The palette will persist and can be edited.
+ // Generate a default palette. The palette will persist and can be edited.
static bool saved_palette_init = true;
static ImVec4 saved_palette[32] = {};
if (saved_palette_init)
{
for (int n = 0; n < IM_ARRAYSIZE(saved_palette); n++)
{
- ImGui::ColorConvertHSVtoRGB(n / 31.0f, 0.8f, 0.8f, saved_palette[n].x, saved_palette[n].y, saved_palette[n].z);
+ ImGui::ColorConvertHSVtoRGB(n / 31.0f, 0.8f, 0.8f,
+ saved_palette[n].x, saved_palette[n].y, saved_palette[n].z);
saved_palette[n].w = 1.0f; // Alpha
}
saved_palette_init = false;
@@ -1260,9 +1645,9 @@ static void ShowDemoWindowWidgets()
ImGui::BeginGroup(); // Lock X position
ImGui::Text("Current");
- ImGui::ColorButton("##current", color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60,40));
+ ImGui::ColorButton("##current", color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40));
ImGui::Text("Previous");
- if (ImGui::ColorButton("##previous", backup_color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60,40)))
+ if (ImGui::ColorButton("##previous", backup_color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40)))
color = backup_color;
ImGui::Separator();
ImGui::Text("Palette");
@@ -1271,11 +1656,13 @@ static void ShowDemoWindowWidgets()
ImGui::PushID(n);
if ((n % 8) != 0)
ImGui::SameLine(0.0f, ImGui::GetStyle().ItemSpacing.y);
- if (ImGui::ColorButton("##palette", saved_palette[n], ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_NoTooltip, ImVec2(20,20)))
+
+ ImGuiColorEditFlags palette_button_flags = ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_NoTooltip;
+ if (ImGui::ColorButton("##palette", saved_palette[n], palette_button_flags, ImVec2(20, 20)))
color = ImVec4(saved_palette[n].x, saved_palette[n].y, saved_palette[n].z, color.w); // Preserve alpha!
- // Allow user to drop colors into each palette entry
- // (Note that ColorButton is already a drag source by default, unless using ImGuiColorEditFlags_NoDragDrop)
+ // Allow user to drop colors into each palette entry. Note that ColorButton() is already a
+ // drag source by default, unless specifying the ImGuiColorEditFlags_NoDragDrop flag.
if (ImGui::BeginDragDropTarget())
{
if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F))
@@ -1292,14 +1679,16 @@ static void ShowDemoWindowWidgets()
}
ImGui::Text("Color button only:");
- ImGui::ColorButton("MyColor##3c", *(ImVec4*)&color, misc_flags, ImVec2(80,80));
+ static bool no_border = false;
+ ImGui::Checkbox("ImGuiColorEditFlags_NoBorder", &no_border);
+ ImGui::ColorButton("MyColor##3c", *(ImVec4*)&color, misc_flags | (no_border ? ImGuiColorEditFlags_NoBorder : 0), ImVec2(80, 80));
ImGui::Text("Color picker:");
static bool alpha = true;
static bool alpha_bar = true;
static bool side_preview = true;
static bool ref_color = false;
- static ImVec4 ref_color_v(1.0f,0.0f,1.0f,0.5f);
+ static ImVec4 ref_color_v(1.0f, 0.0f, 1.0f, 0.5f);
static int display_mode = 0;
static int picker_mode = 0;
ImGui::Checkbox("With Alpha", &alpha);
@@ -1316,7 +1705,10 @@ static void ShowDemoWindowWidgets()
}
}
ImGui::Combo("Display Mode", &display_mode, "Auto/Current\0None\0RGB Only\0HSV Only\0Hex Only\0");
- ImGui::SameLine(); HelpMarker("ColorEdit defaults to displaying RGB inputs if you don't specify a display mode, but the user can change it with a right-click.\n\nColorPicker defaults to displaying RGB+HSV+Hex if you don't specify a display mode.\n\nYou can change the defaults using SetColorEditOptions().");
+ ImGui::SameLine(); HelpMarker(
+ "ColorEdit defaults to displaying RGB inputs if you don't specify a display mode, "
+ "but the user can change it with a right-click.\n\nColorPicker defaults to displaying RGB+HSV+Hex "
+ "if you don't specify a display mode.\n\nYou can change the defaults using SetColorEditOptions().");
ImGui::Combo("Picker Mode", &picker_mode, "Auto/Current\0Hue bar + SV rect\0Hue wheel + SV triangle\0");
ImGui::SameLine(); HelpMarker("User can right-click the picker to change mode.");
ImGuiColorEditFlags flags = misc_flags;
@@ -1331,22 +1723,62 @@ static void ShowDemoWindowWidgets()
if (display_mode == 4) flags |= ImGuiColorEditFlags_DisplayHex;
ImGui::ColorPicker4("MyColor##4", (float*)&color, flags, ref_color ? &ref_color_v.x : NULL);
- ImGui::Text("Programmatically set defaults:");
- ImGui::SameLine(); HelpMarker("SetColorEditOptions() is designed to allow you to set boot-time default.\nWe don't have Push/Pop functions because you can force options on a per-widget basis if needed, and the user can change non-forced ones with the options menu.\nWe don't have a getter to avoid encouraging you to persistently save values that aren't forward-compatible.");
+ ImGui::Text("Set defaults in code:");
+ ImGui::SameLine(); HelpMarker(
+ "SetColorEditOptions() is designed to allow you to set boot-time default.\n"
+ "We don't have Push/Pop functions because you can force options on a per-widget basis if needed,"
+ "and the user can change non-forced ones with the options menu.\nWe don't have a getter to avoid"
+ "encouraging you to persistently save values that aren't forward-compatible.");
if (ImGui::Button("Default: Uint8 + HSV + Hue Bar"))
ImGui::SetColorEditOptions(ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_PickerHueBar);
if (ImGui::Button("Default: Float + HDR + Hue Wheel"))
ImGui::SetColorEditOptions(ImGuiColorEditFlags_Float | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_PickerHueWheel);
// HSV encoded support (to avoid RGB<>HSV round trips and singularities when S==0 or V==0)
- static ImVec4 color_stored_as_hsv(0.23f, 1.0f, 1.0f, 1.0f);
+ static ImVec4 color_hsv(0.23f, 1.0f, 1.0f, 1.0f); // Stored as HSV!
ImGui::Spacing();
ImGui::Text("HSV encoded colors");
- ImGui::SameLine(); HelpMarker("By default, colors are given to ColorEdit and ColorPicker in RGB, but ImGuiColorEditFlags_InputHSV allows you to store colors as HSV and pass them to ColorEdit and ColorPicker as HSV. This comes with the added benefit that you can manipulate hue values with the picker even when saturation or value are zero.");
+ ImGui::SameLine(); HelpMarker(
+ "By default, colors are given to ColorEdit and ColorPicker in RGB, but ImGuiColorEditFlags_InputHSV"
+ "allows you to store colors as HSV and pass them to ColorEdit and ColorPicker as HSV. This comes with the"
+ "added benefit that you can manipulate hue values with the picker even when saturation or value are zero.");
ImGui::Text("Color widget with InputHSV:");
- ImGui::ColorEdit4("HSV shown as RGB##1", (float*)&color_stored_as_hsv, ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float);
- ImGui::ColorEdit4("HSV shown as HSV##1", (float*)&color_stored_as_hsv, ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float);
- ImGui::DragFloat4("Raw HSV values", (float*)&color_stored_as_hsv, 0.01f, 0.0f, 1.0f);
+ ImGui::ColorEdit4("HSV shown as RGB##1", (float*)&color_hsv, ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float);
+ ImGui::ColorEdit4("HSV shown as HSV##1", (float*)&color_hsv, ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float);
+ ImGui::DragFloat4("Raw HSV values", (float*)&color_hsv, 0.01f, 0.0f, 1.0f);
+
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Drag/Slider Flags"))
+ {
+ // Demonstrate using advanced flags for DragXXX and SliderXXX functions. Note that the flags are the same!
+ static ImGuiSliderFlags flags = ImGuiSliderFlags_None;
+ ImGui::CheckboxFlags("ImGuiSliderFlags_AlwaysClamp", &flags, ImGuiSliderFlags_AlwaysClamp);
+ ImGui::SameLine(); HelpMarker("Always clamp value to min/max bounds (if any) when input manually with CTRL+Click.");
+ ImGui::CheckboxFlags("ImGuiSliderFlags_Logarithmic", &flags, ImGuiSliderFlags_Logarithmic);
+ ImGui::SameLine(); HelpMarker("Enable logarithmic editing (more precision for small values).");
+ ImGui::CheckboxFlags("ImGuiSliderFlags_NoRoundToFormat", &flags, ImGuiSliderFlags_NoRoundToFormat);
+ ImGui::SameLine(); HelpMarker("Disable rounding underlying value to match precision of the format string (e.g. %.3f values are rounded to those 3 digits).");
+ ImGui::CheckboxFlags("ImGuiSliderFlags_NoInput", &flags, ImGuiSliderFlags_NoInput);
+ ImGui::SameLine(); HelpMarker("Disable CTRL+Click or Enter key allowing to input text directly into the widget.");
+
+ // Drags
+ static float drag_f = 0.5f;
+ static int drag_i = 50;
+ ImGui::Text("Underlying float value: %f", drag_f);
+ ImGui::DragFloat("DragFloat (0 -> 1)", &drag_f, 0.005f, 0.0f, 1.0f, "%.3f", flags);
+ ImGui::DragFloat("DragFloat (0 -> +inf)", &drag_f, 0.005f, 0.0f, FLT_MAX, "%.3f", flags);
+ ImGui::DragFloat("DragFloat (-inf -> 1)", &drag_f, 0.005f, -FLT_MAX, 1.0f, "%.3f", flags);
+ ImGui::DragFloat("DragFloat (-inf -> +inf)", &drag_f, 0.005f, -FLT_MAX, +FLT_MAX, "%.3f", flags);
+ ImGui::DragInt("DragInt (0 -> 100)", &drag_i, 0.5f, 0, 100, "%d", flags);
+
+ // Sliders
+ static float slider_f = 0.5f;
+ static int slider_i = 50;
+ ImGui::Text("Underlying float value: %f", slider_f);
+ ImGui::SliderFloat("SliderFloat (0 -> 1)", &slider_f, 0.0f, 1.0f, "%.3f", flags);
+ ImGui::SliderInt("SliderInt (0 -> 100)", &slider_i, 0, 100, "%d", flags);
ImGui::TreePop();
}
@@ -1355,27 +1787,31 @@ static void ShowDemoWindowWidgets()
{
static float begin = 10, end = 90;
static int begin_i = 100, end_i = 1000;
- ImGui::DragFloatRange2("range", &begin, &end, 0.25f, 0.0f, 100.0f, "Min: %.1f %%", "Max: %.1f %%");
+ ImGui::DragFloatRange2("range float", &begin, &end, 0.25f, 0.0f, 100.0f, "Min: %.1f %%", "Max: %.1f %%", ImGuiSliderFlags_AlwaysClamp);
+ ImGui::DragIntRange2("range int", &begin_i, &end_i, 5, 0, 1000, "Min: %d units", "Max: %d units");
ImGui::DragIntRange2("range int (no bounds)", &begin_i, &end_i, 5, 0, 0, "Min: %d units", "Max: %d units");
ImGui::TreePop();
}
if (ImGui::TreeNode("Data Types"))
{
- // The DragScalar/InputScalar/SliderScalar functions allow various data types: signed/unsigned int/long long and float/double
- // To avoid polluting the public API with all possible combinations, we use the ImGuiDataType enum to pass the type,
- // and passing all arguments by address.
+ // DragScalar/InputScalar/SliderScalar functions allow various data types
+ // - signed/unsigned
+ // - 8/16/32/64-bits
+ // - integer/float/double
+ // To avoid polluting the public API with all possible combinations, we use the ImGuiDataType enum
+ // to pass the type, and passing all arguments by pointer.
// This is the reason the test code below creates local variables to hold "zero" "one" etc. for each types.
- // In practice, if you frequently use a given type that is not covered by the normal API entry points, you can wrap it
- // yourself inside a 1 line function which can take typed argument as value instead of void*, and then pass their address
- // to the generic function. For example:
+ // In practice, if you frequently use a given type that is not covered by the normal API entry points,
+ // you can wrap it yourself inside a 1 line function which can take typed argument as value instead of void*,
+ // and then pass their address to the generic function. For example:
// bool MySliderU64(const char *label, u64* value, u64 min = 0, u64 max = 0, const char* format = "%lld")
// {
// return SliderScalar(label, ImGuiDataType_U64, value, &min, &max, format);
// }
- // Limits (as helper variables that we can take the address of)
- // Note that the SliderScalar function has a maximum usable range of half the natural type maximum, hence the /2 below.
+ // Setup limits (as helper variables so we can take their address, as explained above)
+ // Note: SliderScalar() functions have a maximum usable range of half the natural type maximum, hence the /2.
#ifndef LLONG_MIN
ImS64 LLONG_MIN = -9223372036854775807LL - 1;
ImS64 LLONG_MAX = 9223372036854775807LL;
@@ -1407,7 +1843,10 @@ static void ShowDemoWindowWidgets()
const float drag_speed = 0.2f;
static bool drag_clamp = false;
ImGui::Text("Drags:");
- ImGui::Checkbox("Clamp integers to 0..50", &drag_clamp); ImGui::SameLine(); HelpMarker("As with every widgets in dear imgui, we never modify values unless there is a user interaction.\nYou can override the clamping limits by using CTRL+Click to input a value.");
+ ImGui::Checkbox("Clamp integers to 0..50", &drag_clamp);
+ ImGui::SameLine(); HelpMarker(
+ "As with every widgets in dear imgui, we never modify values unless there is a user interaction.\n"
+ "You can override the clamping limits by using CTRL+Click to input a value.");
ImGui::DragScalar("drag s8", ImGuiDataType_S8, &s8_v, drag_speed, drag_clamp ? &s8_zero : NULL, drag_clamp ? &s8_fifty : NULL);
ImGui::DragScalar("drag u8", ImGuiDataType_U8, &u8_v, drag_speed, drag_clamp ? &u8_zero : NULL, drag_clamp ? &u8_fifty : NULL, "%u ms");
ImGui::DragScalar("drag s16", ImGuiDataType_S16, &s16_v, drag_speed, drag_clamp ? &s16_zero : NULL, drag_clamp ? &s16_fifty : NULL);
@@ -1416,34 +1855,42 @@ static void ShowDemoWindowWidgets()
ImGui::DragScalar("drag u32", ImGuiDataType_U32, &u32_v, drag_speed, drag_clamp ? &u32_zero : NULL, drag_clamp ? &u32_fifty : NULL, "%u ms");
ImGui::DragScalar("drag s64", ImGuiDataType_S64, &s64_v, drag_speed, drag_clamp ? &s64_zero : NULL, drag_clamp ? &s64_fifty : NULL);
ImGui::DragScalar("drag u64", ImGuiDataType_U64, &u64_v, drag_speed, drag_clamp ? &u64_zero : NULL, drag_clamp ? &u64_fifty : NULL);
- ImGui::DragScalar("drag float", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f", 1.0f);
- ImGui::DragScalar("drag float ^2", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f", 2.0f); ImGui::SameLine(); HelpMarker("You can use the 'power' parameter to increase tweaking precision on one side of the range.");
- ImGui::DragScalar("drag double", ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, NULL, "%.10f grams", 1.0f);
- ImGui::DragScalar("drag double ^2", ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, &f64_one, "0 < %.10f < 1", 2.0f);
+ ImGui::DragScalar("drag float", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f");
+ ImGui::DragScalar("drag float log", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f", ImGuiSliderFlags_Logarithmic);
+ ImGui::DragScalar("drag double", ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, NULL, "%.10f grams");
+ ImGui::DragScalar("drag double log",ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, &f64_one, "0 < %.10f < 1", ImGuiSliderFlags_Logarithmic);
ImGui::Text("Sliders");
- ImGui::SliderScalar("slider s8 full", ImGuiDataType_S8, &s8_v, &s8_min, &s8_max, "%d");
- ImGui::SliderScalar("slider u8 full", ImGuiDataType_U8, &u8_v, &u8_min, &u8_max, "%u");
- ImGui::SliderScalar("slider s16 full", ImGuiDataType_S16, &s16_v, &s16_min, &s16_max, "%d");
- ImGui::SliderScalar("slider u16 full", ImGuiDataType_U16, &u16_v, &u16_min, &u16_max, "%u");
- ImGui::SliderScalar("slider s32 low", ImGuiDataType_S32, &s32_v, &s32_zero, &s32_fifty,"%d");
- ImGui::SliderScalar("slider s32 high", ImGuiDataType_S32, &s32_v, &s32_hi_a, &s32_hi_b, "%d");
- ImGui::SliderScalar("slider s32 full", ImGuiDataType_S32, &s32_v, &s32_min, &s32_max, "%d");
- ImGui::SliderScalar("slider u32 low", ImGuiDataType_U32, &u32_v, &u32_zero, &u32_fifty,"%u");
- ImGui::SliderScalar("slider u32 high", ImGuiDataType_U32, &u32_v, &u32_hi_a, &u32_hi_b, "%u");
- ImGui::SliderScalar("slider u32 full", ImGuiDataType_U32, &u32_v, &u32_min, &u32_max, "%u");
- ImGui::SliderScalar("slider s64 low", ImGuiDataType_S64, &s64_v, &s64_zero, &s64_fifty,"%I64d");
- ImGui::SliderScalar("slider s64 high", ImGuiDataType_S64, &s64_v, &s64_hi_a, &s64_hi_b, "%I64d");
- ImGui::SliderScalar("slider s64 full", ImGuiDataType_S64, &s64_v, &s64_min, &s64_max, "%I64d");
- ImGui::SliderScalar("slider u64 low", ImGuiDataType_U64, &u64_v, &u64_zero, &u64_fifty,"%I64u ms");
- ImGui::SliderScalar("slider u64 high", ImGuiDataType_U64, &u64_v, &u64_hi_a, &u64_hi_b, "%I64u ms");
- ImGui::SliderScalar("slider u64 full", ImGuiDataType_U64, &u64_v, &u64_min, &u64_max, "%I64u ms");
- ImGui::SliderScalar("slider float low", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one);
- ImGui::SliderScalar("slider float low^2", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one, "%.10f", 2.0f);
- ImGui::SliderScalar("slider float high", ImGuiDataType_Float, &f32_v, &f32_lo_a, &f32_hi_a, "%e");
- ImGui::SliderScalar("slider double low", ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f grams", 1.0f);
- ImGui::SliderScalar("slider double low^2",ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f", 2.0f);
- ImGui::SliderScalar("slider double high", ImGuiDataType_Double, &f64_v, &f64_lo_a, &f64_hi_a, "%e grams", 1.0f);
+ ImGui::SliderScalar("slider s8 full", ImGuiDataType_S8, &s8_v, &s8_min, &s8_max, "%d");
+ ImGui::SliderScalar("slider u8 full", ImGuiDataType_U8, &u8_v, &u8_min, &u8_max, "%u");
+ ImGui::SliderScalar("slider s16 full", ImGuiDataType_S16, &s16_v, &s16_min, &s16_max, "%d");
+ ImGui::SliderScalar("slider u16 full", ImGuiDataType_U16, &u16_v, &u16_min, &u16_max, "%u");
+ ImGui::SliderScalar("slider s32 low", ImGuiDataType_S32, &s32_v, &s32_zero, &s32_fifty,"%d");
+ ImGui::SliderScalar("slider s32 high", ImGuiDataType_S32, &s32_v, &s32_hi_a, &s32_hi_b, "%d");
+ ImGui::SliderScalar("slider s32 full", ImGuiDataType_S32, &s32_v, &s32_min, &s32_max, "%d");
+ ImGui::SliderScalar("slider u32 low", ImGuiDataType_U32, &u32_v, &u32_zero, &u32_fifty,"%u");
+ ImGui::SliderScalar("slider u32 high", ImGuiDataType_U32, &u32_v, &u32_hi_a, &u32_hi_b, "%u");
+ ImGui::SliderScalar("slider u32 full", ImGuiDataType_U32, &u32_v, &u32_min, &u32_max, "%u");
+ ImGui::SliderScalar("slider s64 low", ImGuiDataType_S64, &s64_v, &s64_zero, &s64_fifty,"%I64d");
+ ImGui::SliderScalar("slider s64 high", ImGuiDataType_S64, &s64_v, &s64_hi_a, &s64_hi_b, "%I64d");
+ ImGui::SliderScalar("slider s64 full", ImGuiDataType_S64, &s64_v, &s64_min, &s64_max, "%I64d");
+ ImGui::SliderScalar("slider u64 low", ImGuiDataType_U64, &u64_v, &u64_zero, &u64_fifty,"%I64u ms");
+ ImGui::SliderScalar("slider u64 high", ImGuiDataType_U64, &u64_v, &u64_hi_a, &u64_hi_b, "%I64u ms");
+ ImGui::SliderScalar("slider u64 full", ImGuiDataType_U64, &u64_v, &u64_min, &u64_max, "%I64u ms");
+ ImGui::SliderScalar("slider float low", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one);
+ ImGui::SliderScalar("slider float low log", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one, "%.10f", ImGuiSliderFlags_Logarithmic);
+ ImGui::SliderScalar("slider float high", ImGuiDataType_Float, &f32_v, &f32_lo_a, &f32_hi_a, "%e");
+ ImGui::SliderScalar("slider double low", ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f grams");
+ ImGui::SliderScalar("slider double low log",ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f", ImGuiSliderFlags_Logarithmic);
+ ImGui::SliderScalar("slider double high", ImGuiDataType_Double, &f64_v, &f64_lo_a, &f64_hi_a, "%e grams");
+
+ ImGui::Text("Sliders (reverse)");
+ ImGui::SliderScalar("slider s8 reverse", ImGuiDataType_S8, &s8_v, &s8_max, &s8_min, "%d");
+ ImGui::SliderScalar("slider u8 reverse", ImGuiDataType_U8, &u8_v, &u8_max, &u8_min, "%u");
+ ImGui::SliderScalar("slider s32 reverse", ImGuiDataType_S32, &s32_v, &s32_fifty, &s32_zero, "%d");
+ ImGui::SliderScalar("slider u32 reverse", ImGuiDataType_U32, &u32_v, &u32_fifty, &u32_zero, "%u");
+ ImGui::SliderScalar("slider s64 reverse", ImGuiDataType_S64, &s64_v, &s64_fifty, &s64_zero, "%I64d");
+ ImGui::SliderScalar("slider u64 reverse", ImGuiDataType_U64, &u64_v, &u64_fifty, &u64_zero, "%I64u ms");
static bool inputs_step = true;
ImGui::Text("Inputs");
@@ -1501,7 +1948,7 @@ static void ShowDemoWindowWidgets()
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(spacing, spacing));
static int int_value = 0;
- ImGui::VSliderInt("##int", ImVec2(18,160), &int_value, 0, 5);
+ ImGui::VSliderInt("##int", ImVec2(18, 160), &int_value, 0, 5);
ImGui::SameLine();
static float values[7] = { 0.0f, 0.60f, 0.35f, 0.9f, 0.70f, 0.20f, 0.0f };
@@ -1510,11 +1957,11 @@ static void ShowDemoWindowWidgets()
{
if (i > 0) ImGui::SameLine();
ImGui::PushID(i);
- ImGui::PushStyleColor(ImGuiCol_FrameBg, (ImVec4)ImColor::HSV(i/7.0f, 0.5f, 0.5f));
- ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, (ImVec4)ImColor::HSV(i/7.0f, 0.6f, 0.5f));
- ImGui::PushStyleColor(ImGuiCol_FrameBgActive, (ImVec4)ImColor::HSV(i/7.0f, 0.7f, 0.5f));
- ImGui::PushStyleColor(ImGuiCol_SliderGrab, (ImVec4)ImColor::HSV(i/7.0f, 0.9f, 0.9f));
- ImGui::VSliderFloat("##v", ImVec2(18,160), &values[i], 0.0f, 1.0f, "");
+ ImGui::PushStyleColor(ImGuiCol_FrameBg, (ImVec4)ImColor::HSV(i / 7.0f, 0.5f, 0.5f));
+ ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, (ImVec4)ImColor::HSV(i / 7.0f, 0.6f, 0.5f));
+ ImGui::PushStyleColor(ImGuiCol_FrameBgActive, (ImVec4)ImColor::HSV(i / 7.0f, 0.7f, 0.5f));
+ ImGui::PushStyleColor(ImGuiCol_SliderGrab, (ImVec4)ImColor::HSV(i / 7.0f, 0.9f, 0.9f));
+ ImGui::VSliderFloat("##v", ImVec2(18, 160), &values[i], 0.0f, 1.0f, "");
if (ImGui::IsItemActive() || ImGui::IsItemHovered())
ImGui::SetTooltip("%.3f", values[i]);
ImGui::PopStyleColor(4);
@@ -1533,7 +1980,7 @@ static void ShowDemoWindowWidgets()
ImGui::BeginGroup();
for (int ny = 0; ny < rows; ny++)
{
- ImGui::PushID(nx*rows+ny);
+ ImGui::PushID(nx * rows + ny);
ImGui::VSliderFloat("##v", small_slider_size, &values2[nx], 0.0f, 1.0f, "");
if (ImGui::IsItemActive() || ImGui::IsItemHovered())
ImGui::SetTooltip("%.3f", values2[nx]);
@@ -1550,7 +1997,7 @@ static void ShowDemoWindowWidgets()
if (i > 0) ImGui::SameLine();
ImGui::PushID(i);
ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize, 40);
- ImGui::VSliderFloat("##v", ImVec2(40,160), &values[i], 0.0f, 1.0f, "%.2f\nsec");
+ ImGui::VSliderFloat("##v", ImVec2(40, 160), &values[i], 0.0f, 1.0f, "%.2f\nsec");
ImGui::PopStyleVar();
ImGui::PopID();
}
@@ -1564,9 +2011,10 @@ static void ShowDemoWindowWidgets()
if (ImGui::TreeNode("Drag and drop in standard widgets"))
{
// ColorEdit widgets automatically act as drag source and drag target.
- // They are using standardized payload strings IMGUI_PAYLOAD_TYPE_COLOR_3F and IMGUI_PAYLOAD_TYPE_COLOR_4F to allow your own widgets
- // to use colors in their drag and drop interaction. Also see the demo in Color Picker -> Palette demo.
- HelpMarker("You can drag from the colored squares.");
+ // They are using standardized payload strings IMGUI_PAYLOAD_TYPE_COLOR_3F and IMGUI_PAYLOAD_TYPE_COLOR_4F
+ // to allow your own widgets to use colors in their drag and drop interaction.
+ // Also see 'Demo->Widgets->Color/Picker Widgets->Palette' demo.
+ HelpMarker("You can drag from the color squares.");
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);
@@ -1586,19 +2034,28 @@ static void ShowDemoWindowWidgets()
if (ImGui::RadioButton("Copy", mode == Mode_Copy)) { mode = Mode_Copy; } ImGui::SameLine();
if (ImGui::RadioButton("Move", mode == Mode_Move)) { mode = Mode_Move; } ImGui::SameLine();
if (ImGui::RadioButton("Swap", mode == Mode_Swap)) { mode = Mode_Swap; }
- static const char* names[9] = { "Bobby", "Beatrice", "Betty", "Brianna", "Barry", "Bernard", "Bibi", "Blaine", "Bryn" };
+ static const char* names[9] =
+ {
+ "Bobby", "Beatrice", "Betty",
+ "Brianna", "Barry", "Bernard",
+ "Bibi", "Blaine", "Bryn"
+ };
for (int n = 0; n < IM_ARRAYSIZE(names); n++)
{
ImGui::PushID(n);
if ((n % 3) != 0)
ImGui::SameLine();
- ImGui::Button(names[n], ImVec2(60,60));
+ ImGui::Button(names[n], ImVec2(60, 60));
// Our buttons are both drag sources and drag targets here!
if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None))
{
- ImGui::SetDragDropPayload("DND_DEMO_CELL", &n, sizeof(int)); // Set payload to carry the index of our item (could be anything)
- if (mode == Mode_Copy) { ImGui::Text("Copy %s", names[n]); } // Display preview (could be anything, e.g. when dragging an image we could decide to display the filename and a small preview of the image, etc.)
+ // Set payload to carry the index of our item (could be anything)
+ ImGui::SetDragDropPayload("DND_DEMO_CELL", &n, sizeof(int));
+
+ // Display preview (could be anything, e.g. when dragging an image we could decide to display
+ // the filename and a small preview of the image, etc.)
+ if (mode == Mode_Copy) { ImGui::Text("Copy %s", names[n]); }
if (mode == Mode_Move) { ImGui::Text("Move %s", names[n]); }
if (mode == Mode_Swap) { ImGui::Text("Swap %s", names[n]); }
ImGui::EndDragDropSource();
@@ -1635,7 +2092,9 @@ static void ShowDemoWindowWidgets()
if (ImGui::TreeNode("Drag to reorder items (simple)"))
{
// Simple reordering
- HelpMarker("We don't use the drag and drop api at all here! Instead we query when the item is held but not hovered, and order items accordingly.");
+ HelpMarker(
+ "We don't use the drag and drop api at all here! "
+ "Instead we query when the item is held but not hovered, and order items accordingly.");
static const char* item_names[] = { "Item One", "Item Two", "Item Three", "Item Four", "Item Five" };
for (int n = 0; n < IM_ARRAYSIZE(item_names); n++)
{
@@ -1659,13 +2118,20 @@ static void ShowDemoWindowWidgets()
ImGui::TreePop();
}
- if (ImGui::TreeNode("Querying Status (Active/Focused/Hovered etc.)"))
+ if (ImGui::TreeNode("Querying Status (Edited/Active/Focused/Hovered etc.)"))
{
- // Submit an item (various types available) so we can query their status in the following block.
+ // Select an item type
+ const char* item_names[] =
+ {
+ "Text", "Button", "Button (w/ repeat)", "Checkbox", "SliderFloat", "InputText", "InputFloat",
+ "InputFloat3", "ColorEdit4", "MenuItem", "TreeNode", "TreeNode (w/ double-click)", "Combo", "ListBox"
+ };
static int item_type = 1;
- ImGui::Combo("Item Type", &item_type, "Text\0Button\0Button (w/ repeat)\0Checkbox\0SliderFloat\0InputText\0InputFloat\0InputFloat3\0ColorEdit4\0MenuItem\0TreeNode (w/ double-click)\0ListBox\0");
+ ImGui::Combo("Item Type", &item_type, item_names, IM_ARRAYSIZE(item_names), IM_ARRAYSIZE(item_names));
ImGui::SameLine();
- HelpMarker("Testing how various types of items are interacting with the IsItemXXX functions.");
+ HelpMarker("Testing how various types of items are interacting with the IsItemXXX functions. Note that the bool return value of most ImGui function is generally equivalent to calling ImGui::IsItemHovered().");
+
+ // Submit selected item item so we can query their status in the code following it.
bool ret = false;
static bool b = false;
static float col4f[4] = { 1.0f, 0.5, 0.0f, 1.0f };
@@ -1680,13 +2146,15 @@ static void ShowDemoWindowWidgets()
if (item_type == 7) { ret = ImGui::InputFloat3("ITEM: InputFloat3", col4f); } // Testing multi-component items (IsItemXXX flags are reported merged)
if (item_type == 8) { ret = ImGui::ColorEdit4("ITEM: ColorEdit4", col4f); } // Testing multi-component items (IsItemXXX flags are reported merged)
if (item_type == 9) { ret = ImGui::MenuItem("ITEM: MenuItem"); } // Testing menu item (they use ImGuiButtonFlags_PressedOnRelease button policy)
- if (item_type == 10){ ret = ImGui::TreeNodeEx("ITEM: TreeNode w/ ImGuiTreeNodeFlags_OpenOnDoubleClick", ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_NoTreePushOnOpen); } // Testing tree node with ImGuiButtonFlags_PressedOnDoubleClick button policy.
- if (item_type == 11){ const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi" }; static int current = 1; ret = ImGui::ListBox("ITEM: ListBox", ¤t, items, IM_ARRAYSIZE(items), IM_ARRAYSIZE(items)); }
+ if (item_type == 10){ ret = ImGui::TreeNode("ITEM: TreeNode"); if (ret) ImGui::TreePop(); } // Testing tree node
+ if (item_type == 11){ ret = ImGui::TreeNodeEx("ITEM: TreeNode w/ ImGuiTreeNodeFlags_OpenOnDoubleClick", ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_NoTreePushOnOpen); } // Testing tree node with ImGuiButtonFlags_PressedOnDoubleClick button policy.
+ if (item_type == 12){ const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi" }; static int current = 1; ret = ImGui::Combo("ITEM: Combo", ¤t, items, IM_ARRAYSIZE(items)); }
+ if (item_type == 13){ const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi" }; static int current = 1; ret = ImGui::ListBox("ITEM: ListBox", ¤t, items, IM_ARRAYSIZE(items), IM_ARRAYSIZE(items)); }
- // Display the value of IsItemHovered() and other common item state functions.
+ // Display the values of IsItemHovered() and other common item state functions.
// Note that the ImGuiHoveredFlags_XXX flags can be combined.
// Because BulletText is an item itself and that would affect the output of IsItemXXX functions,
- // we query every state in a single call to avoid storing them and to simplify the code
+ // we query every state in a single call to avoid storing them and to simplify the code.
ImGui::BulletText(
"Return value = %d\n"
"IsItemFocused() = %d\n"
@@ -1702,6 +2170,7 @@ static void ShowDemoWindowWidgets()
"IsItemDeactivatedAfterEdit() = %d\n"
"IsItemVisible() = %d\n"
"IsItemClicked() = %d\n"
+ "IsItemToggledOpen() = %d\n"
"GetItemRectMin() = (%.1f, %.1f)\n"
"GetItemRectMax() = (%.1f, %.1f)\n"
"GetItemRectSize() = (%.1f, %.1f)",
@@ -1719,6 +2188,7 @@ static void ShowDemoWindowWidgets()
ImGui::IsItemDeactivatedAfterEdit(),
ImGui::IsItemVisible(),
ImGui::IsItemClicked(),
+ ImGui::IsItemToggledOpen(),
ImGui::GetItemRectMin().x, ImGui::GetItemRectMin().y,
ImGui::GetItemRectMax().x, ImGui::GetItemRectMax().y,
ImGui::GetItemRectSize().x, ImGui::GetItemRectSize().y
@@ -1727,7 +2197,7 @@ static void ShowDemoWindowWidgets()
static bool embed_all_inside_a_child_window = false;
ImGui::Checkbox("Embed everything inside a child window (for additional testing)", &embed_all_inside_a_child_window);
if (embed_all_inside_a_child_window)
- ImGui::BeginChild("outer_child", ImVec2(0, ImGui::GetFontSize() * 20), true);
+ ImGui::BeginChild("outer_child", ImVec2(0, ImGui::GetFontSize() * 20.0f), true);
// Testing IsWindowFocused() function with its various flags.
// Note that the ImGuiFocusedFlags_XXX flags can be combined.
@@ -1769,18 +2239,15 @@ static void ShowDemoWindowWidgets()
if (embed_all_inside_a_child_window)
ImGui::EndChild();
- static char dummy_str[] = "This is a dummy field to be able to tab-out of the widgets above.";
- ImGui::InputText("dummy", dummy_str, IM_ARRAYSIZE(dummy_str), ImGuiInputTextFlags_ReadOnly);
+ static char unused_str[] = "This widget is only here to be able to tab-out of the widgets above.";
+ ImGui::InputText("unused", unused_str, IM_ARRAYSIZE(unused_str), ImGuiInputTextFlags_ReadOnly);
// Calling IsItemHovered() after begin returns the hovered status of the title bar.
- // This is useful in particular if you want to create a context menu (with BeginPopupContextItem) associated to the title bar of a window.
- // This will also work when docked into a Tab (the Tab replace the Title Bar and guarantee the same properties).
+ // This is useful in particular if you want to create a context menu associated to the title bar of a window.
static bool test_window = false;
ImGui::Checkbox("Hovered/Active tests after Begin() for title bar testing", &test_window);
if (test_window)
{
- // FIXME-DOCK: This window cannot be docked within the ImGui Demo window, this will cause a feedback loop and get them stuck.
- // Could we fix this through an ImGuiWindowClass feature? Or an API call to tag our parent as "don't skip items"?
ImGui::Begin("Title bar Hovered/Active tests", &test_window);
if (ImGui::BeginPopupContextItem()) // <-- This is using IsItemHovered()
{
@@ -1800,7 +2267,7 @@ static void ShowDemoWindowWidgets()
static void ShowDemoWindowLayout()
{
- if (!ImGui::CollapsingHeader("Layout"))
+ if (!ImGui::CollapsingHeader("Layout & Scrolling"))
return;
if (ImGui::TreeNode("Child windows"))
@@ -1811,24 +2278,14 @@ static void ShowDemoWindowLayout()
ImGui::Checkbox("Disable Mouse Wheel", &disable_mouse_wheel);
ImGui::Checkbox("Disable Menu", &disable_menu);
- static int line = 50;
- bool goto_line = ImGui::Button("Goto");
- ImGui::SameLine();
- ImGui::SetNextItemWidth(100);
- goto_line |= ImGui::InputInt("##Line", &line, 0, 0, ImGuiInputTextFlags_EnterReturnsTrue);
-
// Child 1: no border, enable horizontal scrollbar
{
- ImGuiWindowFlags window_flags = ImGuiWindowFlags_HorizontalScrollbar | (disable_mouse_wheel ? ImGuiWindowFlags_NoScrollWithMouse : 0);
- ImGui::BeginChild("Child1", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.5f, 260), false, window_flags);
+ ImGuiWindowFlags window_flags = ImGuiWindowFlags_HorizontalScrollbar;
+ if (disable_mouse_wheel)
+ window_flags |= ImGuiWindowFlags_NoScrollWithMouse;
+ ImGui::BeginChild("ChildL", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.5f, 260), false, window_flags);
for (int i = 0; i < 100; i++)
- {
ImGui::Text("%04d: scrollable region", i);
- if (goto_line && line == i)
- ImGui::SetScrollHereY();
- }
- if (goto_line && line >= 100)
- ImGui::SetScrollHereY();
ImGui::EndChild();
}
@@ -1836,9 +2293,13 @@ static void ShowDemoWindowLayout()
// Child 2: rounded border
{
- ImGuiWindowFlags window_flags = (disable_mouse_wheel ? ImGuiWindowFlags_NoScrollWithMouse : 0) | (disable_menu ? 0 : ImGuiWindowFlags_MenuBar);
+ ImGuiWindowFlags window_flags = ImGuiWindowFlags_None;
+ if (disable_mouse_wheel)
+ window_flags |= ImGuiWindowFlags_NoScrollWithMouse;
+ if (!disable_menu)
+ window_flags |= ImGuiWindowFlags_MenuBar;
ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f);
- ImGui::BeginChild("Child2", ImVec2(0, 260), true, window_flags);
+ ImGui::BeginChild("ChildR", ImVec2(0, 260), true, window_flags);
if (!disable_menu && ImGui::BeginMenuBar())
{
if (ImGui::BeginMenu("Menu"))
@@ -1848,13 +2309,16 @@ static void ShowDemoWindowLayout()
}
ImGui::EndMenuBar();
}
- ImGui::Columns(2);
- for (int i = 0; i < 100; i++)
+ if (ImGui::BeginTable("split", 2, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings))
{
- char buf[32];
- sprintf(buf, "%03d", i);
- ImGui::Button(buf, ImVec2(-FLT_MIN, 0.0f));
- ImGui::NextColumn();
+ for (int i = 0; i < 100; i++)
+ {
+ char buf[32];
+ sprintf(buf, "%03d", i);
+ ImGui::TableNextColumn();
+ ImGui::Button(buf, ImVec2(-FLT_MIN, 0.0f));
+ }
+ ImGui::EndTable();
}
ImGui::EndChild();
ImGui::PopStyleVar();
@@ -1864,20 +2328,27 @@ static void ShowDemoWindowLayout()
// Demonstrate a few extra things
// - Changing ImGuiCol_ChildBg (which is transparent black in default styles)
- // - Using SetCursorPos() to position the child window (because the child window is an item from the POV of the parent window)
- // You can also call SetNextWindowPos() to position the child window. The parent window will effectively layout from this position.
- // - Using ImGui::GetItemRectMin/Max() to query the "item" state (because the child window is an item from the POV of the parent window)
- // See "Widgets" -> "Querying Status (Active/Focused/Hovered etc.)" section for more details about this.
+ // - Using SetCursorPos() to position child window (the child window is an item from the POV of parent window)
+ // You can also call SetNextWindowPos() to position the child window. The parent window will effectively
+ // layout from this position.
+ // - Using ImGui::GetItemRectMin/Max() to query the "item" state (because the child window is an item from
+ // the POV of the parent window). See 'Demo->Querying Status (Active/Focused/Hovered etc.)' for details.
{
- ImGui::SetCursorPosX(ImGui::GetCursorPosX() + 10);
+ static int offset_x = 0;
+ ImGui::SetNextItemWidth(100);
+ ImGui::DragInt("Offset X", &offset_x, 1.0f, -1000, 1000);
+
+ ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (float)offset_x);
ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(255, 0, 0, 100));
- ImGui::BeginChild("blah", ImVec2(200, 100), true, ImGuiWindowFlags_None);
+ ImGui::BeginChild("Red", ImVec2(200, 100), true, ImGuiWindowFlags_None);
for (int n = 0; n < 50; n++)
ImGui::Text("Some test %d", n);
ImGui::EndChild();
+ bool child_is_hovered = ImGui::IsItemHovered();
ImVec2 child_rect_min = ImGui::GetItemRectMin();
ImVec2 child_rect_max = ImGui::GetItemRectMax();
ImGui::PopStyleColor();
+ ImGui::Text("Hovered: %d", child_is_hovered);
ImGui::Text("Rect of child window is: (%.0f,%.0f) (%.0f,%.0f)", child_rect_min.x, child_rect_min.y, child_rect_max.x, child_rect_max.y);
}
@@ -1888,34 +2359,73 @@ static void ShowDemoWindowLayout()
{
// Use SetNextItemWidth() to set the width of a single upcoming item.
// Use PushItemWidth()/PopItemWidth() to set the width of a group of items.
+ // In real code use you'll probably want to choose width values that are proportional to your font size
+ // e.g. Using '20.0f * GetFontSize()' as width instead of '200.0f', etc.
+
static float f = 0.0f;
+ static bool show_indented_items = true;
+ ImGui::Checkbox("Show indented items", &show_indented_items);
+
ImGui::Text("SetNextItemWidth/PushItemWidth(100)");
ImGui::SameLine(); HelpMarker("Fixed width.");
- ImGui::SetNextItemWidth(100);
- ImGui::DragFloat("float##1", &f);
-
- ImGui::Text("SetNextItemWidth/PushItemWidth(GetWindowWidth() * 0.5f)");
- ImGui::SameLine(); HelpMarker("Half of window width.");
- ImGui::SetNextItemWidth(ImGui::GetWindowWidth() * 0.5f);
- ImGui::DragFloat("float##2", &f);
-
- ImGui::Text("SetNextItemWidth/PushItemWidth(GetContentRegionAvail().x * 0.5f)");
- ImGui::SameLine(); HelpMarker("Half of available width.\n(~ right-cursor_pos)\n(works within a column set)");
- ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x * 0.5f);
- ImGui::DragFloat("float##3", &f);
+ ImGui::PushItemWidth(100);
+ ImGui::DragFloat("float##1b", &f);
+ if (show_indented_items)
+ {
+ ImGui::Indent();
+ ImGui::DragFloat("float (indented)##1b", &f);
+ ImGui::Unindent();
+ }
+ ImGui::PopItemWidth();
ImGui::Text("SetNextItemWidth/PushItemWidth(-100)");
ImGui::SameLine(); HelpMarker("Align to right edge minus 100");
- ImGui::SetNextItemWidth(-100);
- ImGui::DragFloat("float##4", &f);
+ ImGui::PushItemWidth(-100);
+ ImGui::DragFloat("float##2a", &f);
+ if (show_indented_items)
+ {
+ ImGui::Indent();
+ ImGui::DragFloat("float (indented)##2b", &f);
+ ImGui::Unindent();
+ }
+ ImGui::PopItemWidth();
- // Demonstrate using PushItemWidth to surround three items. Calling SetNextItemWidth() before each of them would have the same effect.
- ImGui::Text("SetNextItemWidth/PushItemWidth(-1)");
+ ImGui::Text("SetNextItemWidth/PushItemWidth(GetContentRegionAvail().x * 0.5f)");
+ ImGui::SameLine(); HelpMarker("Half of available width.\n(~ right-cursor_pos)\n(works within a column set)");
+ ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x * 0.5f);
+ ImGui::DragFloat("float##3a", &f);
+ if (show_indented_items)
+ {
+ ImGui::Indent();
+ ImGui::DragFloat("float (indented)##3b", &f);
+ ImGui::Unindent();
+ }
+ ImGui::PopItemWidth();
+
+ ImGui::Text("SetNextItemWidth/PushItemWidth(-GetContentRegionAvail().x * 0.5f)");
+ ImGui::SameLine(); HelpMarker("Align to right edge minus half");
+ ImGui::PushItemWidth(-ImGui::GetContentRegionAvail().x * 0.5f);
+ ImGui::DragFloat("float##4a", &f);
+ if (show_indented_items)
+ {
+ ImGui::Indent();
+ ImGui::DragFloat("float (indented)##4b", &f);
+ ImGui::Unindent();
+ }
+ ImGui::PopItemWidth();
+
+ // Demonstrate using PushItemWidth to surround three items.
+ // Calling SetNextItemWidth() before each of them would have the same effect.
+ ImGui::Text("SetNextItemWidth/PushItemWidth(-FLT_MIN)");
ImGui::SameLine(); HelpMarker("Align to right edge");
- ImGui::PushItemWidth(-1);
+ ImGui::PushItemWidth(-FLT_MIN);
ImGui::DragFloat("##float5a", &f);
- ImGui::DragFloat("##float5b", &f);
- ImGui::DragFloat("##float5c", &f);
+ if (show_indented_items)
+ {
+ ImGui::Indent();
+ ImGui::DragFloat("float (indented)##5b", &f);
+ ImGui::Unindent();
+ }
ImGui::PopItemWidth();
ImGui::TreePop();
@@ -1990,7 +2500,8 @@ static void ShowDemoWindowLayout()
ImGui::Dummy(button_sz); ImGui::SameLine();
ImGui::Button("B", button_sz);
- // Manually wrapping (we should eventually provide this as an automatic layout feature, but for now you can do it manually)
+ // Manually wrapping
+ // (we should eventually provide this as an automatic layout feature, but for now you can do it manually)
ImGui::Text("Manually wrapping:");
ImGuiStyle& style = ImGui::GetStyle();
int buttons_count = 20;
@@ -2009,80 +2520,12 @@ static void ShowDemoWindowLayout()
ImGui::TreePop();
}
- if (ImGui::TreeNode("Tabs"))
- {
- if (ImGui::TreeNode("Basic"))
- {
- ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_None;
- if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags))
- {
- if (ImGui::BeginTabItem("Avocado"))
- {
- ImGui::Text("This is the Avocado tab!\nblah blah blah blah blah");
- ImGui::EndTabItem();
- }
- if (ImGui::BeginTabItem("Broccoli"))
- {
- ImGui::Text("This is the Broccoli tab!\nblah blah blah blah blah");
- ImGui::EndTabItem();
- }
- if (ImGui::BeginTabItem("Cucumber"))
- {
- ImGui::Text("This is the Cucumber tab!\nblah blah blah blah blah");
- ImGui::EndTabItem();
- }
- ImGui::EndTabBar();
- }
- ImGui::Separator();
- ImGui::TreePop();
- }
-
- if (ImGui::TreeNode("Advanced & Close Button"))
- {
- // Expose a couple of the available flags. In most cases you may just call BeginTabBar() with no flags (0).
- static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable;
- ImGui::CheckboxFlags("ImGuiTabBarFlags_Reorderable", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_Reorderable);
- ImGui::CheckboxFlags("ImGuiTabBarFlags_AutoSelectNewTabs", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_AutoSelectNewTabs);
- ImGui::CheckboxFlags("ImGuiTabBarFlags_TabListPopupButton", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton);
- ImGui::CheckboxFlags("ImGuiTabBarFlags_NoCloseWithMiddleMouseButton", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_NoCloseWithMiddleMouseButton);
- if ((tab_bar_flags & ImGuiTabBarFlags_FittingPolicyMask_) == 0)
- tab_bar_flags |= ImGuiTabBarFlags_FittingPolicyDefault_;
- if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyResizeDown", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_FittingPolicyResizeDown))
- tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyResizeDown);
- if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyScroll", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_FittingPolicyScroll))
- tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyScroll);
-
- // Tab Bar
- const char* names[4] = { "Artichoke", "Beetroot", "Celery", "Daikon" };
- static bool opened[4] = { true, true, true, true }; // Persistent user state
- for (int n = 0; n < IM_ARRAYSIZE(opened); n++)
- {
- if (n > 0) { ImGui::SameLine(); }
- ImGui::Checkbox(names[n], &opened[n]);
- }
-
- // Passing a bool* to BeginTabItem() is similar to passing one to Begin(): the underlying bool will be set to false when the tab is closed.
- if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags))
- {
- for (int n = 0; n < IM_ARRAYSIZE(opened); n++)
- if (opened[n] && ImGui::BeginTabItem(names[n], &opened[n]))
- {
- ImGui::Text("This is the %s tab!", names[n]);
- if (n & 1)
- ImGui::Text("I am an odd tab.");
- ImGui::EndTabItem();
- }
- ImGui::EndTabBar();
- }
- ImGui::Separator();
- ImGui::TreePop();
- }
- ImGui::TreePop();
- }
-
if (ImGui::TreeNode("Groups"))
{
- HelpMarker("BeginGroup() basically locks the horizontal position for new line. EndGroup() bundles the whole group so that you can use \"item\" functions such as IsItemHovered()/IsItemActive() or SameLine() etc. on the whole group.");
+ HelpMarker(
+ "BeginGroup() basically locks the horizontal position for new line. "
+ "EndGroup() bundles the whole group so that you can use \"item\" functions such as "
+ "IsItemHovered()/IsItemActive() or SameLine() etc. on the whole group.");
ImGui::BeginGroup();
{
ImGui::BeginGroup();
@@ -2105,9 +2548,9 @@ static void ShowDemoWindowLayout()
const float values[5] = { 0.5f, 0.20f, 0.80f, 0.60f, 0.25f };
ImGui::PlotHistogram("##values", values, IM_ARRAYSIZE(values), 0, NULL, 0.0f, 1.0f, size);
- ImGui::Button("ACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x)*0.5f, size.y));
+ ImGui::Button("ACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x) * 0.5f, size.y));
ImGui::SameLine();
- ImGui::Button("REACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x)*0.5f, size.y));
+ ImGui::Button("REACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x) * 0.5f, size.y));
ImGui::EndGroup();
ImGui::SameLine();
@@ -2128,8 +2571,9 @@ static void ShowDemoWindowLayout()
{
{
ImGui::BulletText("Text baseline:");
- ImGui::SameLine();
- HelpMarker("This is testing the vertical alignment that gets applied on text to keep it aligned with widgets. Lines only composed of text or \"small\" widgets fit in less vertical spaces than lines with normal widgets.");
+ ImGui::SameLine(); HelpMarker(
+ "This is testing the vertical alignment that gets applied on text to keep it aligned with widgets. "
+ "Lines only composed of text or \"small\" widgets use less vertical space than lines with framed widgets.");
ImGui::Indent();
ImGui::Text("KO Blahblah"); ImGui::SameLine();
@@ -2137,7 +2581,8 @@ static void ShowDemoWindowLayout()
HelpMarker("Baseline of button will look misaligned with text..");
// If your line starts with text, call AlignTextToFramePadding() to align text to upcoming widgets.
- // Because we don't know what's coming after the Text() statement, we need to move the text baseline down by FramePadding.y
+ // (because we don't know what's coming after the Text() statement, we need to move the text baseline
+ // down by FramePadding.y ahead of time)
ImGui::AlignTextToFramePadding();
ImGui::Text("OK Blahblah"); ImGui::SameLine();
ImGui::Button("Some framed item"); ImGui::SameLine();
@@ -2189,7 +2634,7 @@ static void ShowDemoWindowLayout()
ImGui::BulletText("Misc items:");
ImGui::Indent();
- // SmallButton() sets FramePadding to zero. Text baseline is aligned to match baseline of previous Button
+ // SmallButton() sets FramePadding to zero. Text baseline is aligned to match baseline of previous Button.
ImGui::Button("80x80", ImVec2(80, 80));
ImGui::SameLine();
ImGui::Button("50x50", ImVec2(50, 50));
@@ -2202,12 +2647,29 @@ static void ShowDemoWindowLayout()
const float spacing = ImGui::GetStyle().ItemInnerSpacing.x;
ImGui::Button("Button##1");
ImGui::SameLine(0.0f, spacing);
- if (ImGui::TreeNode("Node##1")) { for (int i = 0; i < 6; i++) ImGui::BulletText("Item %d..", i); ImGui::TreePop(); } // Dummy tree data
+ if (ImGui::TreeNode("Node##1"))
+ {
+ // Placeholder tree data
+ for (int i = 0; i < 6; i++)
+ ImGui::BulletText("Item %d..", i);
+ ImGui::TreePop();
+ }
- ImGui::AlignTextToFramePadding(); // Vertically align text node a bit lower so it'll be vertically centered with upcoming widget. Otherwise you can use SmallButton (smaller fit).
- bool node_open = ImGui::TreeNode("Node##2");// Common mistake to avoid: if we want to SameLine after TreeNode we need to do it before we add child content.
+ // Vertically align text node a bit lower so it'll be vertically centered with upcoming widget.
+ // Otherwise you can use SmallButton() (smaller fit).
+ ImGui::AlignTextToFramePadding();
+
+ // Common mistake to avoid: if we want to SameLine after TreeNode we need to do it before we add
+ // other contents below the node.
+ bool node_open = ImGui::TreeNode("Node##2");
ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##2");
- if (node_open) { for (int i = 0; i < 6; i++) ImGui::BulletText("Item %d..", i); ImGui::TreePop(); } // Dummy tree data
+ if (node_open)
+ {
+ // Placeholder tree data
+ for (int i = 0; i < 6; i++)
+ ImGui::BulletText("Item %d..", i);
+ ImGui::TreePop();
+ }
// Bullet
ImGui::Button("Button##3");
@@ -2235,18 +2697,16 @@ static void ShowDemoWindowLayout()
static float scroll_to_pos_px = 200.0f;
ImGui::Checkbox("Decoration", &enable_extra_decorations);
- ImGui::SameLine();
- HelpMarker("We expose this for testing because scrolling sometimes had issues with window decoration such as menu-bars.");
ImGui::Checkbox("Track", &enable_track);
ImGui::PushItemWidth(100);
ImGui::SameLine(140); enable_track |= ImGui::DragInt("##item", &track_item, 0.25f, 0, 99, "Item = %d");
bool scroll_to_off = ImGui::Button("Scroll Offset");
- ImGui::SameLine(140); scroll_to_off |= ImGui::DragFloat("##off", &scroll_to_off_px, 1.00f, 0, 9999, "+%.0f px");
+ ImGui::SameLine(140); scroll_to_off |= ImGui::DragFloat("##off", &scroll_to_off_px, 1.00f, 0, FLT_MAX, "+%.0f px");
bool scroll_to_pos = ImGui::Button("Scroll To Pos");
- ImGui::SameLine(140); scroll_to_pos |= ImGui::DragFloat("##pos", &scroll_to_pos_px, 1.00f, -10, 9999, "X/Y = %.0f px");
+ ImGui::SameLine(140); scroll_to_pos |= ImGui::DragFloat("##pos", &scroll_to_pos_px, 1.00f, -10, FLT_MAX, "X/Y = %.0f px");
ImGui::PopItemWidth();
if (scroll_to_off || scroll_to_pos)
@@ -2264,8 +2724,9 @@ static void ShowDemoWindowLayout()
const char* names[] = { "Top", "25%", "Center", "75%", "Bottom" };
ImGui::TextUnformatted(names[i]);
- ImGuiWindowFlags child_flags = enable_extra_decorations ? ImGuiWindowFlags_MenuBar : 0;
- ImGui::BeginChild(ImGui::GetID((void*)(intptr_t)i), ImVec2(child_w, 200.0f), true, child_flags);
+ const ImGuiWindowFlags child_flags = enable_extra_decorations ? ImGuiWindowFlags_MenuBar : 0;
+ const ImGuiID child_id = ImGui::GetID((void*)(intptr_t)i);
+ const bool child_is_visible = ImGui::BeginChild(child_id, ImVec2(child_w, 200.0f), true, child_flags);
if (ImGui::BeginMenuBar())
{
ImGui::TextUnformatted("abc");
@@ -2275,16 +2736,19 @@ static void ShowDemoWindowLayout()
ImGui::SetScrollY(scroll_to_off_px);
if (scroll_to_pos)
ImGui::SetScrollFromPosY(ImGui::GetCursorStartPos().y + scroll_to_pos_px, i * 0.25f);
- for (int item = 0; item < 100; item++)
+ if (child_is_visible) // Avoid calling SetScrollHereY when running with culled items
{
- if (enable_track && item == track_item)
+ for (int item = 0; item < 100; item++)
{
- ImGui::TextColored(ImVec4(1,1,0,1), "Item %d", item);
- ImGui::SetScrollHereY(i * 0.25f); // 0.0f:top, 0.5f:center, 1.0f:bottom
- }
- else
- {
- ImGui::Text("Item %d", item);
+ if (enable_track && item == track_item)
+ {
+ ImGui::TextColored(ImVec4(1, 1, 0, 1), "Item %d", item);
+ ImGui::SetScrollHereY(i * 0.25f); // 0.0f:top, 0.5f:center, 1.0f:bottom
+ }
+ else
+ {
+ ImGui::Text("Item %d", item);
+ }
}
}
float scroll_y = ImGui::GetScrollY();
@@ -2297,29 +2761,37 @@ static void ShowDemoWindowLayout()
// Horizontal scroll functions
ImGui::Spacing();
- HelpMarker("Use SetScrollHereX() or SetScrollFromPosX() to scroll to a given horizontal position.\n\nUsing the \"Scroll To Pos\" button above will make the discontinuity at edges visible: scrolling to the top/bottom/left/right-most item will add an additional WindowPadding to reflect on reaching the edge of the list.\n\nBecause the clipping rectangle of most window hides half worth of WindowPadding on the left/right, using SetScrollFromPosX(+1) will usually result in clipped text whereas the equivalent SetScrollFromPosY(+1) wouldn't.");
+ HelpMarker(
+ "Use SetScrollHereX() or SetScrollFromPosX() to scroll to a given horizontal position.\n\n"
+ "Because the clipping rectangle of most window hides half worth of WindowPadding on the "
+ "left/right, using SetScrollFromPosX(+1) will usually result in clipped text whereas the "
+ "equivalent SetScrollFromPosY(+1) wouldn't.");
ImGui::PushID("##HorizontalScrolling");
for (int i = 0; i < 5; i++)
{
float child_height = ImGui::GetTextLineHeight() + style.ScrollbarSize + style.WindowPadding.y * 2.0f;
ImGuiWindowFlags child_flags = ImGuiWindowFlags_HorizontalScrollbar | (enable_extra_decorations ? ImGuiWindowFlags_AlwaysVerticalScrollbar : 0);
- ImGui::BeginChild(ImGui::GetID((void*)(intptr_t)i), ImVec2(-100, child_height), true, child_flags);
+ ImGuiID child_id = ImGui::GetID((void*)(intptr_t)i);
+ bool child_is_visible = ImGui::BeginChild(child_id, ImVec2(-100, child_height), true, child_flags);
if (scroll_to_off)
ImGui::SetScrollX(scroll_to_off_px);
if (scroll_to_pos)
ImGui::SetScrollFromPosX(ImGui::GetCursorStartPos().x + scroll_to_pos_px, i * 0.25f);
- for (int item = 0; item < 100; item++)
+ if (child_is_visible) // Avoid calling SetScrollHereY when running with culled items
{
- if (enable_track && item == track_item)
+ for (int item = 0; item < 100; item++)
{
- ImGui::TextColored(ImVec4(1, 1, 0, 1), "Item %d", item);
- ImGui::SetScrollHereX(i * 0.25f); // 0.0f:left, 0.5f:center, 1.0f:right
+ if (enable_track && item == track_item)
+ {
+ ImGui::TextColored(ImVec4(1, 1, 0, 1), "Item %d", item);
+ ImGui::SetScrollHereX(i * 0.25f); // 0.0f:left, 0.5f:center, 1.0f:right
+ }
+ else
+ {
+ ImGui::Text("Item %d", item);
+ }
+ ImGui::SameLine();
}
- else
- {
- ImGui::Text("Item %d", item);
- }
- ImGui::SameLine();
}
float scroll_x = ImGui::GetScrollX();
float scroll_max_x = ImGui::GetScrollMaxX();
@@ -2332,16 +2804,21 @@ static void ShowDemoWindowLayout()
ImGui::PopID();
// Miscellaneous Horizontal Scrolling Demo
- HelpMarker("Horizontal scrolling for a window has to be enabled explicitly via the ImGuiWindowFlags_HorizontalScrollbar flag.\n\nYou may want to explicitly specify content width by calling SetNextWindowContentWidth() before Begin().");
+ HelpMarker(
+ "Horizontal scrolling for a window is enabled via the ImGuiWindowFlags_HorizontalScrollbar flag.\n\n"
+ "You may want to also explicitly specify content width by using SetNextWindowContentWidth() before Begin().");
static int lines = 7;
ImGui::SliderInt("Lines", &lines, 1, 15);
ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 3.0f);
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2.0f, 1.0f));
- ImGui::BeginChild("scrolling", ImVec2(0, ImGui::GetFrameHeightWithSpacing() * 7 + 30), true, ImGuiWindowFlags_HorizontalScrollbar);
+ ImVec2 scrolling_child_size = ImVec2(0, ImGui::GetFrameHeightWithSpacing() * 7 + 30);
+ ImGui::BeginChild("scrolling", scrolling_child_size, true, ImGuiWindowFlags_HorizontalScrollbar);
for (int line = 0; line < lines; line++)
{
- // Display random stuff (for the sake of this trivial demo we are using basic Button+SameLine. If you want to create your own time line for a real application you may be better off
- // manipulating the cursor position yourself, aka using SetCursorPos/SetCursorScreenPos to position the widgets yourself. You may also want to use the lower-level ImDrawList API)
+ // Display random stuff. For the sake of this trivial demo we are using basic Button() + SameLine()
+ // If you want to create your own time line for a real application you may be better off manipulating
+ // the cursor position yourself, aka using SetCursorPos/SetCursorScreenPos to position the widgets
+ // yourself. You may also want to use the lower-level ImDrawList API.
int num_buttons = 10 + ((line & 1) ? line * 9 : line * 3);
for (int n = 0; n < num_buttons; n++)
{
@@ -2349,8 +2826,8 @@ static void ShowDemoWindowLayout()
ImGui::PushID(n + line * 1000);
char num_buf[16];
sprintf(num_buf, "%d", n);
- const char* label = (!(n%15)) ? "FizzBuzz" : (!(n%3)) ? "Fizz" : (!(n%5)) ? "Buzz" : num_buf;
- float hue = n*0.05f;
+ const char* label = (!(n % 15)) ? "FizzBuzz" : (!(n % 3)) ? "Fizz" : (!(n % 5)) ? "Buzz" : num_buf;
+ float hue = n * 0.05f;
ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(hue, 0.6f, 0.6f));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(hue, 0.7f, 0.7f));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(hue, 0.8f, 0.8f));
@@ -2364,13 +2841,21 @@ static void ShowDemoWindowLayout()
ImGui::EndChild();
ImGui::PopStyleVar(2);
float scroll_x_delta = 0.0f;
- ImGui::SmallButton("<<"); if (ImGui::IsItemActive()) { scroll_x_delta = -ImGui::GetIO().DeltaTime * 1000.0f; } ImGui::SameLine();
+ ImGui::SmallButton("<<");
+ if (ImGui::IsItemActive())
+ scroll_x_delta = -ImGui::GetIO().DeltaTime * 1000.0f;
+ ImGui::SameLine();
ImGui::Text("Scroll from code"); ImGui::SameLine();
- ImGui::SmallButton(">>"); if (ImGui::IsItemActive()) { scroll_x_delta = +ImGui::GetIO().DeltaTime * 1000.0f; } ImGui::SameLine();
+ ImGui::SmallButton(">>");
+ if (ImGui::IsItemActive())
+ scroll_x_delta = +ImGui::GetIO().DeltaTime * 1000.0f;
+ ImGui::SameLine();
ImGui::Text("%.0f/%.0f", scroll_x, scroll_max_x);
if (scroll_x_delta != 0.0f)
{
- ImGui::BeginChild("scrolling"); // Demonstrate a trick: you can use Begin to set yourself in the context of another window (here we are already out of your child window)
+ // Demonstrate a trick: you can use Begin to set yourself in the context of another window
+ // (here we are already out of your child window)
+ ImGui::BeginChild("scrolling");
ImGui::SetScrollX(ImGui::GetScrollX() + scroll_x_delta);
ImGui::EndChild();
}
@@ -2441,6 +2926,17 @@ static void ShowDemoWindowLayout()
}
if (show_columns)
{
+ ImGui::Text("Tables:");
+ if (ImGui::BeginTable("table", 4, ImGuiTableFlags_Borders))
+ {
+ for (int n = 0; n < 4; n++)
+ {
+ ImGui::TableNextColumn();
+ ImGui::Text("Width %.2f", ImGui::GetContentRegionAvail().x);
+ }
+ ImGui::EndTable();
+ }
+ ImGui::Text("Columns:");
ImGui::Columns(4);
for (int n = 0; n < 4; n++)
{
@@ -2459,7 +2955,7 @@ static void ShowDemoWindowLayout()
}
if (show_child)
{
- ImGui::BeginChild("child", ImVec2(0,0), true);
+ ImGui::BeginChild("child", ImVec2(0, 0), true);
ImGui::EndChild();
}
ImGui::End();
@@ -2470,16 +2966,66 @@ static void ShowDemoWindowLayout()
if (ImGui::TreeNode("Clipping"))
{
- static ImVec2 size(100, 100), offset(50, 20);
- ImGui::TextWrapped("On a per-widget basis we are occasionally clipping text CPU-side if it won't fit in its frame. Otherwise we are doing coarser clipping + passing a scissor rectangle to the renderer. The system is designed to try minimizing both execution and CPU/GPU rendering cost.");
+ static ImVec2 size(100.0f, 100.0f);
+ static ImVec2 offset(30.0f, 30.0f);
ImGui::DragFloat2("size", (float*)&size, 0.5f, 1.0f, 200.0f, "%.0f");
- ImGui::TextWrapped("(Click and drag)");
- ImVec2 pos = ImGui::GetCursorScreenPos();
- 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), 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::TextWrapped("(Click and drag to scroll)");
+
+ for (int n = 0; n < 3; n++)
+ {
+ if (n > 0)
+ ImGui::SameLine();
+ ImGui::PushID(n);
+ ImGui::BeginGroup(); // Lock X position
+
+ ImGui::InvisibleButton("##empty", size);
+ if (ImGui::IsItemActive() && ImGui::IsMouseDragging(ImGuiMouseButton_Left))
+ {
+ offset.x += ImGui::GetIO().MouseDelta.x;
+ offset.y += ImGui::GetIO().MouseDelta.y;
+ }
+ const ImVec2 p0 = ImGui::GetItemRectMin();
+ const ImVec2 p1 = ImGui::GetItemRectMax();
+ const char* text_str = "Line 1 hello\nLine 2 clip me!";
+ const ImVec2 text_pos = ImVec2(p0.x + offset.x, p0.y + offset.y);
+ ImDrawList* draw_list = ImGui::GetWindowDrawList();
+
+ switch (n)
+ {
+ case 0:
+ HelpMarker(
+ "Using ImGui::PushClipRect():\n"
+ "Will alter ImGui hit-testing logic + ImDrawList rendering.\n"
+ "(use this if you want your clipping rectangle to affect interactions)");
+ ImGui::PushClipRect(p0, p1, true);
+ draw_list->AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255));
+ draw_list->AddText(text_pos, IM_COL32_WHITE, text_str);
+ ImGui::PopClipRect();
+ break;
+ case 1:
+ HelpMarker(
+ "Using ImDrawList::PushClipRect():\n"
+ "Will alter ImDrawList rendering only.\n"
+ "(use this as a shortcut if you are only using ImDrawList calls)");
+ draw_list->PushClipRect(p0, p1, true);
+ draw_list->AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255));
+ draw_list->AddText(text_pos, IM_COL32_WHITE, text_str);
+ draw_list->PopClipRect();
+ break;
+ case 2:
+ HelpMarker(
+ "Using ImDrawList::AddText() with a fine ClipRect:\n"
+ "Will alter only this specific ImDrawList::AddText() rendering.\n"
+ "(this is often used internally to avoid altering the clipping rectangle and minimize draw calls)");
+ ImVec4 clip_rect(p0.x, p0.y, p1.x, p1.y); // AddText() takes a ImVec4* here so let's convert.
+ draw_list->AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255));
+ draw_list->AddText(ImGui::GetFont(), ImGui::GetFontSize(), text_pos, IM_COL32_WHITE, text_str, NULL, 0.0f, &clip_rect);
+ break;
+ }
+ ImGui::EndGroup();
+ ImGui::PopID();
+ }
+
ImGui::TreePop();
}
}
@@ -2492,10 +3038,12 @@ static void ShowDemoWindowPopups()
// The properties of popups windows are:
// - They block normal mouse hovering detection outside them. (*)
// - Unless modal, they can be closed by clicking anywhere outside them, or by pressing ESCAPE.
- // - Their visibility state (~bool) is held internally by Dear ImGui instead of being held by the programmer as we are used to with regular Begin() calls.
- // User can manipulate the visibility state by calling OpenPopup().
- // (*) One can use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup) to bypass it and detect hovering even when normally blocked by a popup.
- // Those three properties are connected. The library needs to hold their visibility state because it can close popups at any time.
+ // - Their visibility state (~bool) is held internally by Dear ImGui instead of being held by the programmer as
+ // we are used to with regular Begin() calls. User can manipulate the visibility state by calling OpenPopup().
+ // (*) One can use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup) to bypass it and detect hovering even
+ // when normally blocked by a popup.
+ // Those three properties are connected. The library needs to hold their visibility state BECAUSE it can close
+ // popups at any time.
// Typical use for regular windows:
// bool my_tool_is_active = false; if (ImGui::Button("Open")) my_tool_is_active = true; [...] if (my_tool_is_active) Begin("My Tool", &my_tool_is_active) { [...] } End();
@@ -2507,14 +3055,16 @@ static void ShowDemoWindowPopups()
if (ImGui::TreeNode("Popups"))
{
- ImGui::TextWrapped("When a popup is active, it inhibits interacting with windows that are behind the popup. Clicking outside the popup closes it.");
+ ImGui::TextWrapped(
+ "When a popup is active, it inhibits interacting with windows that are behind the popup. "
+ "Clicking outside the popup closes it.");
static int selected_fish = -1;
const char* names[] = { "Bream", "Haddock", "Mackerel", "Pollock", "Tilefish" };
static bool toggles[] = { true, false, false, false, false };
- // Simple selection popup
- // (If you want to show the current selection inside the Button itself, you may want to build a string using the "###" operator to preserve a constant ID with a variable label)
+ // Simple selection popup (if you want to show the current selection inside the Button itself,
+ // you may want to build a string using the "###" operator to preserve a constant ID with a variable label)
if (ImGui::Button("Select.."))
ImGui::OpenPopup("my_select_popup");
ImGui::SameLine();
@@ -2585,10 +3135,11 @@ static void ShowDemoWindowPopups()
if (ImGui::TreeNode("Context menus"))
{
// BeginPopupContextItem() is a helper to provide common/simple popup behavior of essentially doing:
- // if (IsItemHovered() && IsMouseReleased(0))
+ // if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
// OpenPopup(id);
// return BeginPopup(id);
- // For more advanced uses you may want to replicate and cuztomize this code. This the comments inside BeginPopupContextItem() implementation.
+ // For more advanced uses you may want to replicate and customize this code.
+ // See details in BeginPopupContextItem().
static float value = 0.5f;
ImGui::Text("Value = %.3f (<-- right-click here)", value);
if (ImGui::BeginPopupContextItem("item context menu"))
@@ -2600,16 +3151,19 @@ static void ShowDemoWindowPopups()
ImGui::EndPopup();
}
- // We can also use OpenPopupOnItemClick() which is the same as BeginPopupContextItem() but without the Begin call.
- // So here we will make it that clicking on the text field with the right mouse button (1) will toggle the visibility of the popup above.
+ // We can also use OpenPopupOnItemClick() which is the same as BeginPopupContextItem() but without the
+ // Begin() call. So here we will make it that clicking on the text field with the right mouse button (1)
+ // will toggle the visibility of the popup above.
ImGui::Text("(You can also right-click me to open the same popup as above.)");
ImGui::OpenPopupOnItemClick("item context menu", 1);
- // When used after an item that has an ID (here the Button), we can skip providing an ID to BeginPopupContextItem().
+ // When used after an item that has an ID (e.g.Button), we can skip providing an ID to BeginPopupContextItem().
// BeginPopupContextItem() will use the last item ID as the popup ID.
- // In addition here, we want to include your editable label inside the button label. We use the ### operator to override the ID (read FAQ about ID for details)
+ // In addition here, we want to include your editable label inside the button label.
+ // We use the ### operator to override the ID (read FAQ about ID for details)
static char name[32] = "Label1";
- char buf[64]; sprintf(buf, "Button: %s###Button", name); // ### operator override ID ignoring the preceding label
+ char buf[64];
+ sprintf(buf, "Button: %s###Button", name); // ### operator override ID ignoring the preceding label
ImGui::Button(buf);
if (ImGui::BeginPopupContextItem())
{
@@ -2626,18 +3180,22 @@ static void ShowDemoWindowPopups()
if (ImGui::TreeNode("Modals"))
{
- ImGui::TextWrapped("Modal windows are like popups but the user cannot close them by clicking outside the window.");
+ ImGui::TextWrapped("Modal windows are like popups but the user cannot close them by clicking outside.");
if (ImGui::Button("Delete.."))
ImGui::OpenPopup("Delete?");
+ // Always center this window when appearing
+ ImVec2 center(ImGui::GetIO().DisplaySize.x * 0.5f, ImGui::GetIO().DisplaySize.y * 0.5f);
+ ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
+
if (ImGui::BeginPopupModal("Delete?", NULL, ImGuiWindowFlags_AlwaysAutoResize))
{
ImGui::Text("All those beautiful files will be deleted.\nThis operation cannot be undone!\n\n");
ImGui::Separator();
- //static int dummy_i = 0;
- //ImGui::Combo("Combo", &dummy_i, "Delete\0Delete harder\0");
+ //static int unused_i = 0;
+ //ImGui::Combo("Combo", &unused_i, "Delete\0Delete harder\0");
static bool dont_ask_me_next_time = false;
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
@@ -2659,7 +3217,7 @@ static void ShowDemoWindowPopups()
{
if (ImGui::BeginMenu("File"))
{
- if (ImGui::MenuItem("Dummy menu item")) {}
+ if (ImGui::MenuItem("Some menu item")) {}
ImGui::EndMenu();
}
ImGui::EndMenuBar();
@@ -2668,17 +3226,18 @@ static void ShowDemoWindowPopups()
// Testing behavior of widgets stacking their own regular popups over the modal.
static int item = 1;
- static float color[4] = { 0.4f,0.7f,0.0f,0.5f };
+ static float color[4] = { 0.4f, 0.7f, 0.0f, 0.5f };
ImGui::Combo("Combo", &item, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0");
ImGui::ColorEdit4("color", color);
if (ImGui::Button("Add another modal.."))
ImGui::OpenPopup("Stacked 2");
- // Also demonstrate passing a bool* to BeginPopupModal(), this will create a regular close button which will close the popup.
- // Note that the visibility state of popups is owned by imgui, so the input value of the bool actually doesn't matter here.
- bool dummy_open = true;
- if (ImGui::BeginPopupModal("Stacked 2", &dummy_open))
+ // Also demonstrate passing a bool* to BeginPopupModal(), this will create a regular close button which
+ // will close the popup. Note that the visibility state of popups is owned by imgui, so the input value
+ // of the bool actually doesn't matter here.
+ bool unused_open = true;
+ if (ImGui::BeginPopupModal("Stacked 2", &unused_open))
{
ImGui::Text("Hello from Stacked The Second!");
if (ImGui::Button("Close"))
@@ -2698,9 +3257,12 @@ static void ShowDemoWindowPopups()
{
ImGui::TextWrapped("Below we are testing adding menu items to a regular window. It's rather unusual but should work!");
ImGui::Separator();
- // NB: As a quirk in this very specific example, we want to differentiate the parent of this menu from the parent of the various popup menus above.
- // To do so we are encloding the items in a PushID()/PopID() block to make them two different menusets. If we don't, opening any popup above and hovering our menu here
- // would open it. This is because once a menu is active, we allow to switch to a sibling menu by just hovering on it, which is the desired behavior for regular menus.
+
+ // Note: As a quirk in this very specific example, we want to differentiate the parent of this menu from the
+ // parent of the various popup menus above. To do so we are encloding the items in a PushID()/PopID() block
+ // to make them two different menusets. If we don't, opening any popup above and hovering our menu here would
+ // open it. This is because once a menu is active, we allow to switch to a sibling menu by just hovering on it,
+ // which is the desired behavior for regular menus.
ImGui::PushID("foo");
ImGui::MenuItem("Menu item", "CTRL+M");
if (ImGui::BeginMenu("Menu inside a regular window"))
@@ -2714,20 +3276,1863 @@ static void ShowDemoWindowPopups()
}
}
-static void ShowDemoWindowColumns()
+// Dummy data structure that we use for the Table demo.
+// (pre-C++11 doesn't allow us to instantiate ImVector template if this structure if defined inside the demo function)
+namespace
{
- if (!ImGui::CollapsingHeader("Columns"))
+// We are passing our own identifier to TableSetupColumn() to facilitate identifying columns in the sorting code.
+// This identifier will be passed down into ImGuiTableSortSpec::ColumnUserID.
+// But it is possible to omit the user id parameter of TableSetupColumn() and just use the column index instead! (ImGuiTableSortSpec::ColumnIndex)
+// If you don't use sorting, you will generally never care about giving column an ID!
+enum MyItemColumnID
+{
+ MyItemColumnID_ID,
+ MyItemColumnID_Name,
+ MyItemColumnID_Action,
+ MyItemColumnID_Quantity,
+ MyItemColumnID_Description
+};
+
+struct MyItem
+{
+ int ID;
+ const char* Name;
+ int Quantity;
+
+ // We have a problem which is affecting _only this demo_ and should not affect your code:
+ // As we don't rely on std:: or other third-party library to compile dear imgui, we only have reliable access to qsort(),
+ // however qsort doesn't allow passing user data to comparing function.
+ // As a workaround, we are storing the sort specs in a static/global for the comparing function to access.
+ // In your own use case you would probably pass the sort specs to your sorting/comparing functions directly and not use a global.
+ // We could technically call ImGui::TableGetSortSpecs() in CompareWithSortSpecs(), but considering that this function is called
+ // very often by the sorting algorithm it would be a little wasteful.
+ static const ImGuiTableSortSpecs* s_current_sort_specs;
+
+ // Compare function to be used by qsort()
+ static int IMGUI_CDECL CompareWithSortSpecs(const void* lhs, const void* rhs)
+ {
+ const MyItem* a = (const MyItem*)lhs;
+ const MyItem* b = (const MyItem*)rhs;
+ for (int n = 0; n < s_current_sort_specs->SpecsCount; n++)
+ {
+ // Here we identify columns using the ColumnUserID value that we ourselves passed to TableSetupColumn()
+ // We could also choose to identify columns based on their index (sort_spec->ColumnIndex), which is simpler!
+ const ImGuiTableColumnSortSpecs* sort_spec = &s_current_sort_specs->Specs[n];
+ int delta = 0;
+ switch (sort_spec->ColumnUserID)
+ {
+ case MyItemColumnID_ID: delta = (a->ID - b->ID); break;
+ case MyItemColumnID_Name: delta = (strcmp(a->Name, b->Name)); break;
+ case MyItemColumnID_Quantity: delta = (a->Quantity - b->Quantity); break;
+ case MyItemColumnID_Description: delta = (strcmp(a->Name, b->Name)); break;
+ default: IM_ASSERT(0); break;
+ }
+ if (delta > 0)
+ return (sort_spec->SortDirection == ImGuiSortDirection_Ascending) ? +1 : -1;
+ if (delta < 0)
+ return (sort_spec->SortDirection == ImGuiSortDirection_Ascending) ? -1 : +1;
+ }
+
+ // qsort() is instable so always return a way to differenciate items.
+ // Your own compare function may want to avoid fallback on implicit sort specs e.g. a Name compare if it wasn't already part of the sort specs.
+ return (a->ID - b->ID);
+ }
+};
+const ImGuiTableSortSpecs* MyItem::s_current_sort_specs = NULL;
+}
+
+// Make the UI compact because there are so many fields
+static void PushStyleCompact()
+{
+ ImGuiStyle& style = ImGui::GetStyle();
+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(style.FramePadding.x, (float)(int)(style.FramePadding.y * 0.60f)));
+ ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(style.ItemSpacing.x, (float)(int)(style.ItemSpacing.y * 0.60f)));
+}
+
+static void PopStyleCompact()
+{
+ ImGui::PopStyleVar(2);
+}
+
+// Show a combo box with a choice of sizing policies
+static void EditTableSizingFlags(ImGuiTableFlags* p_flags)
+{
+ struct EnumDesc { ImGuiTableFlags Value; const char* Name; const char* Tooltip; };
+ static const EnumDesc policies[] =
+ {
+ { ImGuiTableFlags_None, "Default", "Use default sizing policy:\n- ImGuiTableFlags_SizingFixedFit if ScrollX is on or if host window has ImGuiWindowFlags_AlwaysAutoResize.\n- ImGuiTableFlags_SizingStretchSame otherwise." },
+ { ImGuiTableFlags_SizingFixedFit, "ImGuiTableFlags_SizingFixedFit", "Columns default to _WidthFixed (if resizable) or _WidthAuto (if not resizable), matching contents width." },
+ { ImGuiTableFlags_SizingFixedSame, "ImGuiTableFlags_SizingFixedSame", "Columns are all the same width, matching the maximum contents width.\nImplicitly disable ImGuiTableFlags_Resizable and enable ImGuiTableFlags_NoKeepColumnsVisible." },
+ { ImGuiTableFlags_SizingStretchProp, "ImGuiTableFlags_SizingStretchProp", "Columns default to _WidthStretch with weights proportional to their widths." },
+ { ImGuiTableFlags_SizingStretchSame, "ImGuiTableFlags_SizingStretchSame", "Columns default to _WidthStretch with same weights." }
+ };
+ int idx;
+ for (idx = 0; idx < IM_ARRAYSIZE(policies); idx++)
+ if (policies[idx].Value == (*p_flags & ImGuiTableFlags_SizingMask_))
+ break;
+ const char* preview_text = (idx < IM_ARRAYSIZE(policies)) ? policies[idx].Name + (idx > 0 ? strlen("ImGuiTableFlags") : 0) : "";
+ if (ImGui::BeginCombo("Sizing Policy", preview_text))
+ {
+ for (int n = 0; n < IM_ARRAYSIZE(policies); n++)
+ if (ImGui::Selectable(policies[n].Name, idx == n))
+ *p_flags = (*p_flags & ~ImGuiTableFlags_SizingMask_) | policies[n].Value;
+ ImGui::EndCombo();
+ }
+ ImGui::SameLine();
+ ImGui::TextDisabled("(?)");
+ if (ImGui::IsItemHovered())
+ {
+ ImGui::BeginTooltip();
+ ImGui::PushTextWrapPos(ImGui::GetFontSize() * 50.0f);
+ for (int m = 0; m < IM_ARRAYSIZE(policies); m++)
+ {
+ ImGui::Separator();
+ ImGui::Text("%s:", policies[m].Name);
+ ImGui::Separator();
+ ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetStyle().IndentSpacing * 0.5f);
+ ImGui::TextUnformatted(policies[m].Tooltip);
+ }
+ ImGui::PopTextWrapPos();
+ ImGui::EndTooltip();
+ }
+}
+
+static void EditTableColumnsFlags(ImGuiTableColumnFlags* p_flags)
+{
+ ImGui::CheckboxFlags("_DefaultHide", p_flags, ImGuiTableColumnFlags_DefaultHide);
+ ImGui::CheckboxFlags("_DefaultSort", p_flags, ImGuiTableColumnFlags_DefaultSort);
+ if (ImGui::CheckboxFlags("_WidthStretch", p_flags, ImGuiTableColumnFlags_WidthStretch))
+ *p_flags &= ~(ImGuiTableColumnFlags_WidthMask_ ^ ImGuiTableColumnFlags_WidthStretch);
+ if (ImGui::CheckboxFlags("_WidthFixed", p_flags, ImGuiTableColumnFlags_WidthFixed))
+ *p_flags &= ~(ImGuiTableColumnFlags_WidthMask_ ^ ImGuiTableColumnFlags_WidthFixed);
+ ImGui::CheckboxFlags("_NoResize", p_flags, ImGuiTableColumnFlags_NoResize);
+ ImGui::CheckboxFlags("_NoReorder", p_flags, ImGuiTableColumnFlags_NoReorder);
+ ImGui::CheckboxFlags("_NoHide", p_flags, ImGuiTableColumnFlags_NoHide);
+ ImGui::CheckboxFlags("_NoClip", p_flags, ImGuiTableColumnFlags_NoClip);
+ ImGui::CheckboxFlags("_NoSort", p_flags, ImGuiTableColumnFlags_NoSort);
+ ImGui::CheckboxFlags("_NoSortAscending", p_flags, ImGuiTableColumnFlags_NoSortAscending);
+ ImGui::CheckboxFlags("_NoSortDescending", p_flags, ImGuiTableColumnFlags_NoSortDescending);
+ ImGui::CheckboxFlags("_NoHeaderWidth", p_flags, ImGuiTableColumnFlags_NoHeaderWidth);
+ ImGui::CheckboxFlags("_PreferSortAscending", p_flags, ImGuiTableColumnFlags_PreferSortAscending);
+ ImGui::CheckboxFlags("_PreferSortDescending", p_flags, ImGuiTableColumnFlags_PreferSortDescending);
+ ImGui::CheckboxFlags("_IndentEnable", p_flags, ImGuiTableColumnFlags_IndentEnable); ImGui::SameLine(); HelpMarker("Default for column 0");
+ ImGui::CheckboxFlags("_IndentDisable", p_flags, ImGuiTableColumnFlags_IndentDisable); ImGui::SameLine(); HelpMarker("Default for column >0");
+}
+
+static void ShowTableColumnsStatusFlags(ImGuiTableColumnFlags flags)
+{
+ ImGui::CheckboxFlags("_IsEnabled", &flags, ImGuiTableColumnFlags_IsEnabled);
+ ImGui::CheckboxFlags("_IsVisible", &flags, ImGuiTableColumnFlags_IsVisible);
+ ImGui::CheckboxFlags("_IsSorted", &flags, ImGuiTableColumnFlags_IsSorted);
+ ImGui::CheckboxFlags("_IsHovered", &flags, ImGuiTableColumnFlags_IsHovered);
+}
+
+static void ShowDemoWindowTables()
+{
+ //ImGui::SetNextItemOpen(true, ImGuiCond_Once);
+ if (!ImGui::CollapsingHeader("Tables & Columns"))
return;
- ImGui::PushID("Columns");
+ // Using those as a base value to create width/height that are factor of the size of our font
+ const float TEXT_BASE_WIDTH = ImGui::CalcTextSize("A").x;
+ const float TEXT_BASE_HEIGHT = ImGui::GetTextLineHeightWithSpacing();
+ ImGui::PushID("Tables");
+
+ int open_action = -1;
+ if (ImGui::Button("Open all"))
+ open_action = 1;
+ ImGui::SameLine();
+ if (ImGui::Button("Close all"))
+ open_action = 0;
+ ImGui::SameLine();
+
+ // Options
static bool disable_indent = false;
ImGui::Checkbox("Disable tree indentation", &disable_indent);
ImGui::SameLine();
- HelpMarker("Disable the indenting of tree nodes so demo columns can use the full window width.");
+ HelpMarker("Disable the indenting of tree nodes so demo tables can use the full window width.");
+ ImGui::Separator();
if (disable_indent)
ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, 0.0f);
+ // About Styling of tables
+ // Most settings are configured on a per-table basis via the flags passed to BeginTable() and TableSetupColumns APIs.
+ // There are however a few settings that a shared and part of the ImGuiStyle structure:
+ // style.CellPadding // Padding within each cell
+ // style.Colors[ImGuiCol_TableHeaderBg] // Table header background
+ // style.Colors[ImGuiCol_TableBorderStrong] // Table outer and header borders
+ // style.Colors[ImGuiCol_TableBorderLight] // Table inner borders
+ // style.Colors[ImGuiCol_TableRowBg] // Table row background when ImGuiTableFlags_RowBg is enabled (even rows)
+ // style.Colors[ImGuiCol_TableRowBgAlt] // Table row background when ImGuiTableFlags_RowBg is enabled (odds rows)
+
+ // Demos
+ if (open_action != -1)
+ ImGui::SetNextItemOpen(open_action != 0);
+ if (ImGui::TreeNode("Basic"))
+ {
+ // Here we will showcase three different ways to output a table.
+ // They are very simple variations of a same thing!
+
+ // [Method 1] Using TableNextRow() to create a new row, and TableSetColumnIndex() to select the column.
+ // In many situations, this is the most flexible and easy to use pattern.
+ HelpMarker("Using TableNextRow() + calling TableSetColumnIndex() _before_ each cell, in a loop.");
+ if (ImGui::BeginTable("table1", 3))
+ {
+ for (int row = 0; row < 4; row++)
+ {
+ ImGui::TableNextRow();
+ for (int column = 0; column < 3; column++)
+ {
+ ImGui::TableSetColumnIndex(column);
+ ImGui::Text("Row %d Column %d", row, column);
+ }
+ }
+ ImGui::EndTable();
+ }
+
+ // [Method 2] Using TableNextColumn() called multiple times, instead of using a for loop + TableSetColumnIndex().
+ // This is generally more convenient when you have code manually submitting the contents of each columns.
+ HelpMarker("Using TableNextRow() + calling TableNextColumn() _before_ each cell, manually.");
+ if (ImGui::BeginTable("table2", 3))
+ {
+ for (int row = 0; row < 4; row++)
+ {
+ ImGui::TableNextRow();
+ ImGui::TableNextColumn();
+ ImGui::Text("Row %d", row);
+ ImGui::TableNextColumn();
+ ImGui::Text("Some contents");
+ ImGui::TableNextColumn();
+ ImGui::Text("123.456");
+ }
+ ImGui::EndTable();
+ }
+
+ // [Method 3] We call TableNextColumn() _before_ each cell. We never call TableNextRow(),
+ // as TableNextColumn() will automatically wrap around and create new roes as needed.
+ // This is generally more convenient when your cells all contains the same type of data.
+ HelpMarker(
+ "Only using TableNextColumn(), which tends to be convenient for tables where every cells contains the same type of contents.\n"
+ "This is also more similar to the old NextColumn() function of the Columns API, and provided to facilitate the Columns->Tables API transition.");
+ if (ImGui::BeginTable("table3", 3))
+ {
+ for (int item = 0; item < 14; item++)
+ {
+ ImGui::TableNextColumn();
+ ImGui::Text("Item %d", item);
+ }
+ ImGui::EndTable();
+ }
+
+ ImGui::TreePop();
+ }
+
+ if (open_action != -1)
+ ImGui::SetNextItemOpen(open_action != 0);
+ if (ImGui::TreeNode("Borders, background"))
+ {
+ // Expose a few Borders related flags interactively
+ enum ContentsType { CT_Text, CT_FillButton };
+ static ImGuiTableFlags flags = ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg;
+ static bool display_headers = false;
+ static int contents_type = CT_Text;
+
+ PushStyleCompact();
+ ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", &flags, ImGuiTableFlags_RowBg);
+ ImGui::CheckboxFlags("ImGuiTableFlags_Borders", &flags, ImGuiTableFlags_Borders);
+ ImGui::SameLine(); HelpMarker("ImGuiTableFlags_Borders\n = ImGuiTableFlags_BordersInnerV\n | ImGuiTableFlags_BordersOuterV\n | ImGuiTableFlags_BordersInnerV\n | ImGuiTableFlags_BordersOuterH");
+ ImGui::Indent();
+
+ ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", &flags, ImGuiTableFlags_BordersH);
+ ImGui::Indent();
+ ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterH", &flags, ImGuiTableFlags_BordersOuterH);
+ ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerH", &flags, ImGuiTableFlags_BordersInnerH);
+ ImGui::Unindent();
+
+ ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", &flags, ImGuiTableFlags_BordersV);
+ ImGui::Indent();
+ ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", &flags, ImGuiTableFlags_BordersOuterV);
+ ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", &flags, ImGuiTableFlags_BordersInnerV);
+ ImGui::Unindent();
+
+ ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuter", &flags, ImGuiTableFlags_BordersOuter);
+ ImGui::CheckboxFlags("ImGuiTableFlags_BordersInner", &flags, ImGuiTableFlags_BordersInner);
+ ImGui::Unindent();
+
+ ImGui::AlignTextToFramePadding(); ImGui::Text("Cell contents:");
+ ImGui::SameLine(); ImGui::RadioButton("Text", &contents_type, CT_Text);
+ ImGui::SameLine(); ImGui::RadioButton("FillButton", &contents_type, CT_FillButton);
+ ImGui::Checkbox("Display headers", &display_headers);
+ ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBody", &flags, ImGuiTableFlags_NoBordersInBody); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body (borders will always appears in Headers");
+ PopStyleCompact();
+
+ if (ImGui::BeginTable("table1", 3, flags))
+ {
+ // Display headers so we can inspect their interaction with borders.
+ // (Headers are not the main purpose of this section of the demo, so we are not elaborating on them too much. See other sections for details)
+ if (display_headers)
+ {
+ ImGui::TableSetupColumn("One");
+ ImGui::TableSetupColumn("Two");
+ ImGui::TableSetupColumn("Three");
+ ImGui::TableHeadersRow();
+ }
+
+ for (int row = 0; row < 5; row++)
+ {
+ ImGui::TableNextRow();
+ for (int column = 0; column < 3; column++)
+ {
+ ImGui::TableSetColumnIndex(column);
+ char buf[32];
+ sprintf(buf, "Hello %d,%d", column, row);
+ if (contents_type == CT_Text)
+ ImGui::TextUnformatted(buf);
+ else if (contents_type)
+ ImGui::Button(buf, ImVec2(-FLT_MIN, 0.0f));
+ }
+ }
+ ImGui::EndTable();
+ }
+ ImGui::TreePop();
+ }
+
+ if (open_action != -1)
+ ImGui::SetNextItemOpen(open_action != 0);
+ if (ImGui::TreeNode("Resizable, stretch"))
+ {
+ // By default, if we don't enable ScrollX the sizing policy for each columns is "Stretch"
+ // Each columns maintain a sizing weight, and they will occupy all available width.
+ static ImGuiTableFlags flags = ImGuiTableFlags_SizingStretchSame | ImGuiTableFlags_Resizable | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_ContextMenuInBody;
+ PushStyleCompact();
+ ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags, ImGuiTableFlags_Resizable);
+ ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", &flags, ImGuiTableFlags_BordersV);
+ ImGui::SameLine(); HelpMarker("Using the _Resizable flag automatically enables the _BordersInnerV flag as well, this is why the resize borders are still showing when unchecking this.");
+ PopStyleCompact();
+
+ if (ImGui::BeginTable("table1", 3, flags))
+ {
+ for (int row = 0; row < 5; row++)
+ {
+ ImGui::TableNextRow();
+ for (int column = 0; column < 3; column++)
+ {
+ ImGui::TableSetColumnIndex(column);
+ ImGui::Text("Hello %d,%d", column, row);
+ }
+ }
+ ImGui::EndTable();
+ }
+ ImGui::TreePop();
+ }
+
+ if (open_action != -1)
+ ImGui::SetNextItemOpen(open_action != 0);
+ if (ImGui::TreeNode("Resizable, fixed"))
+ {
+ // Here we use ImGuiTableFlags_SizingFixedFit (even though _ScrollX is not set)
+ // So columns will adopt the "Fixed" policy and will maintain a fixed width regardless of the whole available width (unless table is small)
+ // If there is not enough available width to fit all columns, they will however be resized down.
+ // FIXME-TABLE: Providing a stretch-on-init would make sense especially for tables which don't have saved settings
+ HelpMarker(
+ "Using _Resizable + _SizingFixedFit flags.\n"
+ "Fixed-width columns generally makes more sense if you want to use horizontal scrolling.\n\n"
+ "Double-click a column border to auto-fit the column to its contents.");
+ PushStyleCompact();
+ static ImGuiTableFlags flags = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_ContextMenuInBody;
+ ImGui::CheckboxFlags("ImGuiTableFlags_NoHostExtendX", &flags, ImGuiTableFlags_NoHostExtendX);
+ PopStyleCompact();
+
+ if (ImGui::BeginTable("table1", 3, flags))
+ {
+ for (int row = 0; row < 5; row++)
+ {
+ ImGui::TableNextRow();
+ for (int column = 0; column < 3; column++)
+ {
+ ImGui::TableSetColumnIndex(column);
+ ImGui::Text("Hello %d,%d", column, row);
+ }
+ }
+ ImGui::EndTable();
+ }
+ ImGui::TreePop();
+ }
+
+ if (open_action != -1)
+ ImGui::SetNextItemOpen(open_action != 0);
+ if (ImGui::TreeNode("Resizable, mixed"))
+ {
+ HelpMarker(
+ "Using TableSetupColumn() to alter resizing policy on a per-column basis.\n\n"
+ "When combining Fixed and Stretch columns, generally you only want one, maybe two trailing columns to use _WidthStretch.");
+ static ImGuiTableFlags flags = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable;
+
+ if (ImGui::BeginTable("table1", 3, flags))
+ {
+ ImGui::TableSetupColumn("AAA", ImGuiTableColumnFlags_WidthFixed);
+ ImGui::TableSetupColumn("BBB", ImGuiTableColumnFlags_WidthFixed);
+ ImGui::TableSetupColumn("CCC", ImGuiTableColumnFlags_WidthStretch);
+ ImGui::TableHeadersRow();
+ for (int row = 0; row < 5; row++)
+ {
+ ImGui::TableNextRow();
+ for (int column = 0; column < 3; column++)
+ {
+ ImGui::TableSetColumnIndex(column);
+ ImGui::Text("%s %d,%d", (column == 2) ? "Stretch" : "Fixed", column, row);
+ }
+ }
+ ImGui::EndTable();
+ }
+ if (ImGui::BeginTable("table2", 6, flags))
+ {
+ ImGui::TableSetupColumn("AAA", ImGuiTableColumnFlags_WidthFixed);
+ ImGui::TableSetupColumn("BBB", ImGuiTableColumnFlags_WidthFixed);
+ ImGui::TableSetupColumn("CCC", ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_DefaultHide);
+ ImGui::TableSetupColumn("DDD", ImGuiTableColumnFlags_WidthStretch);
+ ImGui::TableSetupColumn("EEE", ImGuiTableColumnFlags_WidthStretch);
+ ImGui::TableSetupColumn("FFF", ImGuiTableColumnFlags_WidthStretch | ImGuiTableColumnFlags_DefaultHide);
+ ImGui::TableHeadersRow();
+ for (int row = 0; row < 5; row++)
+ {
+ ImGui::TableNextRow();
+ for (int column = 0; column < 6; column++)
+ {
+ ImGui::TableSetColumnIndex(column);
+ ImGui::Text("%s %d,%d", (column >= 3) ? "Stretch" : "Fixed", column, row);
+ }
+ }
+ ImGui::EndTable();
+ }
+ ImGui::TreePop();
+ }
+
+ if (open_action != -1)
+ ImGui::SetNextItemOpen(open_action != 0);
+ if (ImGui::TreeNode("Reorderable, hideable, with headers"))
+ {
+ HelpMarker(
+ "Click and drag column headers to reorder columns.\n\n"
+ "Right-click on a header to open a context menu.");
+ static ImGuiTableFlags flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV;
+ PushStyleCompact();
+ ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags, ImGuiTableFlags_Resizable);
+ ImGui::CheckboxFlags("ImGuiTableFlags_Reorderable", &flags, ImGuiTableFlags_Reorderable);
+ ImGui::CheckboxFlags("ImGuiTableFlags_Hideable", &flags, ImGuiTableFlags_Hideable);
+ ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBody", &flags, ImGuiTableFlags_NoBordersInBody);
+ ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBodyUntilResize", &flags, ImGuiTableFlags_NoBordersInBodyUntilResize); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body until hovered for resize (borders will always appears in Headers)");
+ PopStyleCompact();
+
+ if (ImGui::BeginTable("table1", 3, flags))
+ {
+ // Submit columns name with TableSetupColumn() and call TableHeadersRow() to create a row with a header in each column.
+ // (Later we will show how TableSetupColumn() has other uses, optional flags, sizing weight etc.)
+ ImGui::TableSetupColumn("One");
+ ImGui::TableSetupColumn("Two");
+ ImGui::TableSetupColumn("Three");
+ ImGui::TableHeadersRow();
+ for (int row = 0; row < 6; row++)
+ {
+ ImGui::TableNextRow();
+ for (int column = 0; column < 3; column++)
+ {
+ ImGui::TableSetColumnIndex(column);
+ ImGui::Text("Hello %d,%d", column, row);
+ }
+ }
+ ImGui::EndTable();
+ }
+
+ // Use outer_size.x == 0.0f instead of default to make the table as tight as possible (only valid when no scrolling and no stretch column)
+ if (ImGui::BeginTable("table2", 3, flags | ImGuiTableFlags_SizingFixedFit, ImVec2(0.0f, 0.0f)))
+ {
+ ImGui::TableSetupColumn("One");
+ ImGui::TableSetupColumn("Two");
+ ImGui::TableSetupColumn("Three");
+ ImGui::TableHeadersRow();
+ for (int row = 0; row < 6; row++)
+ {
+ ImGui::TableNextRow();
+ for (int column = 0; column < 3; column++)
+ {
+ ImGui::TableSetColumnIndex(column);
+ ImGui::Text("Fixed %d,%d", column, row);
+ }
+ }
+ ImGui::EndTable();
+ }
+ ImGui::TreePop();
+ }
+
+ if (open_action != -1)
+ ImGui::SetNextItemOpen(open_action != 0);
+ if (ImGui::TreeNode("Padding"))
+ {
+ // First example: showcase use of padding flags and effect of BorderOuterV/BorderInnerV on X padding.
+ // We don't expose BorderOuterH/BorderInnerH here because they have no effect on X padding.
+ HelpMarker(
+ "We often want outer padding activated when any using features which makes the edges of a column visible:\n"
+ "e.g.:\n"
+ "- BorderOuterV\n"
+ "- any form of row selection\n"
+ "Because of this, activating BorderOuterV sets the default to PadOuterX. Using PadOuterX or NoPadOuterX you can override the default.\n\n"
+ "Actual padding values are using style.CellPadding.\n\n"
+ "In this demo we don't show horizontal borders to emphasis how they don't affect default horizontal padding.");
+
+ static ImGuiTableFlags flags1 = ImGuiTableFlags_BordersV;
+ PushStyleCompact();
+ ImGui::CheckboxFlags("ImGuiTableFlags_PadOuterX", &flags1, ImGuiTableFlags_PadOuterX);
+ ImGui::SameLine(); HelpMarker("Enable outer-most padding (default if ImGuiTableFlags_BordersOuterV is set)");
+ ImGui::CheckboxFlags("ImGuiTableFlags_NoPadOuterX", &flags1, ImGuiTableFlags_NoPadOuterX);
+ ImGui::SameLine(); HelpMarker("Disable outer-most padding (default if ImGuiTableFlags_BordersOuterV is not set)");
+ ImGui::CheckboxFlags("ImGuiTableFlags_NoPadInnerX", &flags1, ImGuiTableFlags_NoPadInnerX);
+ ImGui::SameLine(); HelpMarker("Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off)");
+ ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", &flags1, ImGuiTableFlags_BordersOuterV);
+ ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", &flags1, ImGuiTableFlags_BordersInnerV);
+ static bool show_headers = false;
+ ImGui::Checkbox("show_headers", &show_headers);
+ PopStyleCompact();
+
+ if (ImGui::BeginTable("table_padding", 3, flags1))
+ {
+ if (show_headers)
+ {
+ ImGui::TableSetupColumn("One");
+ ImGui::TableSetupColumn("Two");
+ ImGui::TableSetupColumn("Three");
+ ImGui::TableHeadersRow();
+ }
+
+ for (int row = 0; row < 5; row++)
+ {
+ ImGui::TableNextRow();
+ for (int column = 0; column < 3; column++)
+ {
+ ImGui::TableSetColumnIndex(column);
+ if (row == 0)
+ {
+ ImGui::Text("Avail %.2f", ImGui::GetContentRegionAvail().x);
+ }
+ else
+ {
+ char buf[32];
+ sprintf(buf, "Hello %d,%d", column, row);
+ ImGui::Button(buf, ImVec2(-FLT_MIN, 0.0f));
+ }
+ //if (ImGui::TableGetColumnFlags() & ImGuiTableColumnFlags_IsHovered)
+ // ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, IM_COL32(0, 100, 0, 255));
+ }
+ }
+ ImGui::EndTable();
+ }
+
+ // Second example: set style.CellPadding to (0.0) or a custom value.
+ // FIXME-TABLE: Vertical border effectively not displayed the same way as horizontal one...
+ HelpMarker("Setting style.CellPadding to (0,0) or a custom value.");
+ static ImGuiTableFlags flags2 = ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg;
+ static ImVec2 cell_padding(0.0f, 0.0f);
+ static bool show_widget_frame_bg = true;
+
+ PushStyleCompact();
+ ImGui::CheckboxFlags("ImGuiTableFlags_Borders", &flags2, ImGuiTableFlags_Borders);
+ ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", &flags2, ImGuiTableFlags_BordersH);
+ ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", &flags2, ImGuiTableFlags_BordersV);
+ ImGui::CheckboxFlags("ImGuiTableFlags_BordersInner", &flags2, ImGuiTableFlags_BordersInner);
+ ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuter", &flags2, ImGuiTableFlags_BordersOuter);
+ ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", &flags2, ImGuiTableFlags_RowBg);
+ ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags2, ImGuiTableFlags_Resizable);
+ ImGui::Checkbox("show_widget_frame_bg", &show_widget_frame_bg);
+ ImGui::SliderFloat2("CellPadding", &cell_padding.x, 0.0f, 10.0f, "%.0f");
+ PopStyleCompact();
+
+ ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, cell_padding);
+ if (ImGui::BeginTable("table_padding_2", 3, flags2))
+ {
+ static char text_bufs[3 * 5][16]; // Mini text storage for 3x5 cells
+ static bool init = true;
+ if (!show_widget_frame_bg)
+ ImGui::PushStyleColor(ImGuiCol_FrameBg, 0);
+ for (int cell = 0; cell < 3 * 5; cell++)
+ {
+ ImGui::TableNextColumn();
+ if (init)
+ strcpy(text_bufs[cell], "edit me");
+ ImGui::SetNextItemWidth(-FLT_MIN);
+ ImGui::PushID(cell);
+ ImGui::InputText("##cell", text_bufs[cell], IM_ARRAYSIZE(text_bufs[cell]));
+ ImGui::PopID();
+ }
+ if (!show_widget_frame_bg)
+ ImGui::PopStyleColor();
+ init = false;
+ ImGui::EndTable();
+ }
+ ImGui::PopStyleVar();
+
+ ImGui::TreePop();
+ }
+
+ if (open_action != -1)
+ ImGui::SetNextItemOpen(open_action != 0);
+ if (ImGui::TreeNode("Sizing policies"))
+ {
+ static ImGuiTableFlags flags1 = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_RowBg | ImGuiTableFlags_ContextMenuInBody;
+ PushStyleCompact();
+ ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags1, ImGuiTableFlags_Resizable);
+ ImGui::CheckboxFlags("ImGuiTableFlags_NoHostExtendX", &flags1, ImGuiTableFlags_NoHostExtendX);
+ PopStyleCompact();
+
+ static ImGuiTableFlags sizing_policy_flags[4] = { ImGuiTableFlags_SizingFixedFit, ImGuiTableFlags_SizingFixedSame, ImGuiTableFlags_SizingStretchProp, ImGuiTableFlags_SizingStretchSame };
+ for (int table_n = 0; table_n < 4; table_n++)
+ {
+ ImGui::PushID(table_n);
+ ImGui::SetNextItemWidth(TEXT_BASE_WIDTH * 30);
+ EditTableSizingFlags(&sizing_policy_flags[table_n]);
+
+ // To make it easier to understand the different sizing policy,
+ // For each policy: we display one table where the columns have equal contents width, and one where the columns have different contents width.
+ if (ImGui::BeginTable("table1", 3, sizing_policy_flags[table_n] | flags1))
+ {
+ for (int row = 0; row < 3; row++)
+ {
+ ImGui::TableNextRow();
+ ImGui::TableNextColumn(); ImGui::Text("Oh dear");
+ ImGui::TableNextColumn(); ImGui::Text("Oh dear");
+ ImGui::TableNextColumn(); ImGui::Text("Oh dear");
+ }
+ ImGui::EndTable();
+ }
+ if (ImGui::BeginTable("table2", 3, sizing_policy_flags[table_n] | flags1))
+ {
+ for (int row = 0; row < 3; row++)
+ {
+ ImGui::TableNextRow();
+ ImGui::TableNextColumn(); ImGui::Text("AAAA");
+ ImGui::TableNextColumn(); ImGui::Text("BBBBBBBB");
+ ImGui::TableNextColumn(); ImGui::Text("CCCCCCCCCCCC");
+ }
+ ImGui::EndTable();
+ }
+ ImGui::PopID();
+ }
+
+ ImGui::Spacing();
+ ImGui::TextUnformatted("Advanced");
+ ImGui::SameLine();
+ HelpMarker("This section allows you to interact and see the effect of various sizing policies depending on whether Scroll is enabled and the contents of your columns.");
+
+ enum ContentsType { CT_ShowWidth, CT_ShortText, CT_LongText, CT_Button, CT_FillButton, CT_InputText };
+ static ImGuiTableFlags flags = ImGuiTableFlags_ScrollY | ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_Resizable;
+ static int contents_type = CT_ShowWidth;
+ static int column_count = 3;
+
+ PushStyleCompact();
+ ImGui::PushID("Advanced");
+ ImGui::PushItemWidth(TEXT_BASE_WIDTH * 30);
+ EditTableSizingFlags(&flags);
+ ImGui::Combo("Contents", &contents_type, "Show width\0Short Text\0Long Text\0Button\0Fill Button\0InputText\0");
+ if (contents_type == CT_FillButton)
+ {
+ ImGui::SameLine();
+ HelpMarker("Be mindful that using right-alignment (e.g. size.x = -FLT_MIN) creates a feedback loop where contents width can feed into auto-column width can feed into contents width.");
+ }
+ ImGui::DragInt("Columns", &column_count, 0.1f, 1, 64, "%d", ImGuiSliderFlags_AlwaysClamp);
+ ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags, ImGuiTableFlags_Resizable);
+ ImGui::CheckboxFlags("ImGuiTableFlags_PreciseWidths", &flags, ImGuiTableFlags_PreciseWidths);
+ ImGui::SameLine(); HelpMarker("Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth.");
+ ImGui::CheckboxFlags("ImGuiTableFlags_ScrollX", &flags, ImGuiTableFlags_ScrollX);
+ ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", &flags, ImGuiTableFlags_ScrollY);
+ ImGui::CheckboxFlags("ImGuiTableFlags_NoClip", &flags, ImGuiTableFlags_NoClip);
+ ImGui::PopItemWidth();
+ ImGui::PopID();
+ PopStyleCompact();
+
+ if (ImGui::BeginTable("table2", column_count, flags, ImVec2(0.0f, TEXT_BASE_HEIGHT * 7)))
+ {
+ for (int cell = 0; cell < 10 * column_count; cell++)
+ {
+ ImGui::TableNextColumn();
+ int column = ImGui::TableGetColumnIndex();
+ int row = ImGui::TableGetRowIndex();
+
+ ImGui::PushID(cell);
+ char label[32];
+ static char text_buf[32] = "";
+ sprintf(label, "Hello %d,%d", column, row);
+ switch (contents_type)
+ {
+ case CT_ShortText: ImGui::TextUnformatted(label); break;
+ case CT_LongText: ImGui::Text("Some %s text %d,%d\nOver two lines..", column == 0 ? "long" : "longeeer", column, row); break;
+ case CT_ShowWidth: ImGui::Text("W: %.1f", ImGui::GetContentRegionAvail().x); break;
+ case CT_Button: ImGui::Button(label); break;
+ case CT_FillButton: ImGui::Button(label, ImVec2(-FLT_MIN, 0.0f)); break;
+ case CT_InputText: ImGui::SetNextItemWidth(-FLT_MIN); ImGui::InputText("##", text_buf, IM_ARRAYSIZE(text_buf)); break;
+ }
+ ImGui::PopID();
+ }
+ ImGui::EndTable();
+ }
+ ImGui::TreePop();
+ }
+
+ if (open_action != -1)
+ ImGui::SetNextItemOpen(open_action != 0);
+ if (ImGui::TreeNode("Vertical scrolling, with clipping"))
+ {
+ HelpMarker("Here we activate ScrollY, which will create a child window container to allow hosting scrollable contents.\n\nWe also demonstrate using ImGuiListClipper to virtualize the submission of many items.");
+ static ImGuiTableFlags flags = ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable;
+
+ PushStyleCompact();
+ ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", &flags, ImGuiTableFlags_ScrollY);
+ PopStyleCompact();
+
+ // When using ScrollX or ScrollY we need to specify a size for our table container!
+ // Otherwise by default the table will fit all available space, like a BeginChild() call.
+ ImVec2 outer_size = ImVec2(0.0f, TEXT_BASE_HEIGHT * 8);
+ if (ImGui::BeginTable("table_scrolly", 3, flags, outer_size))
+ {
+ ImGui::TableSetupScrollFreeze(0, 1); // Make top row always visible
+ ImGui::TableSetupColumn("One", ImGuiTableColumnFlags_None);
+ ImGui::TableSetupColumn("Two", ImGuiTableColumnFlags_None);
+ ImGui::TableSetupColumn("Three", ImGuiTableColumnFlags_None);
+ ImGui::TableHeadersRow();
+
+ // Demonstrate using clipper for large vertical lists
+ ImGuiListClipper clipper;
+ clipper.Begin(1000);
+ while (clipper.Step())
+ {
+ for (int row = clipper.DisplayStart; row < clipper.DisplayEnd; row++)
+ {
+ ImGui::TableNextRow();
+ for (int column = 0; column < 3; column++)
+ {
+ ImGui::TableSetColumnIndex(column);
+ ImGui::Text("Hello %d,%d", column, row);
+ }
+ }
+ }
+ ImGui::EndTable();
+ }
+ ImGui::TreePop();
+ }
+
+ if (open_action != -1)
+ ImGui::SetNextItemOpen(open_action != 0);
+ if (ImGui::TreeNode("Horizontal scrolling"))
+ {
+ HelpMarker(
+ "When ScrollX is enabled, the default sizing policy becomes ImGuiTableFlags_SizingFixedFit, "
+ "as automatically stretching columns doesn't make much sense with horizontal scrolling.\n\n"
+ "Also note that as of the current version, you will almost always want to enable ScrollY along with ScrollX,"
+ "because the container window won't automatically extend vertically to fix contents (this may be improved in future versions).");
+ static ImGuiTableFlags flags = ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable;
+ static int freeze_cols = 1;
+ static int freeze_rows = 1;
+
+ PushStyleCompact();
+ ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags, ImGuiTableFlags_Resizable);
+ ImGui::CheckboxFlags("ImGuiTableFlags_ScrollX", &flags, ImGuiTableFlags_ScrollX);
+ ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", &flags, ImGuiTableFlags_ScrollY);
+ ImGui::SetNextItemWidth(ImGui::GetFrameHeight());
+ ImGui::DragInt("freeze_cols", &freeze_cols, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput);
+ ImGui::SetNextItemWidth(ImGui::GetFrameHeight());
+ ImGui::DragInt("freeze_rows", &freeze_rows, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput);
+ PopStyleCompact();
+
+ // When using ScrollX or ScrollY we need to specify a size for our table container!
+ // Otherwise by default the table will fit all available space, like a BeginChild() call.
+ ImVec2 outer_size = ImVec2(0.0f, TEXT_BASE_HEIGHT * 8);
+ if (ImGui::BeginTable("table_scrollx", 7, flags, outer_size))
+ {
+ ImGui::TableSetupScrollFreeze(freeze_cols, freeze_rows);
+ ImGui::TableSetupColumn("Line #", ImGuiTableColumnFlags_NoHide); // Make the first column not hideable to match our use of TableSetupScrollFreeze()
+ ImGui::TableSetupColumn("One");
+ ImGui::TableSetupColumn("Two");
+ ImGui::TableSetupColumn("Three");
+ ImGui::TableSetupColumn("Four");
+ ImGui::TableSetupColumn("Five");
+ ImGui::TableSetupColumn("Six");
+ ImGui::TableHeadersRow();
+ for (int row = 0; row < 20; row++)
+ {
+ ImGui::TableNextRow();
+ for (int column = 0; column < 7; column++)
+ {
+ // Both TableNextColumn() and TableSetColumnIndex() return true when a column is visible or performing width measurement.
+ // Because here we know that:
+ // - A) all our columns are contributing the same to row height
+ // - B) column 0 is always visible,
+ // We only always submit this one column and can skip others.
+ // More advanced per-column clipping behaviors may benefit from polling the status flags via TableGetColumnFlags().
+ if (!ImGui::TableSetColumnIndex(column) && column > 0)
+ continue;
+ if (column == 0)
+ ImGui::Text("Line %d", row);
+ else
+ ImGui::Text("Hello world %d,%d", column, row);
+ }
+ }
+ ImGui::EndTable();
+ }
+
+ ImGui::Spacing();
+ ImGui::TextUnformatted("Stretch + ScrollX");
+ ImGui::SameLine();
+ HelpMarker(
+ "Showcase using Stretch columns + ScrollX together: "
+ "this is rather unusual and only makes sense when specifying an 'inner_width' for the table!\n"
+ "Without an explicit value, inner_width is == outer_size.x and therefore using Stretch columns + ScrollX together doesn't make sense.");
+ static ImGuiTableFlags flags2 = ImGuiTableFlags_SizingStretchSame | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_RowBg | ImGuiTableFlags_ContextMenuInBody;
+ static float inner_width = 1000.0f;
+ PushStyleCompact();
+ ImGui::PushID("flags3");
+ ImGui::PushItemWidth(TEXT_BASE_WIDTH * 30);
+ ImGui::CheckboxFlags("ImGuiTableFlags_ScrollX", &flags2, ImGuiTableFlags_ScrollX);
+ ImGui::DragFloat("inner_width", &inner_width, 1.0f, 0.0f, FLT_MAX, "%.1f");
+ ImGui::PopItemWidth();
+ ImGui::PopID();
+ PopStyleCompact();
+ if (ImGui::BeginTable("table2", 7, flags2, outer_size, inner_width))
+ {
+ for (int cell = 0; cell < 20 * 7; cell++)
+ {
+ ImGui::TableNextColumn();
+ ImGui::Text("Hello world %d,%d", ImGui::TableGetColumnIndex(), ImGui::TableGetRowIndex());
+ }
+ ImGui::EndTable();
+ }
+ ImGui::TreePop();
+ }
+
+ if (open_action != -1)
+ ImGui::SetNextItemOpen(open_action != 0);
+ if (ImGui::TreeNode("Columns flags"))
+ {
+ // Create a first table just to show all the options/flags we want to make visible in our example!
+ const int column_count = 3;
+ const char* column_names[column_count] = { "One", "Two", "Three" };
+ static ImGuiTableColumnFlags column_flags[column_count] = { ImGuiTableColumnFlags_DefaultSort, ImGuiTableColumnFlags_None, ImGuiTableColumnFlags_DefaultHide };
+ static ImGuiTableColumnFlags column_flags_out[column_count] = { 0, 0, 0 }; // Output from TableGetColumnFlags()
+
+ if (ImGui::BeginTable("table_columns_flags_checkboxes", column_count, ImGuiTableFlags_None))
+ {
+ PushStyleCompact();
+ for (int column = 0; column < column_count; column++)
+ {
+ ImGui::TableNextColumn();
+ ImGui::PushID(column);
+ ImGui::AlignTextToFramePadding(); // FIXME-TABLE: Workaround for wrong text baseline propagation
+ ImGui::Text("'%s'", column_names[column]);
+ ImGui::Spacing();
+ ImGui::Text("Input flags:");
+ EditTableColumnsFlags(&column_flags[column]);
+ ImGui::Spacing();
+ ImGui::Text("Output flags:");
+ ShowTableColumnsStatusFlags(column_flags_out[column]);
+ ImGui::PopID();
+ }
+ PopStyleCompact();
+ ImGui::EndTable();
+ }
+
+ // Create the real table we care about for the example!
+ // We use a scrolling table to be able to showcase the difference between the _IsEnabled and _IsVisible flags above, otherwise in
+ // a non-scrolling table columns are always visible (unless using ImGuiTableFlags_NoKeepColumnsVisible + resizing the parent window down)
+ const ImGuiTableFlags flags
+ = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY
+ | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV
+ | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Sortable;
+ ImVec2 outer_size = ImVec2(0.0f, TEXT_BASE_HEIGHT * 9);
+ if (ImGui::BeginTable("table_columns_flags", column_count, flags, outer_size))
+ {
+ for (int column = 0; column < column_count; column++)
+ ImGui::TableSetupColumn(column_names[column], column_flags[column]);
+ ImGui::TableHeadersRow();
+ for (int column = 0; column < column_count; column++)
+ column_flags_out[column] = ImGui::TableGetColumnFlags(column);
+ float indent_step = (float)((int)TEXT_BASE_WIDTH / 2);
+ for (int row = 0; row < 8; row++)
+ {
+ ImGui::Indent(indent_step); // Add some indentation to demonstrate usage of per-column IndentEnable/IndentDisable flags.
+ ImGui::TableNextRow();
+ for (int column = 0; column < column_count; column++)
+ {
+ ImGui::TableSetColumnIndex(column);
+ ImGui::Text("%s %s", (column == 0) ? "Indented" : "Hello", ImGui::TableGetColumnName(column));
+ }
+ }
+ ImGui::Unindent(indent_step * 8.0f);
+
+ ImGui::EndTable();
+ }
+ ImGui::TreePop();
+ }
+
+ if (open_action != -1)
+ ImGui::SetNextItemOpen(open_action != 0);
+ if (ImGui::TreeNode("Columns widths"))
+ {
+ HelpMarker("Using TableSetupColumn() to setup default width.");
+
+ static ImGuiTableFlags flags1 = ImGuiTableFlags_Borders | ImGuiTableFlags_NoBordersInBodyUntilResize;
+ PushStyleCompact();
+ ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags1, ImGuiTableFlags_Resizable);
+ ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBodyUntilResize", &flags1, ImGuiTableFlags_NoBordersInBodyUntilResize);
+ PopStyleCompact();
+ if (ImGui::BeginTable("table1", 3, flags1))
+ {
+ // We could also set ImGuiTableFlags_SizingFixedFit on the table and all columns will default to ImGuiTableColumnFlags_WidthFixed.
+ ImGui::TableSetupColumn("one", ImGuiTableColumnFlags_WidthFixed, 100.0f); // Default to 100.0f
+ ImGui::TableSetupColumn("two", ImGuiTableColumnFlags_WidthFixed, 200.0f); // Default to 200.0f
+ ImGui::TableSetupColumn("three", ImGuiTableColumnFlags_WidthFixed); // Default to auto
+ ImGui::TableHeadersRow();
+ for (int row = 0; row < 4; row++)
+ {
+ ImGui::TableNextRow();
+ for (int column = 0; column < 3; column++)
+ {
+ ImGui::TableSetColumnIndex(column);
+ if (row == 0)
+ ImGui::Text("(w: %5.1f)", ImGui::GetContentRegionAvail().x);
+ else
+ ImGui::Text("Hello %d,%d", column, row);
+ }
+ }
+ ImGui::EndTable();
+ }
+
+ HelpMarker("Using TableSetupColumn() to setup explicit width.\n\nUnless _NoKeepColumnsVisible is set, fixed columns with set width may still be shrunk down if there's not enough space in the host.");
+
+ static ImGuiTableFlags flags2 = ImGuiTableFlags_None;
+ PushStyleCompact();
+ ImGui::CheckboxFlags("ImGuiTableFlags_NoKeepColumnsVisible", &flags2, ImGuiTableFlags_NoKeepColumnsVisible);
+ ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", &flags2, ImGuiTableFlags_BordersInnerV);
+ ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", &flags2, ImGuiTableFlags_BordersOuterV);
+ PopStyleCompact();
+ if (ImGui::BeginTable("table2", 4, flags2))
+ {
+ // We could also set ImGuiTableFlags_SizingFixedFit on the table and all columns will default to ImGuiTableColumnFlags_WidthFixed.
+ ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, 100.0f);
+ ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 15.0f);
+ ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 30.0f);
+ ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 15.0f);
+ for (int row = 0; row < 5; row++)
+ {
+ ImGui::TableNextRow();
+ for (int column = 0; column < 4; column++)
+ {
+ ImGui::TableSetColumnIndex(column);
+ if (row == 0)
+ ImGui::Text("(w: %5.1f)", ImGui::GetContentRegionAvail().x);
+ else
+ ImGui::Text("Hello %d,%d", column, row);
+ }
+ }
+ ImGui::EndTable();
+ }
+ ImGui::TreePop();
+ }
+
+ if (open_action != -1)
+ ImGui::SetNextItemOpen(open_action != 0);
+ if (ImGui::TreeNode("Nested tables"))
+ {
+ HelpMarker("This demonstrate embedding a table into another table cell.");
+
+ if (ImGui::BeginTable("table_nested1", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable))
+ {
+ ImGui::TableSetupColumn("A0");
+ ImGui::TableSetupColumn("A1");
+ ImGui::TableHeadersRow();
+
+ ImGui::TableNextColumn();
+ ImGui::Text("A0 Row 0");
+ {
+ float rows_height = TEXT_BASE_HEIGHT * 2;
+ if (ImGui::BeginTable("table_nested2", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable))
+ {
+ ImGui::TableSetupColumn("B0");
+ ImGui::TableSetupColumn("B1");
+ ImGui::TableHeadersRow();
+
+ ImGui::TableNextRow(ImGuiTableRowFlags_None, rows_height);
+ ImGui::TableNextColumn();
+ ImGui::Text("B0 Row 0");
+ ImGui::TableNextColumn();
+ ImGui::Text("B1 Row 0");
+ ImGui::TableNextRow(ImGuiTableRowFlags_None, rows_height);
+ ImGui::TableNextColumn();
+ ImGui::Text("B0 Row 1");
+ ImGui::TableNextColumn();
+ ImGui::Text("B1 Row 1");
+
+ ImGui::EndTable();
+ }
+ }
+ ImGui::TableNextColumn(); ImGui::Text("A1 Row 0");
+ ImGui::TableNextColumn(); ImGui::Text("A0 Row 1");
+ ImGui::TableNextColumn(); ImGui::Text("A1 Row 1");
+ ImGui::EndTable();
+ }
+ ImGui::TreePop();
+ }
+
+ if (open_action != -1)
+ ImGui::SetNextItemOpen(open_action != 0);
+ if (ImGui::TreeNode("Row height"))
+ {
+ HelpMarker("You can pass a 'min_row_height' to TableNextRow().\n\nRows are padded with 'style.CellPadding.y' on top and bottom, so effectively the minimum row height will always be >= 'style.CellPadding.y * 2.0f'.\n\nWe cannot honor a _maximum_ row height as that would requires a unique clipping rectangle per row.");
+ if (ImGui::BeginTable("table_row_height", 1, ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersInnerV))
+ {
+ for (int row = 0; row < 10; row++)
+ {
+ float min_row_height = (float)(int)(TEXT_BASE_HEIGHT * 0.30f * row);
+ ImGui::TableNextRow(ImGuiTableRowFlags_None, min_row_height);
+ ImGui::TableNextColumn();
+ ImGui::Text("min_row_height = %.2f", min_row_height);
+ }
+ ImGui::EndTable();
+ }
+ ImGui::TreePop();
+ }
+
+ if (open_action != -1)
+ ImGui::SetNextItemOpen(open_action != 0);
+ if (ImGui::TreeNode("Outer size"))
+ {
+ // Showcasing use of ImGuiTableFlags_NoHostExtendX and ImGuiTableFlags_NoHostExtendY
+ // Important to that note how the two flags have slightly different behaviors!
+ ImGui::Text("Using NoHostExtendX and NoHostExtendY:");
+ PushStyleCompact();
+ static ImGuiTableFlags flags = ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_ContextMenuInBody | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_NoHostExtendX;
+ ImGui::CheckboxFlags("ImGuiTableFlags_NoHostExtendX", &flags, ImGuiTableFlags_NoHostExtendX);
+ ImGui::SameLine(); HelpMarker("Make outer width auto-fit to columns, overriding outer_size.x value.\n\nOnly available when ScrollX/ScrollY are disabled and Stretch columns are not used.");
+ ImGui::CheckboxFlags("ImGuiTableFlags_NoHostExtendY", &flags, ImGuiTableFlags_NoHostExtendY);
+ ImGui::SameLine(); HelpMarker("Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit).\n\nOnly available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible.");
+ PopStyleCompact();
+
+ ImVec2 outer_size = ImVec2(0.0f, TEXT_BASE_HEIGHT * 5.5f);
+ if (ImGui::BeginTable("table1", 3, flags, outer_size))
+ {
+ for (int row = 0; row < 10; row++)
+ {
+ ImGui::TableNextRow();
+ for (int column = 0; column < 3; column++)
+ {
+ ImGui::TableNextColumn();
+ ImGui::Text("Cell %d,%d", column, row);
+ }
+ }
+ ImGui::EndTable();
+ }
+ ImGui::SameLine();
+ ImGui::Text("Hello!");
+
+ ImGui::Spacing();
+
+ ImGui::Text("Using explicit size:");
+ if (ImGui::BeginTable("table2", 3, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg, ImVec2(TEXT_BASE_WIDTH * 30, 0.0f)))
+ {
+ for (int row = 0; row < 5; row++)
+ {
+ ImGui::TableNextRow();
+ for (int column = 0; column < 3; column++)
+ {
+ ImGui::TableNextColumn();
+ ImGui::Text("Cell %d,%d", column, row);
+ }
+ }
+ ImGui::EndTable();
+ }
+ ImGui::SameLine();
+ if (ImGui::BeginTable("table3", 3, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg, ImVec2(TEXT_BASE_WIDTH * 30, 0.0f)))
+ {
+ for (int row = 0; row < 3; row++)
+ {
+ ImGui::TableNextRow(0, TEXT_BASE_HEIGHT * 1.5f);
+ for (int column = 0; column < 3; column++)
+ {
+ ImGui::TableNextColumn();
+ ImGui::Text("Cell %d,%d", column, row);
+ }
+ }
+ ImGui::EndTable();
+ }
+
+ ImGui::TreePop();
+ }
+
+ if (open_action != -1)
+ ImGui::SetNextItemOpen(open_action != 0);
+ if (ImGui::TreeNode("Background color"))
+ {
+ static ImGuiTableFlags flags = ImGuiTableFlags_RowBg;
+ static int row_bg_type = 1;
+ static int row_bg_target = 1;
+ static int cell_bg_type = 1;
+
+ PushStyleCompact();
+ ImGui::CheckboxFlags("ImGuiTableFlags_Borders", &flags, ImGuiTableFlags_Borders);
+ ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", &flags, ImGuiTableFlags_RowBg);
+ ImGui::SameLine(); HelpMarker("ImGuiTableFlags_RowBg automatically sets RowBg0 to alternative colors pulled from the Style.");
+ ImGui::Combo("row bg type", (int*)&row_bg_type, "None\0Red\0Gradient\0");
+ ImGui::Combo("row bg target", (int*)&row_bg_target, "RowBg0\0RowBg1\0"); ImGui::SameLine(); HelpMarker("Target RowBg0 to override the alternating odd/even colors,\nTarget RowBg1 to blend with them.");
+ ImGui::Combo("cell bg type", (int*)&cell_bg_type, "None\0Blue\0"); ImGui::SameLine(); HelpMarker("We are colorizing cells to B1->C2 here.");
+ IM_ASSERT(row_bg_type >= 0 && row_bg_type <= 2);
+ IM_ASSERT(row_bg_target >= 0 && row_bg_target <= 1);
+ IM_ASSERT(cell_bg_type >= 0 && cell_bg_type <= 1);
+ PopStyleCompact();
+
+ if (ImGui::BeginTable("table1", 5, flags))
+ {
+ for (int row = 0; row < 6; row++)
+ {
+ ImGui::TableNextRow();
+
+ // Demonstrate setting a row background color with 'ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBgX, ...)'
+ // We use a transparent color so we can see the one behind in case our target is RowBg1 and RowBg0 was already targeted by the ImGuiTableFlags_RowBg flag.
+ if (row_bg_type != 0)
+ {
+ ImU32 row_bg_color = ImGui::GetColorU32(row_bg_type == 1 ? ImVec4(0.7f, 0.3f, 0.3f, 0.65f) : ImVec4(0.2f + row * 0.1f, 0.2f, 0.2f, 0.65f)); // Flat or Gradient?
+ ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0 + row_bg_target, row_bg_color);
+ }
+
+ // Fill cells
+ for (int column = 0; column < 5; column++)
+ {
+ ImGui::TableSetColumnIndex(column);
+ ImGui::Text("%c%c", 'A' + row, '0' + column);
+
+ // Change background of Cells B1->C2
+ // Demonstrate setting a cell background color with 'ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, ...)'
+ // (the CellBg color will be blended over the RowBg and ColumnBg colors)
+ // We can also pass a column number as a third parameter to TableSetBgColor() and do this outside the column loop.
+ if (row >= 1 && row <= 2 && column >= 1 && column <= 2 && cell_bg_type == 1)
+ {
+ ImU32 cell_bg_color = ImGui::GetColorU32(ImVec4(0.3f, 0.3f, 0.7f, 0.65f));
+ ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, cell_bg_color);
+ }
+ }
+ }
+ ImGui::EndTable();
+ }
+ ImGui::TreePop();
+ }
+
+ if (open_action != -1)
+ ImGui::SetNextItemOpen(open_action != 0);
+ if (ImGui::TreeNode("Tree view"))
+ {
+ static ImGuiTableFlags flags = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg | ImGuiTableFlags_NoBordersInBody;
+
+ if (ImGui::BeginTable("3ways", 3, flags))
+ {
+ // The first column will use the default _WidthStretch when ScrollX is Off and _WidthFixed when ScrollX is On
+ ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_NoHide);
+ ImGui::TableSetupColumn("Size", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 12.0f);
+ ImGui::TableSetupColumn("Type", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 18.0f);
+ ImGui::TableHeadersRow();
+
+ // Simple storage to output a dummy file-system.
+ struct MyTreeNode
+ {
+ const char* Name;
+ const char* Type;
+ int Size;
+ int ChildIdx;
+ int ChildCount;
+ static void DisplayNode(const MyTreeNode* node, const MyTreeNode* all_nodes)
+ {
+ ImGui::TableNextRow();
+ ImGui::TableNextColumn();
+ const bool is_folder = (node->ChildCount > 0);
+ if (is_folder)
+ {
+ bool open = ImGui::TreeNodeEx(node->Name, ImGuiTreeNodeFlags_SpanFullWidth);
+ ImGui::TableNextColumn();
+ ImGui::TextDisabled("--");
+ ImGui::TableNextColumn();
+ ImGui::TextUnformatted(node->Type);
+ if (open)
+ {
+ for (int child_n = 0; child_n < node->ChildCount; child_n++)
+ DisplayNode(&all_nodes[node->ChildIdx + child_n], all_nodes);
+ ImGui::TreePop();
+ }
+ }
+ else
+ {
+ ImGui::TreeNodeEx(node->Name, ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_Bullet | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_SpanFullWidth);
+ ImGui::TableNextColumn();
+ ImGui::Text("%d", node->Size);
+ ImGui::TableNextColumn();
+ ImGui::TextUnformatted(node->Type);
+ }
+ }
+ };
+ static const MyTreeNode nodes[] =
+ {
+ { "Root", "Folder", -1, 1, 3 }, // 0
+ { "Music", "Folder", -1, 4, 2 }, // 1
+ { "Textures", "Folder", -1, 6, 3 }, // 2
+ { "desktop.ini", "System file", 1024, -1,-1 }, // 3
+ { "File1_a.wav", "Audio file", 123000, -1,-1 }, // 4
+ { "File1_b.wav", "Audio file", 456000, -1,-1 }, // 5
+ { "Image001.png", "Image file", 203128, -1,-1 }, // 6
+ { "Copy of Image001.png", "Image file", 203256, -1,-1 }, // 7
+ { "Copy of Image001 (Final2).png","Image file", 203512, -1,-1 }, // 8
+ };
+
+ MyTreeNode::DisplayNode(&nodes[0], nodes);
+
+ ImGui::EndTable();
+ }
+ ImGui::TreePop();
+ }
+
+ if (open_action != -1)
+ ImGui::SetNextItemOpen(open_action != 0);
+ if (ImGui::TreeNode("Item width"))
+ {
+ HelpMarker(
+ "Showcase using PushItemWidth() and how it is preserved on a per-column basis.\n\n"
+ "Note that on auto-resizing non-resizable fixed columns, querying the content width for e.g. right-alignment doesn't make sense.");
+ if (ImGui::BeginTable("table_item_width", 3, ImGuiTableFlags_Borders))
+ {
+ ImGui::TableSetupColumn("small");
+ ImGui::TableSetupColumn("half");
+ ImGui::TableSetupColumn("right-align");
+ ImGui::TableHeadersRow();
+
+ for (int row = 0; row < 3; row++)
+ {
+ ImGui::TableNextRow();
+ if (row == 0)
+ {
+ // Setup ItemWidth once (instead of setting up every time, which is also possible but less efficient)
+ ImGui::TableSetColumnIndex(0);
+ ImGui::PushItemWidth(TEXT_BASE_WIDTH * 3.0f); // Small
+ ImGui::TableSetColumnIndex(1);
+ ImGui::PushItemWidth(-ImGui::GetContentRegionAvail().x * 0.5f);
+ ImGui::TableSetColumnIndex(2);
+ ImGui::PushItemWidth(-FLT_MIN); // Right-aligned
+ }
+
+ // Draw our contents
+ static float dummy_f = 0.0f;
+ ImGui::PushID(row);
+ ImGui::TableSetColumnIndex(0);
+ ImGui::SliderFloat("float0", &dummy_f, 0.0f, 1.0f);
+ ImGui::TableSetColumnIndex(1);
+ ImGui::SliderFloat("float1", &dummy_f, 0.0f, 1.0f);
+ ImGui::TableSetColumnIndex(2);
+ ImGui::SliderFloat("float2", &dummy_f, 0.0f, 1.0f);
+ ImGui::PopID();
+ }
+ ImGui::EndTable();
+ }
+ ImGui::TreePop();
+ }
+
+ // Demonstrate using TableHeader() calls instead of TableHeadersRow()
+ if (open_action != -1)
+ ImGui::SetNextItemOpen(open_action != 0);
+ if (ImGui::TreeNode("Custom headers"))
+ {
+ const int COLUMNS_COUNT = 3;
+ if (ImGui::BeginTable("table_custom_headers", COLUMNS_COUNT, ImGuiTableFlags_Borders | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable))
+ {
+ ImGui::TableSetupColumn("Apricot");
+ ImGui::TableSetupColumn("Banana");
+ ImGui::TableSetupColumn("Cherry");
+
+ // Dummy entire-column selection storage
+ // FIXME: It would be nice to actually demonstrate full-featured selection using those checkbox.
+ static bool column_selected[3] = {};
+
+ // Instead of calling TableHeadersRow() we'll submit custom headers ourselves
+ ImGui::TableNextRow(ImGuiTableRowFlags_Headers);
+ for (int column = 0; column < COLUMNS_COUNT; column++)
+ {
+ ImGui::TableSetColumnIndex(column);
+ const char* column_name = ImGui::TableGetColumnName(column); // Retrieve name passed to TableSetupColumn()
+ ImGui::PushID(column);
+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
+ ImGui::Checkbox("##checkall", &column_selected[column]);
+ ImGui::PopStyleVar();
+ ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x);
+ ImGui::TableHeader(column_name);
+ ImGui::PopID();
+ }
+
+ for (int row = 0; row < 5; row++)
+ {
+ ImGui::TableNextRow();
+ for (int column = 0; column < 3; column++)
+ {
+ char buf[32];
+ sprintf(buf, "Cell %d,%d", column, row);
+ ImGui::TableSetColumnIndex(column);
+ ImGui::Selectable(buf, column_selected[column]);
+ }
+ }
+ ImGui::EndTable();
+ }
+ ImGui::TreePop();
+ }
+
+ // Demonstrate creating custom context menus inside columns, while playing it nice with context menus provided by TableHeadersRow()/TableHeader()
+ if (open_action != -1)
+ ImGui::SetNextItemOpen(open_action != 0);
+ if (ImGui::TreeNode("Context menus"))
+ {
+ HelpMarker("By default, right-clicking over a TableHeadersRow()/TableHeader() line will open the default context-menu.\nUsing ImGuiTableFlags_ContextMenuInBody we also allow right-clicking over columns body.");
+ static ImGuiTableFlags flags1 = ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Borders | ImGuiTableFlags_ContextMenuInBody;
+
+ PushStyleCompact();
+ ImGui::CheckboxFlags("ImGuiTableFlags_ContextMenuInBody", &flags1, ImGuiTableFlags_ContextMenuInBody);
+ PopStyleCompact();
+
+ // Context Menus: first example
+ // [1.1] Right-click on the TableHeadersRow() line to open the default table context menu.
+ // [1.2] Right-click in columns also open the default table context menu (if ImGuiTableFlags_ContextMenuInBody is set)
+ const int COLUMNS_COUNT = 3;
+ if (ImGui::BeginTable("table_context_menu", COLUMNS_COUNT, flags1))
+ {
+ ImGui::TableSetupColumn("One");
+ ImGui::TableSetupColumn("Two");
+ ImGui::TableSetupColumn("Three");
+
+ // [1.1]] Right-click on the TableHeadersRow() line to open the default table context menu.
+ ImGui::TableHeadersRow();
+
+ // Submit dummy contents
+ for (int row = 0; row < 4; row++)
+ {
+ ImGui::TableNextRow();
+ for (int column = 0; column < COLUMNS_COUNT; column++)
+ {
+ ImGui::TableSetColumnIndex(column);
+ ImGui::Text("Cell %d,%d", column, row);
+ }
+ }
+ ImGui::EndTable();
+ }
+
+ // Context Menus: second example
+ // [2.1] Right-click on the TableHeadersRow() line to open the default table context menu.
+ // [2.2] Right-click on the ".." to open a custom popup
+ // [2.3] Right-click in columns to open another custom popup
+ HelpMarker("Demonstrate mixing table context menu (over header), item context button (over button) and custom per-colum context menu (over column body).");
+ ImGuiTableFlags flags2 = ImGuiTableFlags_Resizable | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Borders;
+ if (ImGui::BeginTable("table_context_menu_2", COLUMNS_COUNT, flags2))
+ {
+ ImGui::TableSetupColumn("One");
+ ImGui::TableSetupColumn("Two");
+ ImGui::TableSetupColumn("Three");
+
+ // [2.1] Right-click on the TableHeadersRow() line to open the default table context menu.
+ ImGui::TableHeadersRow();
+ for (int row = 0; row < 4; row++)
+ {
+ ImGui::TableNextRow();
+ for (int column = 0; column < COLUMNS_COUNT; column++)
+ {
+ // Submit dummy contents
+ ImGui::TableSetColumnIndex(column);
+ ImGui::Text("Cell %d,%d", column, row);
+ ImGui::SameLine();
+
+ // [2.2] Right-click on the ".." to open a custom popup
+ ImGui::PushID(row * COLUMNS_COUNT + column);
+ ImGui::SmallButton("..");
+ if (ImGui::BeginPopupContextItem())
+ {
+ ImGui::Text("This is the popup for Button(\"..\") in Cell %d,%d", column, row);
+ if (ImGui::Button("Close"))
+ ImGui::CloseCurrentPopup();
+ ImGui::EndPopup();
+ }
+ ImGui::PopID();
+ }
+ }
+
+ // [2.3] Right-click anywhere in columns to open another custom popup
+ // (instead of testing for !IsAnyItemHovered() we could also call OpenPopup() with ImGuiPopupFlags_NoOpenOverExistingPopup
+ // to manage popup priority as the popups triggers, here "are we hovering a column" are overlapping)
+ int hovered_column = -1;
+ for (int column = 0; column < COLUMNS_COUNT + 1; column++)
+ {
+ ImGui::PushID(column);
+ if (ImGui::TableGetColumnFlags(column) & ImGuiTableColumnFlags_IsHovered)
+ hovered_column = column;
+ if (hovered_column == column && !ImGui::IsAnyItemHovered() && ImGui::IsMouseReleased(1))
+ ImGui::OpenPopup("MyPopup");
+ if (ImGui::BeginPopup("MyPopup"))
+ {
+ if (column == COLUMNS_COUNT)
+ ImGui::Text("This is a custom popup for unused space after the last column.");
+ else
+ ImGui::Text("This is a custom popup for Column %d", column);
+ if (ImGui::Button("Close"))
+ ImGui::CloseCurrentPopup();
+ ImGui::EndPopup();
+ }
+ ImGui::PopID();
+ }
+
+ ImGui::EndTable();
+ ImGui::Text("Hovered column: %d", hovered_column);
+ }
+ ImGui::TreePop();
+ }
+
+ // Demonstrate creating multiple tables with the same ID
+ if (open_action != -1)
+ ImGui::SetNextItemOpen(open_action != 0);
+ if (ImGui::TreeNode("Synced instances"))
+ {
+ HelpMarker("Multiple tables with the same identifier will share their settings, width, visibility, order etc.");
+ for (int n = 0; n < 3; n++)
+ {
+ char buf[32];
+ sprintf(buf, "Synced Table %d", n);
+ bool open = ImGui::CollapsingHeader(buf, ImGuiTreeNodeFlags_DefaultOpen);
+ if (open && ImGui::BeginTable("Table", 3, ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Borders | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_NoSavedSettings))
+ {
+ ImGui::TableSetupColumn("One");
+ ImGui::TableSetupColumn("Two");
+ ImGui::TableSetupColumn("Three");
+ ImGui::TableHeadersRow();
+ for (int cell = 0; cell < 9; cell++)
+ {
+ ImGui::TableNextColumn();
+ ImGui::Text("this cell %d", cell);
+ }
+ ImGui::EndTable();
+ }
+ }
+ ImGui::TreePop();
+ }
+
+ // Demonstrate using Sorting facilities
+ // This is a simplified version of the "Advanced" example, where we mostly focus on the code necessary to handle sorting.
+ // Note that the "Advanced" example also showcase manually triggering a sort (e.g. if item quantities have been modified)
+ static const char* template_items_names[] =
+ {
+ "Banana", "Apple", "Cherry", "Watermelon", "Grapefruit", "Strawberry", "Mango",
+ "Kiwi", "Orange", "Pineapple", "Blueberry", "Plum", "Coconut", "Pear", "Apricot"
+ };
+ if (open_action != -1)
+ ImGui::SetNextItemOpen(open_action != 0);
+ if (ImGui::TreeNode("Sorting"))
+ {
+ // Create item list
+ static ImVector items;
+ if (items.Size == 0)
+ {
+ items.resize(50, MyItem());
+ for (int n = 0; n < items.Size; n++)
+ {
+ const int template_n = n % IM_ARRAYSIZE(template_items_names);
+ MyItem& item = items[n];
+ item.ID = n;
+ item.Name = template_items_names[template_n];
+ item.Quantity = (n * n - n) % 20; // Assign default quantities
+ }
+ }
+
+ // Options
+ static ImGuiTableFlags flags =
+ ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Sortable | ImGuiTableFlags_SortMulti
+ | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_NoBordersInBody
+ | ImGuiTableFlags_ScrollY;
+ PushStyleCompact();
+ ImGui::CheckboxFlags("ImGuiTableFlags_SortMulti", &flags, ImGuiTableFlags_SortMulti);
+ ImGui::SameLine(); HelpMarker("When sorting is enabled: hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1).");
+ ImGui::CheckboxFlags("ImGuiTableFlags_SortTristate", &flags, ImGuiTableFlags_SortTristate);
+ ImGui::SameLine(); HelpMarker("When sorting is enabled: allow no sorting, disable default sorting. TableGetSortSpecs() may return specs where (SpecsCount == 0).");
+ PopStyleCompact();
+
+ if (ImGui::BeginTable("table_sorting", 4, flags, ImVec2(0.0f, TEXT_BASE_HEIGHT * 15), 0.0f))
+ {
+ // Declare columns
+ // We use the "user_id" parameter of TableSetupColumn() to specify a user id that will be stored in the sort specifications.
+ // This is so our sort function can identify a column given our own identifier. We could also identify them based on their index!
+ // Demonstrate using a mixture of flags among available sort-related flags:
+ // - ImGuiTableColumnFlags_DefaultSort
+ // - ImGuiTableColumnFlags_NoSort / ImGuiTableColumnFlags_NoSortAscending / ImGuiTableColumnFlags_NoSortDescending
+ // - ImGuiTableColumnFlags_PreferSortAscending / ImGuiTableColumnFlags_PreferSortDescending
+ ImGui::TableSetupColumn("ID", ImGuiTableColumnFlags_DefaultSort | ImGuiTableColumnFlags_WidthFixed, 0.0f, MyItemColumnID_ID);
+ ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthFixed, 0.0f, MyItemColumnID_Name);
+ ImGui::TableSetupColumn("Action", ImGuiTableColumnFlags_NoSort | ImGuiTableColumnFlags_WidthFixed, 0.0f, MyItemColumnID_Action);
+ ImGui::TableSetupColumn("Quantity", ImGuiTableColumnFlags_PreferSortDescending | ImGuiTableColumnFlags_WidthStretch, 0.0f, MyItemColumnID_Quantity);
+ ImGui::TableSetupScrollFreeze(0, 1); // Make row always visible
+ ImGui::TableHeadersRow();
+
+ // Sort our data if sort specs have been changed!
+ if (ImGuiTableSortSpecs* sorts_specs = ImGui::TableGetSortSpecs())
+ if (sorts_specs->SpecsDirty)
+ {
+ MyItem::s_current_sort_specs = sorts_specs; // Store in variable accessible by the sort function.
+ if (items.Size > 1)
+ qsort(&items[0], (size_t)items.Size, sizeof(items[0]), MyItem::CompareWithSortSpecs);
+ MyItem::s_current_sort_specs = NULL;
+ sorts_specs->SpecsDirty = false;
+ }
+
+ // Demonstrate using clipper for large vertical lists
+ ImGuiListClipper clipper;
+ clipper.Begin(items.Size);
+ while (clipper.Step())
+ for (int row_n = clipper.DisplayStart; row_n < clipper.DisplayEnd; row_n++)
+ {
+ // Display a data item
+ MyItem* item = &items[row_n];
+ ImGui::PushID(item->ID);
+ ImGui::TableNextRow();
+ ImGui::TableNextColumn();
+ ImGui::Text("%04d", item->ID);
+ ImGui::TableNextColumn();
+ ImGui::TextUnformatted(item->Name);
+ ImGui::TableNextColumn();
+ ImGui::SmallButton("None");
+ ImGui::TableNextColumn();
+ ImGui::Text("%d", item->Quantity);
+ ImGui::PopID();
+ }
+ ImGui::EndTable();
+ }
+ ImGui::TreePop();
+ }
+
+ //ImGui::SetNextItemOpen(true, ImGuiCond_Once); // [DEBUG]
+ if (open_action != -1)
+ ImGui::SetNextItemOpen(open_action != 0);
+ if (ImGui::TreeNode("Advanced"))
+ {
+ static ImGuiTableFlags flags =
+ ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable
+ | ImGuiTableFlags_Sortable | ImGuiTableFlags_SortMulti
+ | ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_NoBordersInBody
+ | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY
+ | ImGuiTableFlags_SizingFixedFit;
+
+ enum ContentsType { CT_Text, CT_Button, CT_SmallButton, CT_FillButton, CT_Selectable, CT_SelectableSpanRow };
+ static int contents_type = CT_SelectableSpanRow;
+ const char* contents_type_names[] = { "Text", "Button", "SmallButton", "FillButton", "Selectable", "Selectable (span row)" };
+ static int freeze_cols = 1;
+ static int freeze_rows = 1;
+ static int items_count = IM_ARRAYSIZE(template_items_names) * 2;
+ static ImVec2 outer_size_value = ImVec2(0.0f, TEXT_BASE_HEIGHT * 12);
+ static float row_min_height = 0.0f; // Auto
+ static float inner_width_with_scroll = 0.0f; // Auto-extend
+ static bool outer_size_enabled = true;
+ static bool show_headers = true;
+ static bool show_wrapped_text = false;
+ //static ImGuiTextFilter filter;
+ //ImGui::SetNextItemOpen(true, ImGuiCond_Once); // FIXME-TABLE: Enabling this results in initial clipped first pass on table which tend to affects column sizing
+ if (ImGui::TreeNode("Options"))
+ {
+ // Make the UI compact because there are so many fields
+ PushStyleCompact();
+ ImGui::PushItemWidth(TEXT_BASE_WIDTH * 28.0f);
+
+ if (ImGui::TreeNodeEx("Features:", ImGuiTreeNodeFlags_DefaultOpen))
+ {
+ ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags, ImGuiTableFlags_Resizable);
+ ImGui::CheckboxFlags("ImGuiTableFlags_Reorderable", &flags, ImGuiTableFlags_Reorderable);
+ ImGui::CheckboxFlags("ImGuiTableFlags_Hideable", &flags, ImGuiTableFlags_Hideable);
+ ImGui::CheckboxFlags("ImGuiTableFlags_Sortable", &flags, ImGuiTableFlags_Sortable);
+ ImGui::CheckboxFlags("ImGuiTableFlags_NoSavedSettings", &flags, ImGuiTableFlags_NoSavedSettings);
+ ImGui::CheckboxFlags("ImGuiTableFlags_ContextMenuInBody", &flags, ImGuiTableFlags_ContextMenuInBody);
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNodeEx("Decorations:", ImGuiTreeNodeFlags_DefaultOpen))
+ {
+ ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", &flags, ImGuiTableFlags_RowBg);
+ ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", &flags, ImGuiTableFlags_BordersV);
+ ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", &flags, ImGuiTableFlags_BordersOuterV);
+ ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", &flags, ImGuiTableFlags_BordersInnerV);
+ ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", &flags, ImGuiTableFlags_BordersH);
+ ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterH", &flags, ImGuiTableFlags_BordersOuterH);
+ ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerH", &flags, ImGuiTableFlags_BordersInnerH);
+ ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBody", &flags, ImGuiTableFlags_NoBordersInBody); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body (borders will always appears in Headers");
+ ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBodyUntilResize", &flags, ImGuiTableFlags_NoBordersInBodyUntilResize); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body until hovered for resize (borders will always appears in Headers)");
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNodeEx("Sizing:", ImGuiTreeNodeFlags_DefaultOpen))
+ {
+ EditTableSizingFlags(&flags);
+ ImGui::SameLine(); HelpMarker("In the Advanced demo we override the policy of each column so those table-wide settings have less effect that typical.");
+ ImGui::CheckboxFlags("ImGuiTableFlags_NoHostExtendX", &flags, ImGuiTableFlags_NoHostExtendX);
+ ImGui::SameLine(); HelpMarker("Make outer width auto-fit to columns, overriding outer_size.x value.\n\nOnly available when ScrollX/ScrollY are disabled and Stretch columns are not used.");
+ ImGui::CheckboxFlags("ImGuiTableFlags_NoHostExtendY", &flags, ImGuiTableFlags_NoHostExtendY);
+ ImGui::SameLine(); HelpMarker("Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit).\n\nOnly available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible.");
+ ImGui::CheckboxFlags("ImGuiTableFlags_NoKeepColumnsVisible", &flags, ImGuiTableFlags_NoKeepColumnsVisible);
+ ImGui::SameLine(); HelpMarker("Only available if ScrollX is disabled.");
+ ImGui::CheckboxFlags("ImGuiTableFlags_PreciseWidths", &flags, ImGuiTableFlags_PreciseWidths);
+ ImGui::SameLine(); HelpMarker("Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth.");
+ ImGui::CheckboxFlags("ImGuiTableFlags_NoClip", &flags, ImGuiTableFlags_NoClip);
+ ImGui::SameLine(); HelpMarker("Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with ScrollFreeze options.");
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNodeEx("Padding:", ImGuiTreeNodeFlags_DefaultOpen))
+ {
+ ImGui::CheckboxFlags("ImGuiTableFlags_PadOuterX", &flags, ImGuiTableFlags_PadOuterX);
+ ImGui::CheckboxFlags("ImGuiTableFlags_NoPadOuterX", &flags, ImGuiTableFlags_NoPadOuterX);
+ ImGui::CheckboxFlags("ImGuiTableFlags_NoPadInnerX", &flags, ImGuiTableFlags_NoPadInnerX);
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNodeEx("Scrolling:", ImGuiTreeNodeFlags_DefaultOpen))
+ {
+ ImGui::CheckboxFlags("ImGuiTableFlags_ScrollX", &flags, ImGuiTableFlags_ScrollX);
+ ImGui::SameLine();
+ ImGui::SetNextItemWidth(ImGui::GetFrameHeight());
+ ImGui::DragInt("freeze_cols", &freeze_cols, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput);
+ ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", &flags, ImGuiTableFlags_ScrollY);
+ ImGui::SameLine();
+ ImGui::SetNextItemWidth(ImGui::GetFrameHeight());
+ ImGui::DragInt("freeze_rows", &freeze_rows, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput);
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNodeEx("Sorting:", ImGuiTreeNodeFlags_DefaultOpen))
+ {
+ ImGui::CheckboxFlags("ImGuiTableFlags_SortMulti", &flags, ImGuiTableFlags_SortMulti);
+ ImGui::SameLine(); HelpMarker("When sorting is enabled: hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1).");
+ ImGui::CheckboxFlags("ImGuiTableFlags_SortTristate", &flags, ImGuiTableFlags_SortTristate);
+ ImGui::SameLine(); HelpMarker("When sorting is enabled: allow no sorting, disable default sorting. TableGetSortSpecs() may return specs where (SpecsCount == 0).");
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNodeEx("Other:", ImGuiTreeNodeFlags_DefaultOpen))
+ {
+ ImGui::Checkbox("show_headers", &show_headers);
+ ImGui::Checkbox("show_wrapped_text", &show_wrapped_text);
+
+ ImGui::DragFloat2("##OuterSize", &outer_size_value.x);
+ ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x);
+ ImGui::Checkbox("outer_size", &outer_size_enabled);
+ ImGui::SameLine();
+ HelpMarker("If scrolling is disabled (ScrollX and ScrollY not set):\n"
+ "- The table is output directly in the parent window.\n"
+ "- OuterSize.x < 0.0f will right-align the table.\n"
+ "- OuterSize.x = 0.0f will narrow fit the table unless there are any Stretch column.\n"
+ "- OuterSize.y then becomes the minimum size for the table, which will extend vertically if there are more rows (unless NoHostExtendY is set).");
+
+ // From a user point of view we will tend to use 'inner_width' differently depending on whether our table is embedding scrolling.
+ // To facilitate toying with this demo we will actually pass 0.0f to the BeginTable() when ScrollX is disabled.
+ ImGui::DragFloat("inner_width (when ScrollX active)", &inner_width_with_scroll, 1.0f, 0.0f, FLT_MAX);
+
+ ImGui::DragFloat("row_min_height", &row_min_height, 1.0f, 0.0f, FLT_MAX);
+ ImGui::SameLine(); HelpMarker("Specify height of the Selectable item.");
+
+ ImGui::DragInt("items_count", &items_count, 0.1f, 0, 9999);
+ ImGui::Combo("items_type (first column)", &contents_type, contents_type_names, IM_ARRAYSIZE(contents_type_names));
+ //filter.Draw("filter");
+ ImGui::TreePop();
+ }
+
+ ImGui::PopItemWidth();
+ PopStyleCompact();
+ ImGui::Spacing();
+ ImGui::TreePop();
+ }
+
+ // Recreate/reset item list if we changed the number of items
+ static ImVector items;
+ static ImVector selection;
+ static bool items_need_sort = false;
+ if (items.Size != items_count)
+ {
+ items.resize(items_count, MyItem());
+ for (int n = 0; n < items_count; n++)
+ {
+ const int template_n = n % IM_ARRAYSIZE(template_items_names);
+ MyItem& item = items[n];
+ item.ID = n;
+ item.Name = template_items_names[template_n];
+ item.Quantity = (template_n == 3) ? 10 : (template_n == 4) ? 20 : 0; // Assign default quantities
+ }
+ }
+
+ const ImDrawList* parent_draw_list = ImGui::GetWindowDrawList();
+ const int parent_draw_list_draw_cmd_count = parent_draw_list->CmdBuffer.Size;
+ ImVec2 table_scroll_cur, table_scroll_max; // For debug display
+ const ImDrawList* table_draw_list = NULL; // "
+
+ const float inner_width_to_use = (flags & ImGuiTableFlags_ScrollX) ? inner_width_with_scroll : 0.0f;
+ if (ImGui::BeginTable("table_advanced", 6, flags, outer_size_enabled ? outer_size_value : ImVec2(0, 0), inner_width_to_use))
+ {
+ // Declare columns
+ // We use the "user_id" parameter of TableSetupColumn() to specify a user id that will be stored in the sort specifications.
+ // This is so our sort function can identify a column given our own identifier. We could also identify them based on their index!
+ ImGui::TableSetupColumn("ID", ImGuiTableColumnFlags_DefaultSort | ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_NoHide, 0.0f, MyItemColumnID_ID);
+ ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthFixed, 0.0f, MyItemColumnID_Name);
+ ImGui::TableSetupColumn("Action", ImGuiTableColumnFlags_NoSort | ImGuiTableColumnFlags_WidthFixed, 0.0f, MyItemColumnID_Action);
+ ImGui::TableSetupColumn("Quantity", ImGuiTableColumnFlags_PreferSortDescending, 0.0f, MyItemColumnID_Quantity);
+ ImGui::TableSetupColumn("Description", (flags & ImGuiTableFlags_NoHostExtendX) ? 0 : ImGuiTableColumnFlags_WidthStretch, 0.0f, MyItemColumnID_Description);
+ ImGui::TableSetupColumn("Hidden", ImGuiTableColumnFlags_DefaultHide | ImGuiTableColumnFlags_NoSort);
+ ImGui::TableSetupScrollFreeze(freeze_cols, freeze_rows);
+
+ // Sort our data if sort specs have been changed!
+ ImGuiTableSortSpecs* sorts_specs = ImGui::TableGetSortSpecs();
+ if (sorts_specs && sorts_specs->SpecsDirty)
+ items_need_sort = true;
+ if (sorts_specs && items_need_sort && items.Size > 1)
+ {
+ MyItem::s_current_sort_specs = sorts_specs; // Store in variable accessible by the sort function.
+ qsort(&items[0], (size_t)items.Size, sizeof(items[0]), MyItem::CompareWithSortSpecs);
+ MyItem::s_current_sort_specs = NULL;
+ sorts_specs->SpecsDirty = false;
+ }
+ items_need_sort = false;
+
+ // Take note of whether we are currently sorting based on the Quantity field,
+ // we will use this to trigger sorting when we know the data of this column has been modified.
+ const bool sorts_specs_using_quantity = (ImGui::TableGetColumnFlags(3) & ImGuiTableColumnFlags_IsSorted) != 0;
+
+ // Show headers
+ if (show_headers)
+ ImGui::TableHeadersRow();
+
+ // Show data
+ // FIXME-TABLE FIXME-NAV: How we can get decent up/down even though we have the buttons here?
+ ImGui::PushButtonRepeat(true);
+#if 1
+ // Demonstrate using clipper for large vertical lists
+ ImGuiListClipper clipper;
+ clipper.Begin(items.Size);
+ while (clipper.Step())
+ {
+ for (int row_n = clipper.DisplayStart; row_n < clipper.DisplayEnd; row_n++)
+#else
+ // Without clipper
+ {
+ for (int row_n = 0; row_n < items.Size; row_n++)
+#endif
+ {
+ MyItem* item = &items[row_n];
+ //if (!filter.PassFilter(item->Name))
+ // continue;
+
+ const bool item_is_selected = selection.contains(item->ID);
+ ImGui::PushID(item->ID);
+ ImGui::TableNextRow(ImGuiTableRowFlags_None, row_min_height);
+ ImGui::TableNextColumn();
+
+ // For the demo purpose we can select among different type of items submitted in the first column
+ char label[32];
+ sprintf(label, "%04d", item->ID);
+ if (contents_type == CT_Text)
+ ImGui::TextUnformatted(label);
+ else if (contents_type == CT_Button)
+ ImGui::Button(label);
+ else if (contents_type == CT_SmallButton)
+ ImGui::SmallButton(label);
+ else if (contents_type == CT_FillButton)
+ ImGui::Button(label, ImVec2(-FLT_MIN, 0.0f));
+ else if (contents_type == CT_Selectable || contents_type == CT_SelectableSpanRow)
+ {
+ ImGuiSelectableFlags selectable_flags = (contents_type == CT_SelectableSpanRow) ? ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowItemOverlap : ImGuiSelectableFlags_None;
+ if (ImGui::Selectable(label, item_is_selected, selectable_flags, ImVec2(0, row_min_height)))
+ {
+ if (ImGui::GetIO().KeyCtrl)
+ {
+ if (item_is_selected)
+ selection.find_erase_unsorted(item->ID);
+ else
+ selection.push_back(item->ID);
+ }
+ else
+ {
+ selection.clear();
+ selection.push_back(item->ID);
+ }
+ }
+ }
+
+ if (ImGui::TableNextColumn())
+ ImGui::TextUnformatted(item->Name);
+
+ // Here we demonstrate marking our data set as needing to be sorted again if we modified a quantity,
+ // and we are currently sorting on the column showing the Quantity.
+ // To avoid triggering a sort while holding the button, we only trigger it when the button has been released.
+ // You will probably need a more advanced system in your code if you want to automatically sort when a specific entry changes.
+ if (ImGui::TableNextColumn())
+ {
+ if (ImGui::SmallButton("Chop")) { item->Quantity += 1; }
+ if (sorts_specs_using_quantity && ImGui::IsItemDeactivated()) { items_need_sort = true; }
+ ImGui::SameLine();
+ if (ImGui::SmallButton("Eat")) { item->Quantity -= 1; }
+ if (sorts_specs_using_quantity && ImGui::IsItemDeactivated()) { items_need_sort = true; }
+ }
+
+ if (ImGui::TableNextColumn())
+ ImGui::Text("%d", item->Quantity);
+
+ ImGui::TableNextColumn();
+ if (show_wrapped_text)
+ ImGui::TextWrapped("Lorem ipsum dolor sit amet");
+ else
+ ImGui::Text("Lorem ipsum dolor sit amet");
+
+ if (ImGui::TableNextColumn())
+ ImGui::Text("1234");
+
+ ImGui::PopID();
+ }
+ }
+ ImGui::PopButtonRepeat();
+
+ // Store some info to display debug details below
+ table_scroll_cur = ImVec2(ImGui::GetScrollX(), ImGui::GetScrollY());
+ table_scroll_max = ImVec2(ImGui::GetScrollMaxX(), ImGui::GetScrollMaxY());
+ table_draw_list = ImGui::GetWindowDrawList();
+ ImGui::EndTable();
+ }
+ static bool show_debug_details = false;
+ ImGui::Checkbox("Debug details", &show_debug_details);
+ if (show_debug_details && table_draw_list)
+ {
+ ImGui::SameLine(0.0f, 0.0f);
+ const int table_draw_list_draw_cmd_count = table_draw_list->CmdBuffer.Size;
+ if (table_draw_list == parent_draw_list)
+ ImGui::Text(": DrawCmd: +%d (in same window)",
+ table_draw_list_draw_cmd_count - parent_draw_list_draw_cmd_count);
+ else
+ ImGui::Text(": DrawCmd: +%d (in child window), Scroll: (%.f/%.f) (%.f/%.f)",
+ table_draw_list_draw_cmd_count - 1, table_scroll_cur.x, table_scroll_max.x, table_scroll_cur.y, table_scroll_max.y);
+ }
+ ImGui::TreePop();
+ }
+
+ ImGui::PopID();
+
+ ShowDemoWindowColumns();
+
+ if (disable_indent)
+ ImGui::PopStyleVar();
+}
+
+// Demonstrate old/legacy Columns API!
+// [2020: Columns are under-featured and not maintained. Prefer using the more flexible and powerful BeginTable() API!]
+static void ShowDemoWindowColumns()
+{
+ bool open = ImGui::TreeNode("Legacy Columns API");
+ ImGui::SameLine();
+ HelpMarker("Columns() is an old API! Prefer using the more flexible and powerful BeginTable() API!");
+ if (!open)
+ return;
+
// Basic columns
if (ImGui::TreeNode("Basic"))
{
@@ -2853,39 +5258,17 @@ static void ShowDemoWindowColumns()
ImGui::TreePop();
}
- // Scrolling columns
- /*
- if (ImGui::TreeNode("Vertical Scrolling"))
- {
- ImGui::BeginChild("##header", ImVec2(0, ImGui::GetTextLineHeightWithSpacing()+ImGui::GetStyle().ItemSpacing.y));
- ImGui::Columns(3);
- ImGui::Text("ID"); ImGui::NextColumn();
- ImGui::Text("Name"); ImGui::NextColumn();
- ImGui::Text("Path"); ImGui::NextColumn();
- ImGui::Columns(1);
- ImGui::Separator();
- ImGui::EndChild();
- ImGui::BeginChild("##scrollingregion", ImVec2(0, 60));
- ImGui::Columns(3);
- for (int i = 0; i < 10; i++)
- {
- ImGui::Text("%04d", i); ImGui::NextColumn();
- ImGui::Text("Foobar"); ImGui::NextColumn();
- ImGui::Text("/path/foobar/%04d/", i); ImGui::NextColumn();
- }
- ImGui::Columns(1);
- ImGui::EndChild();
- ImGui::TreePop();
- }
- */
-
if (ImGui::TreeNode("Horizontal Scrolling"))
{
ImGui::SetNextWindowContentSize(ImVec2(1500.0f, 0.0f));
- ImGui::BeginChild("##ScrollingRegion", ImVec2(0, ImGui::GetFontSize() * 20), false, ImGuiWindowFlags_HorizontalScrollbar);
+ ImVec2 child_size = ImVec2(0, ImGui::GetFontSize() * 20.0f);
+ ImGui::BeginChild("##ScrollingRegion", child_size, false, ImGuiWindowFlags_HorizontalScrollbar);
ImGui::Columns(10);
+
+ // Also demonstrate using clipper for large vertical lists
int ITEMS_COUNT = 2000;
- ImGuiListClipper clipper(ITEMS_COUNT); // Also demonstrate using the clipper for large list
+ ImGuiListClipper clipper;
+ clipper.Begin(ITEMS_COUNT);
while (clipper.Step())
{
for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
@@ -2936,9 +5319,7 @@ static void ShowDemoWindowColumns()
ImGui::TreePop();
}
- if (disable_indent)
- ImGui::PopStyleVar();
- ImGui::PopID();
+ ImGui::TreePop();
}
static void ShowDemoWindowMisc()
@@ -2981,7 +5362,7 @@ static void ShowDemoWindowMisc()
ImGui::Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y);
ImGui::Text("Mouse down:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (io.MouseDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); }
ImGui::Text("Mouse clicked:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); }
- ImGui::Text("Mouse dbl-clicked:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseDoubleClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); }
+ ImGui::Text("Mouse dblclick:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseDoubleClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); }
ImGui::Text("Mouse released:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseReleased(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); }
ImGui::Text("Mouse wheel: %.1f", io.MouseWheel);
@@ -2991,9 +5372,9 @@ static void ShowDemoWindowMisc()
ImGui::Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
ImGui::Text("Chars queue:"); for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; ImGui::SameLine(); ImGui::Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.
- 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::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())
@@ -3009,13 +5390,13 @@ static void ShowDemoWindowMisc()
if (ImGui::TreeNode("Tabbing"))
{
ImGui::Text("Use TAB/SHIFT+TAB to cycle through keyboard editable fields.");
- static char buf[32] = "dummy";
+ static char buf[32] = "hello";
ImGui::InputText("1", buf, IM_ARRAYSIZE(buf));
ImGui::InputText("2", buf, IM_ARRAYSIZE(buf));
ImGui::InputText("3", buf, IM_ARRAYSIZE(buf));
ImGui::PushAllowKeyboardFocus(false);
ImGui::InputText("4 (tab skip)", buf, IM_ARRAYSIZE(buf));
- //ImGui::SameLine(); HelpMarker("Use ImGui::PushAllowKeyboardFocus(bool)\nto disable tabbing through certain widgets.");
+ //ImGui::SameLine(); HelpMarker("Use ImGui::PushAllowKeyboardFocus(bool) to disable tabbing through certain widgets.");
ImGui::PopAllowKeyboardFocus();
ImGui::InputText("5", buf, IM_ARRAYSIZE(buf));
ImGui::TreePop();
@@ -3065,36 +5446,48 @@ static void ShowDemoWindowMisc()
{
ImGui::TextWrapped("You can use ImGui::GetMouseDragDelta(0) to query for the dragged amount on any widget.");
for (int button = 0; button < 3; button++)
- ImGui::Text("IsMouseDragging(%d):\n w/ default threshold: %d,\n w/ zero threshold: %d\n w/ large threshold: %d",
- button, ImGui::IsMouseDragging(button), ImGui::IsMouseDragging(button, 0.0f), ImGui::IsMouseDragging(button, 20.0f));
+ {
+ ImGui::Text("IsMouseDragging(%d):", button);
+ ImGui::Text(" w/ default threshold: %d,", ImGui::IsMouseDragging(button));
+ ImGui::Text(" w/ zero threshold: %d,", ImGui::IsMouseDragging(button, 0.0f));
+ ImGui::Text(" w/ large threshold: %d,", ImGui::IsMouseDragging(button, 20.0f));
+ }
ImGui::Button("Drag Me");
if (ImGui::IsItemActive())
ImGui::GetForegroundDrawList()->AddLine(io.MouseClickedPos[0], io.MousePos, ImGui::GetColorU32(ImGuiCol_Button), 4.0f); // Draw a line between the button and the mouse cursor
- // Drag operations gets "unlocked" when the mouse has moved past a certain threshold (the default threshold is stored in io.MouseDragThreshold)
- // You can request a lower or higher threshold using the second parameter of IsMouseDragging() and GetMouseDragDelta()
+ // Drag operations gets "unlocked" when the mouse has moved past a certain threshold
+ // (the default threshold is stored in io.MouseDragThreshold). You can request a lower or higher
+ // threshold using the second parameter of IsMouseDragging() and GetMouseDragDelta().
ImVec2 value_raw = ImGui::GetMouseDragDelta(0, 0.0f);
ImVec2 value_with_lock_threshold = ImGui::GetMouseDragDelta(0);
ImVec2 mouse_delta = io.MouseDelta;
- ImGui::Text("GetMouseDragDelta(0):\n w/ default threshold: (%.1f, %.1f),\n w/ zero threshold: (%.1f, %.1f)\nMouseDelta: (%.1f, %.1f)", value_with_lock_threshold.x, value_with_lock_threshold.y, value_raw.x, value_raw.y, mouse_delta.x, mouse_delta.y);
+ ImGui::Text("GetMouseDragDelta(0):");
+ ImGui::Text(" w/ default threshold: (%.1f, %.1f)", value_with_lock_threshold.x, value_with_lock_threshold.y);
+ ImGui::Text(" w/ zero threshold: (%.1f, %.1f)", value_raw.x, value_raw.y);
+ ImGui::Text("io.MouseDelta: (%.1f, %.1f)", mouse_delta.x, mouse_delta.y);
ImGui::TreePop();
}
if (ImGui::TreeNode("Mouse cursors"))
{
- const char* mouse_cursors_names[] = { "Arrow", "TextInput", "Move", "ResizeNS", "ResizeEW", "ResizeNESW", "ResizeNWSE", "Hand" };
+ const char* mouse_cursors_names[] = { "Arrow", "TextInput", "ResizeAll", "ResizeNS", "ResizeEW", "ResizeNESW", "ResizeNWSE", "Hand", "NotAllowed" };
IM_ASSERT(IM_ARRAYSIZE(mouse_cursors_names) == ImGuiMouseCursor_COUNT);
- ImGui::Text("Current mouse cursor = %d: %s", ImGui::GetMouseCursor(), mouse_cursors_names[ImGui::GetMouseCursor()]);
+ ImGuiMouseCursor current = ImGui::GetMouseCursor();
+ ImGui::Text("Current mouse cursor = %d: %s", current, mouse_cursors_names[current]);
ImGui::Text("Hover to see mouse cursors:");
- ImGui::SameLine(); HelpMarker("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.");
+ ImGui::SameLine(); HelpMarker(
+ "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++)
{
char label[32];
sprintf(label, "Mouse cursor %d: %s", i, mouse_cursors_names[i]);
ImGui::Bullet(); ImGui::Selectable(label, false);
- if (ImGui::IsItemHovered() || ImGui::IsItemFocused())
+ if (ImGui::IsItemHovered())
ImGui::SetMouseCursor(i);
}
ImGui::TreePop();
@@ -3127,11 +5520,12 @@ void ImGui::ShowAboutWindow(bool* p_open)
ImGuiStyle& style = ImGui::GetStyle();
bool copy_to_clipboard = ImGui::Button("Copy to clipboard");
- ImGui::BeginChildFrame(ImGui::GetID("cfginfos"), ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 18), ImGuiWindowFlags_NoMove);
+ ImVec2 child_size = ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 18);
+ ImGui::BeginChildFrame(ImGui::GetID("cfg_infos"), child_size, ImGuiWindowFlags_NoMove);
if (copy_to_clipboard)
{
ImGui::LogToClipboard();
- ImGui::LogText("```\n"); // Back quotes will make the text appears without formatting when pasting to GitHub
+ ImGui::LogText("```\n"); // Back quotes will make text appears without formatting when pasting on GitHub
}
ImGui::Text("Dear ImGui %s (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM);
@@ -3150,11 +5544,17 @@ void ImGui::ShowAboutWindow(bool* p_open)
#ifdef IMGUI_DISABLE_WIN32_FUNCTIONS
ImGui::Text("define: IMGUI_DISABLE_WIN32_FUNCTIONS");
#endif
-#ifdef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS
- ImGui::Text("define: IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS");
+#ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
+ ImGui::Text("define: IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS");
#endif
-#ifdef IMGUI_DISABLE_MATH_FUNCTIONS
- ImGui::Text("define: IMGUI_DISABLE_MATH_FUNCTIONS");
+#ifdef IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS
+ ImGui::Text("define: IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS");
+#endif
+#ifdef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
+ ImGui::Text("define: IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS");
+#endif
+#ifdef IMGUI_DISABLE_FILE_FUNCTIONS
+ ImGui::Text("define: IMGUI_DISABLE_FILE_FUNCTIONS");
#endif
#ifdef IMGUI_DISABLE_DEFAULT_ALLOCATORS
ImGui::Text("define: IMGUI_DISABLE_DEFAULT_ALLOCATORS");
@@ -3177,6 +5577,9 @@ void ImGui::ShowAboutWindow(bool* p_open)
#ifdef _MSC_VER
ImGui::Text("define: _MSC_VER=%d", _MSC_VER);
#endif
+#ifdef _MSVC_LANG
+ ImGui::Text("define: _MSVC_LANG=%d", (int)_MSVC_LANG);
+#endif
#ifdef __MINGW32__
ImGui::Text("define: __MINGW32__");
#endif
@@ -3188,12 +5591,6 @@ void ImGui::ShowAboutWindow(bool* p_open)
#endif
#ifdef __clang_version__
ImGui::Text("define: __clang_version__=%s", __clang_version__);
-#endif
-#ifdef IMGUI_HAS_VIEWPORT
- ImGui::Text("define: IMGUI_HAS_VIEWPORT");
-#endif
-#ifdef IMGUI_HAS_DOCK
- ImGui::Text("define: IMGUI_HAS_DOCK");
#endif
ImGui::Separator();
ImGui::Text("io.BackendPlatformName: %s", io.BackendPlatformName ? io.BackendPlatformName : "NULL");
@@ -3205,32 +5602,17 @@ void ImGui::ShowAboutWindow(bool* p_open)
if (io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard) ImGui::Text(" NavNoCaptureKeyboard");
if (io.ConfigFlags & ImGuiConfigFlags_NoMouse) ImGui::Text(" NoMouse");
if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) ImGui::Text(" NoMouseCursorChange");
- if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable) ImGui::Text(" DockingEnable");
- if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) ImGui::Text(" ViewportsEnable");
- if (io.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports) ImGui::Text(" DpiEnableScaleViewports");
- if (io.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ImGui::Text(" DpiEnableScaleFonts");
if (io.MouseDrawCursor) ImGui::Text("io.MouseDrawCursor");
- if (io.ConfigViewportsNoAutoMerge) ImGui::Text("io.ConfigViewportsNoAutoMerge");
- if (io.ConfigViewportsNoTaskBarIcon) ImGui::Text("io.ConfigViewportsNoTaskBarIcon");
- if (io.ConfigViewportsNoDecoration) ImGui::Text("io.ConfigViewportsNoDecoration");
- if (io.ConfigViewportsNoDefaultParent) ImGui::Text("io.ConfigViewportsNoDefaultParent");
- if (io.ConfigDockingNoSplit) ImGui::Text("io.ConfigDockingNoSplit");
- if (io.ConfigDockingWithShift) ImGui::Text("io.ConfigDockingWithShift");
- if (io.ConfigDockingAlwaysTabBar) ImGui::Text("io.ConfigDockingAlwaysTabBar");
- if (io.ConfigDockingTransparentPayload) ImGui::Text("io.ConfigDockingTransparentPayload");
if (io.ConfigMacOSXBehaviors) ImGui::Text("io.ConfigMacOSXBehaviors");
if (io.ConfigInputTextCursorBlink) ImGui::Text("io.ConfigInputTextCursorBlink");
if (io.ConfigWindowsResizeFromEdges) ImGui::Text("io.ConfigWindowsResizeFromEdges");
if (io.ConfigWindowsMoveFromTitleBarOnly) ImGui::Text("io.ConfigWindowsMoveFromTitleBarOnly");
- if (io.ConfigWindowsMemoryCompactTimer >= 0.0f) ImGui::Text("io.ConfigWindowsMemoryCompactTimer = %.1ff", io.ConfigWindowsMemoryCompactTimer);
+ if (io.ConfigMemoryCompactTimer >= 0.0f) ImGui::Text("io.ConfigMemoryCompactTimer = %.1f", io.ConfigMemoryCompactTimer);
ImGui::Text("io.BackendFlags: 0x%08X", io.BackendFlags);
if (io.BackendFlags & ImGuiBackendFlags_HasGamepad) ImGui::Text(" HasGamepad");
if (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) ImGui::Text(" HasMouseCursors");
if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) ImGui::Text(" HasSetMousePos");
- if (io.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) ImGui::Text(" PlatformHasViewports");
- if (io.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)ImGui::Text(" HasMouseHoveredViewport");
if (io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) ImGui::Text(" RendererHasVtxOffset");
- if (io.BackendFlags & ImGuiBackendFlags_RendererHasViewports) ImGui::Text(" RendererHasViewports");
ImGui::Separator();
ImGui::Text("io.Fonts: %d fonts, Flags: 0x%08X, TexSize: %d,%d", io.Fonts->Fonts.Size, io.Fonts->Flags, io.Fonts->TexWidth, io.Fonts->TexHeight);
ImGui::Text("io.DisplaySize: %.2f,%.2f", io.DisplaySize.x, io.DisplaySize.y);
@@ -3263,17 +5645,18 @@ void ImGui::ShowAboutWindow(bool* p_open)
//-----------------------------------------------------------------------------
// Demo helper function to select among default colors. See ShowStyleEditor() for more advanced options.
-// 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.
+// 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 = -1;
- if (ImGui::Combo(label, &style_idx, "Classic\0Dark\0Light\0"))
+ if (ImGui::Combo(label, &style_idx, "Dark\0Light\0Classic\0"))
{
switch (style_idx)
{
- case 0: ImGui::StyleColorsClassic(); break;
- case 1: ImGui::StyleColorsDark(); break;
- case 2: ImGui::StyleColorsLight(); break;
+ case 0: ImGui::StyleColorsDark(); break;
+ case 1: ImGui::StyleColorsLight(); break;
+ case 2: ImGui::StyleColorsClassic(); break;
}
return true;
}
@@ -3302,13 +5685,102 @@ void ImGui::ShowFontSelector(const char* label)
HelpMarker(
"- 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 misc/fonts/ for more details.\n"
+ "- Read FAQ and docs/FONTS.md for more details.\n"
"- If you need to add/remove fonts at runtime (e.g. for DPI change), do it before calling NewFrame().");
}
+// [Internal] Display details for a single font, called by ShowStyleEditor().
+static void NodeFont(ImFont* font)
+{
+ ImGuiIO& io = ImGui::GetIO();
+ ImGuiStyle& style = ImGui::GetStyle();
+ bool font_details_opened = ImGui::TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)",
+ font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
+ ImGui::SameLine(); if (ImGui::SmallButton("Set as default")) { io.FontDefault = font; }
+ if (!font_details_opened)
+ return;
+
+ ImGui::PushFont(font);
+ 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::SameLine(); HelpMarker(
+ "Note than the default embedded font is NOT meant to be scaled.\n\n"
+ "Font 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 will be rewritten in the future to make scaling more flexible.)");
+ ImGui::Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
+ ImGui::Text("Fallback character: '%c' (U+%04X)", font->FallbackChar, font->FallbackChar);
+ ImGui::Text("Ellipsis character: '%c' (U+%04X)", font->EllipsisChar, font->EllipsisChar);
+ const int surface_sqrt = (int)sqrtf((float)font->MetricsTotalSurface);
+ ImGui::Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);
+ for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
+ if (font->ConfigData)
+ if (const ImFontConfig* cfg = &font->ConfigData[config_i])
+ ImGui::BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
+ config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);
+ if (ImGui::TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
+ {
+ // Display all glyphs of the fonts in separate pages of 256 characters
+ const ImU32 glyph_col = ImGui::GetColorU32(ImGuiCol_Text);
+ for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
+ {
+ // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
+ // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
+ // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
+ if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095))
+ {
+ base += 4096 - 256;
+ continue;
+ }
+
+ int count = 0;
+ for (unsigned int n = 0; n < 256; n++)
+ if (font->FindGlyphNoFallback((ImWchar)(base + n)))
+ count++;
+ if (count <= 0)
+ continue;
+ if (!ImGui::TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
+ continue;
+ float cell_size = font->FontSize * 1;
+ float cell_spacing = style.ItemSpacing.y;
+ ImVec2 base_pos = ImGui::GetCursorScreenPos();
+ ImDrawList* draw_list = ImGui::GetWindowDrawList();
+ for (unsigned int n = 0; n < 256; n++)
+ {
+ // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
+ // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
+ 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));
+ if (glyph)
+ font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
+ if (glyph && ImGui::IsMouseHoveringRect(cell_p1, cell_p2))
+ {
+ ImGui::BeginTooltip();
+ ImGui::Text("Codepoint: U+%04X", base + n);
+ ImGui::Separator();
+ ImGui::Text("Visible: %d", glyph->Visible);
+ ImGui::Text("AdvanceX: %.1f", glyph->AdvanceX);
+ ImGui::Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
+ ImGui::Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
+ ImGui::EndTooltip();
+ }
+ }
+ ImGui::Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
+ ImGui::TreePop();
+ }
+ ImGui::TreePop();
+ }
+ ImGui::TreePop();
+}
+
void ImGui::ShowStyleEditor(ImGuiStyle* ref)
{
- // You can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it compares to an internally stored reference)
+ // You can pass in a reference ImGuiStyle structure to compare to, revert to and save to
+ // (without a reference style pointer, we will use one compared locally as a reference)
ImGuiStyle& style = ImGui::GetStyle();
static ImGuiStyle ref_saved_style;
@@ -3326,14 +5798,14 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref)
ref_saved_style = style;
ImGui::ShowFontSelector("Fonts##Selector");
- // Simplified Settings
+ // Simplified Settings (expose floating-pointer border sizes as boolean representing 0.0f or 1.0f)
if (ImGui::SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f"))
style.GrabRounding = style.FrameRounding; // Make GrabRounding always the same value as FrameRounding
- { bool window_border = (style.WindowBorderSize > 0.0f); if (ImGui::Checkbox("WindowBorder", &window_border)) style.WindowBorderSize = window_border ? 1.0f : 0.0f; }
+ { bool border = (style.WindowBorderSize > 0.0f); if (ImGui::Checkbox("WindowBorder", &border)) { style.WindowBorderSize = border ? 1.0f : 0.0f; } }
ImGui::SameLine();
- { bool frame_border = (style.FrameBorderSize > 0.0f); if (ImGui::Checkbox("FrameBorder", &frame_border)) style.FrameBorderSize = frame_border ? 1.0f : 0.0f; }
+ { bool border = (style.FrameBorderSize > 0.0f); if (ImGui::Checkbox("FrameBorder", &border)) { style.FrameBorderSize = border ? 1.0f : 0.0f; } }
ImGui::SameLine();
- { bool popup_border = (style.PopupBorderSize > 0.0f); if (ImGui::Checkbox("PopupBorder", &popup_border)) style.PopupBorderSize = popup_border ? 1.0f : 0.0f; }
+ { bool border = (style.PopupBorderSize > 0.0f); if (ImGui::Checkbox("PopupBorder", &border)) { style.PopupBorderSize = border ? 1.0f : 0.0f; } }
// Save/Revert button
if (ImGui::Button("Save Ref"))
@@ -3342,7 +5814,9 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref)
if (ImGui::Button("Revert Ref"))
style = *ref;
ImGui::SameLine();
- HelpMarker("Save/Revert in local non-persistent storage. Default Colors definition are not affected. Use \"Export\" below to save them somewhere.");
+ HelpMarker(
+ "Save/Revert in local non-persistent storage. Default Colors definition are not affected. "
+ "Use \"Export\" below to save them somewhere.");
ImGui::Separator();
@@ -3353,6 +5827,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref)
ImGui::Text("Main");
ImGui::SliderFloat2("WindowPadding", (float*)&style.WindowPadding, 0.0f, 20.0f, "%.0f");
ImGui::SliderFloat2("FramePadding", (float*)&style.FramePadding, 0.0f, 20.0f, "%.0f");
+ ImGui::SliderFloat2("CellPadding", (float*)&style.CellPadding, 0.0f, 20.0f, "%.0f");
ImGui::SliderFloat2("ItemSpacing", (float*)&style.ItemSpacing, 0.0f, 20.0f, "%.0f");
ImGui::SliderFloat2("ItemInnerSpacing", (float*)&style.ItemInnerSpacing, 0.0f, 20.0f, "%.0f");
ImGui::SliderFloat2("TouchExtraPadding", (float*)&style.TouchExtraPadding, 0.0f, 10.0f, "%.0f");
@@ -3372,6 +5847,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref)
ImGui::SliderFloat("PopupRounding", &style.PopupRounding, 0.0f, 12.0f, "%.0f");
ImGui::SliderFloat("ScrollbarRounding", &style.ScrollbarRounding, 0.0f, 12.0f, "%.0f");
ImGui::SliderFloat("GrabRounding", &style.GrabRounding, 0.0f, 12.0f, "%.0f");
+ ImGui::SliderFloat("LogSliderDeadzone", &style.LogSliderDeadzone, 0.0f, 12.0f, "%.0f");
ImGui::SliderFloat("TabRounding", &style.TabRounding, 0.0f, 12.0f, "%.0f");
ImGui::Text("Alignment");
ImGui::SliderFloat2("WindowTitleAlign", (float*)&style.WindowTitleAlign, 0.0f, 1.0f, "%.2f");
@@ -3379,9 +5855,12 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref)
if (ImGui::Combo("WindowMenuButtonPosition", (int*)&window_menu_button_position, "None\0Left\0Right\0"))
style.WindowMenuButtonPosition = window_menu_button_position - 1;
ImGui::Combo("ColorButtonPosition", (int*)&style.ColorButtonPosition, "Left\0Right\0");
- ImGui::SliderFloat2("ButtonTextAlign", (float*)&style.ButtonTextAlign, 0.0f, 1.0f, "%.2f"); ImGui::SameLine(); HelpMarker("Alignment applies when a button is larger than its text content.");
- ImGui::SliderFloat2("SelectableTextAlign", (float*)&style.SelectableTextAlign, 0.0f, 1.0f, "%.2f"); ImGui::SameLine(); HelpMarker("Alignment applies when a selectable is larger than its text content.");
- ImGui::Text("Safe Area Padding"); ImGui::SameLine(); HelpMarker("Adjust if you cannot see the edges of your screen (e.g. on a TV where scaling has not been configured).");
+ ImGui::SliderFloat2("ButtonTextAlign", (float*)&style.ButtonTextAlign, 0.0f, 1.0f, "%.2f");
+ ImGui::SameLine(); HelpMarker("Alignment applies when a button is larger than its text content.");
+ ImGui::SliderFloat2("SelectableTextAlign", (float*)&style.SelectableTextAlign, 0.0f, 1.0f, "%.2f");
+ ImGui::SameLine(); HelpMarker("Alignment applies when a selectable is larger than its text content.");
+ ImGui::Text("Safe Area Padding");
+ ImGui::SameLine(); HelpMarker("Adjust if you cannot see the edges of your screen (e.g. on a TV where scaling has not been configured).");
ImGui::SliderFloat2("DisplaySafeAreaPadding", (float*)&style.DisplaySafeAreaPadding, 0.0f, 30.0f, "%.0f");
ImGui::EndTabItem();
}
@@ -3402,7 +5881,8 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref)
const ImVec4& col = style.Colors[i];
const char* name = ImGui::GetStyleColorName(i);
if (!output_only_modified || memcmp(&col, &ref->Colors[i], sizeof(ImVec4)) != 0)
- ImGui::LogText("colors[ImGuiCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);" IM_NEWLINE, name, 23 - (int)strlen(name), "", col.x, col.y, col.z, col.w);
+ ImGui::LogText("colors[ImGuiCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);" IM_NEWLINE,
+ name, 23 - (int)strlen(name), "", col.x, col.y, col.z, col.w);
}
ImGui::LogFinish();
}
@@ -3413,10 +5893,13 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref)
filter.Draw("Filter colors", ImGui::GetFontSize() * 16);
static ImGuiColorEditFlags alpha_flags = 0;
- ImGui::RadioButton("Opaque", &alpha_flags, 0); ImGui::SameLine();
- ImGui::RadioButton("Alpha", &alpha_flags, ImGuiColorEditFlags_AlphaPreview); ImGui::SameLine();
- ImGui::RadioButton("Both", &alpha_flags, ImGuiColorEditFlags_AlphaPreviewHalf); ImGui::SameLine();
- HelpMarker("In the color list:\nLeft-click on colored square to open color picker,\nRight-click to open edit options menu.");
+ if (ImGui::RadioButton("Opaque", alpha_flags == ImGuiColorEditFlags_None)) { alpha_flags = ImGuiColorEditFlags_None; } ImGui::SameLine();
+ if (ImGui::RadioButton("Alpha", alpha_flags == ImGuiColorEditFlags_AlphaPreview)) { alpha_flags = ImGuiColorEditFlags_AlphaPreview; } ImGui::SameLine();
+ if (ImGui::RadioButton("Both", alpha_flags == ImGuiColorEditFlags_AlphaPreviewHalf)) { alpha_flags = ImGuiColorEditFlags_AlphaPreviewHalf; } ImGui::SameLine();
+ HelpMarker(
+ "In the color list:\n"
+ "Left-click on color square to open color picker,\n"
+ "Right-click to open edit options menu.");
ImGui::BeginChild("##colors", ImVec2(0, 0), true, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar | ImGuiWindowFlags_NavFlattened);
ImGui::PushItemWidth(-160);
@@ -3429,10 +5912,11 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref)
ImGui::ColorEdit4("##color", (float*)&style.Colors[i], ImGuiColorEditFlags_AlphaBar | alpha_flags);
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 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];
+ // 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 docs/FONTS.md 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]; }
}
ImGui::SameLine(0.0f, style.ItemInnerSpacing.x);
ImGui::TextUnformatted(name);
@@ -3448,71 +5932,13 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref)
{
ImGuiIO& io = ImGui::GetIO();
ImFontAtlas* atlas = io.Fonts;
- HelpMarker("Read FAQ and misc/fonts/README.txt for details on font loading.");
+ HelpMarker("Read FAQ and docs/FONTS.md for details on font loading.");
ImGui::PushItemWidth(120);
for (int i = 0; i < atlas->Fonts.Size; i++)
{
ImFont* font = atlas->Fonts[i];
ImGui::PushID(font);
- bool font_details_opened = ImGui::TreeNode(font, "Font %d: \"%s\"\n%.2f px, %d glyphs, %d file(s)", i, font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
- ImGui::SameLine(); if (ImGui::SmallButton("Set as default")) { io.FontDefault = font; }
- if (font_details_opened)
- {
- ImGui::PushFont(font);
- 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::SameLine(); HelpMarker("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::InputFloat("Font offset", &font->DisplayOffset.y, 1, 1, "%.0f");
- ImGui::Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
- ImGui::Text("Fallback character: '%c' (U+%04X)", font->FallbackChar, font->FallbackChar);
- ImGui::Text("Ellipsis character: '%c' (U+%04X)", font->EllipsisChar, font->EllipsisChar);
- const float surface_sqrt = sqrtf((float)font->MetricsTotalSurface);
- ImGui::Text("Texture surface: %d pixels (approx) ~ %dx%d", font->MetricsTotalSurface, (int)surface_sqrt, (int)surface_sqrt);
- for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
- if (const 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
- for (int base = 0; base < 0x10000; base += 256)
- {
- int count = 0;
- for (int n = 0; n < 256; n++)
- 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 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 + 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));
- if (glyph)
- 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();
- ImGui::Text("Codepoint: U+%04X", base + n);
- ImGui::Separator();
- ImGui::Text("AdvanceX: %.1f", glyph->AdvanceX);
- ImGui::Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
- ImGui::Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
- ImGui::EndTooltip();
- }
- }
- ImGui::Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
- ImGui::TreePop();
- }
- }
- ImGui::TreePop();
- }
- ImGui::TreePop();
- }
+ NodeFont(font);
ImGui::PopID();
}
if (ImGui::TreeNode("Atlas texture", "Atlas texture (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
@@ -3523,11 +5949,19 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref)
ImGui::TreePop();
}
- HelpMarker("Those are old settings provided for convenience.\nHowever, the _correct_ way of scaling your UI is currently to reload your font at the designed size, rebuild the font atlas, and call style.ScaleAllSizes() on a reference ImGuiStyle structure.");
+ // Post-baking font scaling. Note that this is NOT the nice way of scaling fonts, read below.
+ // (we enforce hard clamping manually as by default DragFloat/SliderFloat allows CTRL+Click text to get out of bounds).
+ const float MIN_SCALE = 0.3f;
+ const float MAX_SCALE = 2.0f;
+ HelpMarker(
+ "Those are old settings provided for convenience.\n"
+ "However, the _correct_ way of scaling your UI is currently to reload your font at the designed size, "
+ "rebuild the font atlas, and call style.ScaleAllSizes() on a reference ImGuiStyle structure.\n"
+ "Using those settings here will give you poor quality results.");
static float window_scale = 1.0f;
- if (ImGui::DragFloat("window scale", &window_scale, 0.005f, 0.3f, 2.0f, "%.2f")) // scale only this window
+ if (ImGui::DragFloat("window scale", &window_scale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_AlwaysClamp)) // Scale only this window
ImGui::SetWindowFontScale(window_scale);
- ImGui::DragFloat("global scale", &io.FontGlobalScale, 0.005f, 0.3f, 2.0f, "%.2f"); // scale everything
+ ImGui::DragFloat("global scale", &io.FontGlobalScale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_AlwaysClamp); // Scale everything
ImGui::PopItemWidth();
ImGui::EndTabItem();
@@ -3535,11 +5969,41 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref)
if (ImGui::BeginTabItem("Rendering"))
{
- ImGui::Checkbox("Anti-aliased lines", &style.AntiAliasedLines); ImGui::SameLine(); HelpMarker("When disabling anti-aliasing lines, you'll probably want to disable borders in your style as well.");
+ ImGui::Checkbox("Anti-aliased lines", &style.AntiAliasedLines);
+ ImGui::SameLine();
+ HelpMarker("When disabling anti-aliasing lines, you'll probably want to disable borders in your style as well.");
+
+ ImGui::Checkbox("Anti-aliased lines use texture", &style.AntiAliasedLinesUseTex);
+ ImGui::SameLine();
+ HelpMarker("Faster lines using texture data. Require backend to render with bilinear filtering (not point/nearest filtering).");
+
ImGui::Checkbox("Anti-aliased fill", &style.AntiAliasedFill);
ImGui::PushItemWidth(100);
- ImGui::DragFloat("Curve Tessellation Tolerance", &style.CurveTessellationTol, 0.02f, 0.10f, FLT_MAX, "%.2f", 2.0f);
+ ImGui::DragFloat("Curve Tessellation Tolerance", &style.CurveTessellationTol, 0.02f, 0.10f, 10.0f, "%.2f");
if (style.CurveTessellationTol < 0.10f) style.CurveTessellationTol = 0.10f;
+
+ // When editing the "Circle Segment Max Error" value, draw a preview of its effect on auto-tessellated circles.
+ ImGui::DragFloat("Circle Segment Max Error", &style.CircleSegmentMaxError, 0.01f, 0.10f, 10.0f, "%.2f");
+ if (ImGui::IsItemActive())
+ {
+ ImGui::SetNextWindowPos(ImGui::GetCursorScreenPos());
+ ImGui::BeginTooltip();
+ ImVec2 p = ImGui::GetCursorScreenPos();
+ ImDrawList* draw_list = ImGui::GetWindowDrawList();
+ float RAD_MIN = 10.0f, RAD_MAX = 80.0f;
+ float off_x = 10.0f;
+ for (int n = 0; n < 7; n++)
+ {
+ const float rad = RAD_MIN + (RAD_MAX - RAD_MIN) * (float)n / (7.0f - 1.0f);
+ draw_list->AddCircle(ImVec2(p.x + off_x + rad, p.y + RAD_MAX), rad, ImGui::GetColorU32(ImGuiCol_Text), 0);
+ off_x += 10.0f + rad * 2.0f;
+ }
+ ImGui::Dummy(ImVec2(off_x, RAD_MAX * 2.0f));
+ ImGui::EndTooltip();
+ }
+ ImGui::SameLine();
+ HelpMarker("When drawing circle primitives with \"num_segments == 0\" tesselation will be calculated automatically.");
+
ImGui::DragFloat("Global Alpha", &style.Alpha, 0.005f, 0.20f, 1.0f, "%.2f"); // Not exposing zero here so user doesn't "lose" the UI (zero alpha clips all widgets). But application code could have a toggle to switch between zero and non-zero.
ImGui::PopItemWidth();
@@ -3561,7 +6025,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref)
// Demonstrate creating a "main" fullscreen menu bar and populating it.
// Note the difference between BeginMainMenuBar() and BeginMenuBar():
-// - BeginMenuBar() = menu-bar inside current window we Begin()-ed into (the window needs the ImGuiWindowFlags_MenuBar flag)
+// - BeginMenuBar() = menu-bar inside current window (which needs the ImGuiWindowFlags_MenuBar flag!)
// - BeginMainMenuBar() = helper to create menu-bar-sized window at the top of the main viewport + call BeginMenuBar() into it.
static void ShowExampleAppMainMenuBar()
{
@@ -3586,10 +6050,11 @@ static void ShowExampleAppMainMenuBar()
}
}
-// Note that shortcuts are currently provided for display only (future version will add flags to BeginMenu to process shortcuts)
+// Note that shortcuts are currently provided for display only
+// (future version will add explicit flags to BeginMenu() to request processing shortcuts)
static void ShowExampleMenuFile()
{
- ImGui::MenuItem("(dummy menu)", NULL, false, false);
+ ImGui::MenuItem("(demo menu)", NULL, false, false);
if (ImGui::MenuItem("New")) {}
if (ImGui::MenuItem("Open", "Ctrl+O")) {}
if (ImGui::BeginMenu("Open Recent"))
@@ -3612,6 +6077,7 @@ static void ShowExampleMenuFile()
}
if (ImGui::MenuItem("Save", "Ctrl+S")) {}
if (ImGui::MenuItem("Save As..")) {}
+
ImGui::Separator();
if (ImGui::BeginMenu("Options"))
{
@@ -3623,13 +6089,12 @@ static void ShowExampleMenuFile()
ImGui::EndChild();
static float f = 0.5f;
static int n = 0;
- static bool b = true;
ImGui::SliderFloat("Value", &f, 0.0f, 1.0f);
ImGui::InputFloat("Input", &f, 0.1f);
ImGui::Combo("Combo", &n, "Yes\0No\0Maybe\0\0");
- ImGui::Checkbox("Check", &b);
ImGui::EndMenu();
}
+
if (ImGui::BeginMenu("Colors"))
{
float sz = ImGui::GetTextLineHeight();
@@ -3637,13 +6102,24 @@ static void ShowExampleMenuFile()
{
const char* name = ImGui::GetStyleColorName((ImGuiCol)i);
ImVec2 p = ImGui::GetCursorScreenPos();
- ImGui::GetWindowDrawList()->AddRectFilled(p, ImVec2(p.x+sz, p.y+sz), ImGui::GetColorU32((ImGuiCol)i));
+ 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::EndMenu();
}
+
+ // Here we demonstrate appending again to the "Options" menu (which we already created above)
+ // Of course in this demo it is a little bit silly that this function calls BeginMenu("Options") twice.
+ // In a real code-base using it would make senses to use this feature from very different code locations.
+ if (ImGui::BeginMenu("Options")) // <-- Append!
+ {
+ static bool b = true;
+ ImGui::Checkbox("SomeOption", &b);
+ ImGui::EndMenu();
+ }
+
if (ImGui::BeginMenu("Disabled", false)) // Disabled
{
IM_ASSERT(0);
@@ -3657,7 +6133,7 @@ static void ShowExampleMenuFile()
//-----------------------------------------------------------------------------
// Demonstrate creating a simple console window, with scrolling, filtering, completion and history.
-// For the console example, here we are using a more C++ like approach of declaring a class to hold the data and the functions.
+// For the console example, we are using a more C++ like approach of declaring a class to hold both data and functions.
struct ExampleAppConsole
{
char InputBuf[256];
@@ -3674,10 +6150,12 @@ struct ExampleAppConsole
ClearLog();
memset(InputBuf, 0, sizeof(InputBuf));
HistoryPos = -1;
+
+ // "CLASSIFY" is here to provide the test case where "C"+[tab] completes to "CL" and display multiple matches.
Commands.push_back("HELP");
Commands.push_back("HISTORY");
Commands.push_back("CLEAR");
- Commands.push_back("CLASSIFY"); // "classify" is only here to provide an example of "C"+[tab] completing to "CL" and displaying matches.
+ Commands.push_back("CLASSIFY");
AutoScroll = true;
ScrollToBottom = false;
AddLog("Welcome to Dear ImGui!");
@@ -3690,10 +6168,10 @@ struct ExampleAppConsole
}
// Portable helpers
- static int Stricmp(const char* str1, const char* str2) { int d; while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; } return d; }
- static int Strnicmp(const char* str1, const char* str2, int n) { int d = 0; while (n > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; n--; } return d; }
- static char* Strdup(const char *str) { size_t len = strlen(str) + 1; void* buf = malloc(len); IM_ASSERT(buf); return (char*)memcpy(buf, (const void*)str, len); }
- static void Strtrim(char* str) { char* str_end = str + strlen(str); while (str_end > str && str_end[-1] == ' ') str_end--; *str_end = 0; }
+ static int Stricmp(const char* s1, const char* s2) { int d; while ((d = toupper(*s2) - toupper(*s1)) == 0 && *s1) { s1++; s2++; } return d; }
+ static int Strnicmp(const char* s1, const char* s2, int n) { int d = 0; while (n > 0 && (d = toupper(*s2) - toupper(*s1)) == 0 && *s1) { s1++; s2++; n--; } return d; }
+ static char* Strdup(const char* s) { IM_ASSERT(s); size_t len = strlen(s) + 1; void* buf = malloc(len); IM_ASSERT(buf); return (char*)memcpy(buf, (const void*)s, len); }
+ static void Strtrim(char* s) { char* str_end = s + strlen(s); while (str_end > s && str_end[-1] == ' ') str_end--; *str_end = 0; }
void ClearLog()
{
@@ -3716,14 +6194,15 @@ struct ExampleAppConsole
void Draw(const char* title, bool* p_open)
{
- ImGui::SetNextWindowSize(ImVec2(520,600), ImGuiCond_FirstUseEver);
+ ImGui::SetNextWindowSize(ImVec2(520, 600), ImGuiCond_FirstUseEver);
if (!ImGui::Begin(title, p_open))
{
ImGui::End();
return;
}
- // As a specific feature guaranteed by the library, after calling Begin() the last Item represent the title bar. So e.g. IsItemHovered() will return true when hovering the title bar.
+ // As a specific feature guaranteed by the library, after calling Begin() the last Item represent the title bar.
+ // So e.g. IsItemHovered() will return true when hovering the title bar.
// Here we create a context menu only available from the title bar.
if (ImGui::BeginPopupContextItem())
{
@@ -3732,14 +6211,19 @@ struct ExampleAppConsole
ImGui::EndPopup();
}
- ImGui::TextWrapped("This example implements a console with basic coloring, completion and history. A more elaborate implementation may want to store entries along with extra data such as timestamp, emitter, etc.");
- ImGui::TextWrapped("Enter 'HELP' for help, press TAB to use text completion.");
+ ImGui::TextWrapped(
+ "This example implements a console with basic coloring, completion (TAB key) and history (Up/Down keys). A more elaborate "
+ "implementation may want to store entries along with extra data such as timestamp, emitter, etc.");
+ ImGui::TextWrapped("Enter 'HELP' for help.");
// TODO: display items starting from the bottom
- if (ImGui::SmallButton("Add Dummy Text")) { AddLog("%d some text", Items.Size); AddLog("some more text"); AddLog("display very important message here!"); } ImGui::SameLine();
- if (ImGui::SmallButton("Add Dummy Error")) { AddLog("[error] something went wrong"); } ImGui::SameLine();
- if (ImGui::SmallButton("Clear")) { ClearLog(); } ImGui::SameLine();
+ if (ImGui::SmallButton("Add Debug Text")) { AddLog("%d some text", Items.Size); AddLog("some more text"); AddLog("display very important message here!"); }
+ ImGui::SameLine();
+ if (ImGui::SmallButton("Add Debug Error")) { AddLog("[error] something went wrong"); }
+ ImGui::SameLine();
+ if (ImGui::SmallButton("Clear")) { ClearLog(); }
+ ImGui::SameLine();
bool copy_to_clipboard = ImGui::SmallButton("Copy");
//static float t = 0.0f; if (ImGui::GetTime() - t > 0.02f) { t = ImGui::GetTime(); AddLog("Spam %f", t); }
@@ -3759,26 +6243,40 @@ struct ExampleAppConsole
Filter.Draw("Filter (\"incl,-excl\") (\"error\")", 180);
ImGui::Separator();
- const float footer_height_to_reserve = ImGui::GetStyle().ItemSpacing.y + ImGui::GetFrameHeightWithSpacing(); // 1 separator, 1 input text
- ImGui::BeginChild("ScrollingRegion", ImVec2(0, -footer_height_to_reserve), false, ImGuiWindowFlags_HorizontalScrollbar); // Leave room for 1 separator + 1 InputText
+ // Reserve enough left-over height for 1 separator + 1 input text
+ const float footer_height_to_reserve = ImGui::GetStyle().ItemSpacing.y + ImGui::GetFrameHeightWithSpacing();
+ ImGui::BeginChild("ScrollingRegion", ImVec2(0, -footer_height_to_reserve), false, ImGuiWindowFlags_HorizontalScrollbar);
if (ImGui::BeginPopupContextWindow())
{
if (ImGui::Selectable("Clear")) ClearLog();
ImGui::EndPopup();
}
- // Display every line as a separate entry so we can change their color or add custom widgets. If you only want raw text you can use ImGui::TextUnformatted(log.begin(), log.end());
- // NB- if you have thousands of entries this approach may be too inefficient and may require user-side clipping to only process visible items.
- // You can seek and display only the lines that are visible using the ImGuiListClipper helper, if your elements are evenly spaced and you have cheap random access to the elements.
- // To use the clipper we could replace the 'for (int i = 0; i < Items.Size; i++)' loop with:
- // ImGuiListClipper clipper(Items.Size);
- // while (clipper.Step())
+ // Display every line as a separate entry so we can change their color or add custom widgets.
+ // If you only want raw text you can use ImGui::TextUnformatted(log.begin(), log.end());
+ // NB- if you have thousands of entries this approach may be too inefficient and may require user-side clipping
+ // to only process visible items. The clipper will automatically measure the height of your first item and then
+ // "seek" to display only items in the visible area.
+ // To use the clipper we can replace your standard loop:
+ // for (int i = 0; i < Items.Size; i++)
+ // With:
+ // ImGuiListClipper clipper;
+ // clipper.Begin(Items.Size);
+ // while (clipper.Step())
// for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
- // However, note that you can not use this code as is if a filter is active because it breaks the 'cheap random-access' property. We would need random-access on the post-filtered list.
- // A typical application wanting coarse clipping and filtering may want to pre-compute an array of indices that passed the filtering test, recomputing this array when user changes the filter,
- // and appending newly elements as they are inserted. This is left as a task to the user until we can manage to improve this example code!
- // If your items are of variable size you may want to implement code similar to what ImGuiListClipper does. Or split your data into fixed height items to allow random-seeking into your list.
- ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4,1)); // Tighten spacing
+ // - That your items are evenly spaced (same height)
+ // - That you have cheap random access to your elements (you can access them given their index,
+ // without processing all the ones before)
+ // You cannot this code as-is if a filter is active because it breaks the 'cheap random-access' property.
+ // We would need random-access on the post-filtered list.
+ // A typical application wanting coarse clipping and filtering may want to pre-compute an array of indices
+ // or offsets of items that passed the filtering test, recomputing this array when user changes the filter,
+ // and appending newly elements as they are inserted. This is left as a task to the user until we can manage
+ // to improve this example code!
+ // If your items are of variable height:
+ // - Split them into same height items would be simpler and facilitate random-seeking into your list.
+ // - Consider using manual call to IsRectVisible() and skipping extraneous decoration from your items.
+ ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 1)); // Tighten spacing
if (copy_to_clipboard)
ImGui::LogToClipboard();
for (int i = 0; i < Items.Size; i++)
@@ -3787,12 +6285,16 @@ struct ExampleAppConsole
if (!Filter.PassFilter(item))
continue;
- // Normally you would store more information in your item (e.g. make Items[] an array of structure, store color/type etc.)
- bool pop_color = false;
- if (strstr(item, "[error]")) { ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.4f, 0.4f, 1.0f)); pop_color = true; }
- else if (strncmp(item, "# ", 2) == 0) { ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.8f, 0.6f, 1.0f)); pop_color = true; }
+ // Normally you would store more information in your item than just a string.
+ // (e.g. make Items[] an array of structure, store color/type etc.)
+ ImVec4 color;
+ bool has_color = false;
+ if (strstr(item, "[error]")) { color = ImVec4(1.0f, 0.4f, 0.4f, 1.0f); has_color = true; }
+ else if (strncmp(item, "# ", 2) == 0) { color = ImVec4(1.0f, 0.8f, 0.6f, 1.0f); has_color = true; }
+ if (has_color)
+ ImGui::PushStyleColor(ImGuiCol_Text, color);
ImGui::TextUnformatted(item);
- if (pop_color)
+ if (has_color)
ImGui::PopStyleColor();
}
if (copy_to_clipboard)
@@ -3808,7 +6310,8 @@ struct ExampleAppConsole
// Command-line
bool reclaim_focus = false;
- if (ImGui::InputText("Input", InputBuf, IM_ARRAYSIZE(InputBuf), ImGuiInputTextFlags_EnterReturnsTrue|ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_CallbackHistory, &TextEditCallbackStub, (void*)this))
+ ImGuiInputTextFlags input_text_flags = ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory;
+ if (ImGui::InputText("Input", InputBuf, IM_ARRAYSIZE(InputBuf), input_text_flags, &TextEditCallbackStub, (void*)this))
{
char* s = InputBuf;
Strtrim(s);
@@ -3830,9 +6333,10 @@ struct ExampleAppConsole
{
AddLog("# %s\n", command_line);
- // Insert into history. First find match and delete it so it can be pushed to the back. This isn't trying to be smart or optimal.
+ // Insert into history. First find match and delete it so it can be pushed to the back.
+ // This isn't trying to be smart or optimal.
HistoryPos = -1;
- for (int i = History.Size-1; i >= 0; i--)
+ for (int i = History.Size - 1; i >= 0; i--)
if (Stricmp(History[i], command_line) == 0)
{
free(History[i]);
@@ -3863,11 +6367,12 @@ struct ExampleAppConsole
AddLog("Unknown command: '%s'\n", command_line);
}
- // On commad input, we scroll to bottom even if AutoScroll==false
+ // On command input, we scroll to bottom even if AutoScroll==false
ScrollToBottom = true;
}
- static int TextEditCallbackStub(ImGuiInputTextCallbackData* data) // In C++11 you are better off using lambdas for this sort of forwarding callbacks
+ // In C++11 you'd be better off using lambdas for this sort of forwarding callbacks
+ static int TextEditCallbackStub(ImGuiInputTextCallbackData* data)
{
ExampleAppConsole* console = (ExampleAppConsole*)data->UserData;
return console->TextEditCallback(data);
@@ -3896,24 +6401,25 @@ struct ExampleAppConsole
// Build a list of candidates
ImVector candidates;
for (int i = 0; i < Commands.Size; i++)
- if (Strnicmp(Commands[i], word_start, (int)(word_end-word_start)) == 0)
+ if (Strnicmp(Commands[i], word_start, (int)(word_end - word_start)) == 0)
candidates.push_back(Commands[i]);
if (candidates.Size == 0)
{
// No match
- AddLog("No match for \"%.*s\"!\n", (int)(word_end-word_start), word_start);
+ AddLog("No match for \"%.*s\"!\n", (int)(word_end - word_start), word_start);
}
else if (candidates.Size == 1)
{
- // Single match. Delete the beginning of the word and replace it entirely so we've got nice casing
- data->DeleteChars((int)(word_start-data->Buf), (int)(word_end-word_start));
+ // Single match. Delete the beginning of the word and replace it entirely so we've got nice casing.
+ data->DeleteChars((int)(word_start - data->Buf), (int)(word_end - word_start));
data->InsertChars(data->CursorPos, candidates[0]);
data->InsertChars(data->CursorPos, " ");
}
else
{
- // Multiple matches. Complete as much as we can, so inputing "C" will complete to "CL" and display "CLEAR" and "CLASSIFY"
+ // Multiple matches. Complete as much as we can..
+ // So inputing "C"+Tab will complete to "CL" then display "CLEAR" and "CLASSIFY" as matches.
int match_len = (int)(word_end - word_start);
for (;;)
{
@@ -3931,7 +6437,7 @@ struct ExampleAppConsole
if (match_len > 0)
{
- data->DeleteChars((int)(word_start - data->Buf), (int)(word_end-word_start));
+ data->DeleteChars((int)(word_start - data->Buf), (int)(word_end - word_start));
data->InsertChars(data->CursorPos, candidates[0], candidates[0] + match_len);
}
@@ -3992,8 +6498,8 @@ struct ExampleAppLog
{
ImGuiTextBuffer Buf;
ImGuiTextFilter Filter;
- ImVector LineOffsets; // Index to lines offset. We maintain this with AddLog() calls, allowing us to have a random access on lines
- bool AutoScroll; // Keep scrolling if already at the bottom
+ ImVector LineOffsets; // Index to lines offset. We maintain this with AddLog() calls.
+ bool AutoScroll; // Keep scrolling if already at the bottom.
ExampleAppLog()
{
@@ -4046,7 +6552,7 @@ struct ExampleAppLog
Filter.Draw("Filter", -100.0f);
ImGui::Separator();
- ImGui::BeginChild("scrolling", ImVec2(0,0), false, ImGuiWindowFlags_HorizontalScrollbar);
+ ImGui::BeginChild("scrolling", ImVec2(0, 0), false, ImGuiWindowFlags_HorizontalScrollbar);
if (clear)
Clear();
@@ -4060,8 +6566,8 @@ struct ExampleAppLog
{
// In this example we don't use the clipper when Filter is enabled.
// This is because we don't have a random access on the result on our filter.
- // A real application processing logs with ten of thousands of entries may want to store the result of search/filter.
- // especially if the filtering function is not trivial (e.g. reg-exp).
+ // A real application processing logs with ten of thousands of entries may want to store the result of
+ // search/filter.. especially if the filtering function is not trivial (e.g. reg-exp).
for (int line_no = 0; line_no < LineOffsets.Size; line_no++)
{
const char* line_start = buf + LineOffsets[line_no];
@@ -4074,13 +6580,17 @@ struct ExampleAppLog
{
// The simplest and easy way to display the entire buffer:
// ImGui::TextUnformatted(buf_begin, buf_end);
- // And it'll just work. TextUnformatted() has specialization for large blob of text and will fast-forward to skip non-visible lines.
- // Here we instead demonstrate using the clipper to only process lines that are within the visible area.
- // If you have tens of thousands of items and their processing cost is non-negligible, coarse clipping them on your side is recommended.
- // Using ImGuiListClipper requires A) random access into your data, and B) items all being the same height,
+ // And it'll just work. TextUnformatted() has specialization for large blob of text and will fast-forward
+ // to skip non-visible lines. Here we instead demonstrate using the clipper to only process lines that are
+ // within the visible area.
+ // If you have tens of thousands of items and their processing cost is non-negligible, coarse clipping them
+ // on your side is recommended. Using ImGuiListClipper requires
+ // - A) random access into your data
+ // - B) items all being the same height,
// both of which we can handle since we an array pointing to the beginning of each line of text.
- // When using the filter (in the block of code above) we don't have random access into the data to display anymore, which is why we don't use the clipper.
- // Storing or skimming through the search result would make it possible (and would be recommended if you want to search through tens of thousands of entries)
+ // When using the filter (in the block of code above) we don't have random access into the data to display
+ // anymore, which is why we don't use the clipper. Storing or skimming through the search result would make
+ // it possible (and would be recommended if you want to search through tens of thousands of entries).
ImGuiListClipper clipper;
clipper.Begin(LineOffsets.Size);
while (clipper.Step())
@@ -4117,12 +6627,14 @@ static void ShowExampleAppLog(bool* p_open)
if (ImGui::SmallButton("[Debug] Add 5 entries"))
{
static int counter = 0;
+ const char* categories[3] = { "info", "warn", "error" };
+ const char* words[] = { "Bumfuzzled", "Cattywampus", "Snickersnee", "Abibliophobia", "Absquatulate", "Nincompoop", "Pauciloquent" };
for (int n = 0; n < 5; n++)
{
- const char* categories[3] = { "info", "warn", "error" };
- const char* words[] = { "Bumfuzzled", "Cattywampus", "Snickersnee", "Abibliophobia", "Absquatulate", "Nincompoop", "Pauciloquent" };
+ const char* category = categories[counter % IM_ARRAYSIZE(categories)];
+ const char* word = words[counter % IM_ARRAYSIZE(words)];
log.AddLog("[%05d] [%s] Hello, current time is %.1f, here's a word: '%s'\n",
- ImGui::GetFrameCount(), categories[counter % IM_ARRAYSIZE(categories)], ImGui::GetTime(), words[counter % IM_ARRAYSIZE(words)]);
+ ImGui::GetFrameCount(), category, ImGui::GetTime(), word);
counter++;
}
}
@@ -4152,43 +6664,47 @@ static void ShowExampleAppLayout(bool* p_open)
ImGui::EndMenuBar();
}
- // left
+ // Left
static int selected = 0;
- ImGui::BeginChild("left pane", ImVec2(150, 0), true);
- for (int i = 0; i < 100; i++)
{
- char label[128];
- sprintf(label, "MyObject %d", i);
- if (ImGui::Selectable(label, selected == i))
- selected = i;
+ ImGui::BeginChild("left pane", ImVec2(150, 0), true);
+ for (int i = 0; i < 100; i++)
+ {
+ char label[128];
+ sprintf(label, "MyObject %d", i);
+ if (ImGui::Selectable(label, selected == i))
+ selected = i;
+ }
+ ImGui::EndChild();
}
- ImGui::EndChild();
ImGui::SameLine();
- // right
- ImGui::BeginGroup();
+ // Right
+ {
+ ImGui::BeginGroup();
ImGui::BeginChild("item view", ImVec2(0, -ImGui::GetFrameHeightWithSpacing())); // Leave room for 1 line below us
- ImGui::Text("MyObject: %d", selected);
- ImGui::Separator();
- if (ImGui::BeginTabBar("##Tabs", ImGuiTabBarFlags_None))
+ ImGui::Text("MyObject: %d", selected);
+ ImGui::Separator();
+ if (ImGui::BeginTabBar("##Tabs", ImGuiTabBarFlags_None))
+ {
+ if (ImGui::BeginTabItem("Description"))
{
- if (ImGui::BeginTabItem("Description"))
- {
- ImGui::TextWrapped("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ");
- ImGui::EndTabItem();
- }
- if (ImGui::BeginTabItem("Details"))
- {
- ImGui::Text("ID: 0123456789");
- ImGui::EndTabItem();
- }
- ImGui::EndTabBar();
+ ImGui::TextWrapped("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ");
+ ImGui::EndTabItem();
}
+ if (ImGui::BeginTabItem("Details"))
+ {
+ ImGui::Text("ID: 0123456789");
+ ImGui::EndTabItem();
+ }
+ ImGui::EndTabBar();
+ }
ImGui::EndChild();
if (ImGui::Button("Revert")) {}
ImGui::SameLine();
if (ImGui::Button("Save")) {}
- ImGui::EndGroup();
+ ImGui::EndGroup();
+ }
}
ImGui::End();
}
@@ -4197,70 +6713,80 @@ static void ShowExampleAppLayout(bool* p_open)
// [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor()
//-----------------------------------------------------------------------------
+static void ShowPlaceholderObject(const char* prefix, int uid)
+{
+ // Use object uid as identifier. Most commonly you could also use the object pointer as a base ID.
+ ImGui::PushID(uid);
+
+ // Text and Tree nodes are less high than framed widgets, using AlignTextToFramePadding() we add vertical spacing to make the tree lines equal high.
+ ImGui::TableNextRow();
+ ImGui::TableSetColumnIndex(0);
+ ImGui::AlignTextToFramePadding();
+ bool node_open = ImGui::TreeNode("Object", "%s_%u", prefix, uid);
+ ImGui::TableSetColumnIndex(1);
+ ImGui::Text("my sailor is rich");
+
+ if (node_open)
+ {
+ static float placeholder_members[8] = { 0.0f, 0.0f, 1.0f, 3.1416f, 100.0f, 999.0f };
+ for (int i = 0; i < 8; i++)
+ {
+ ImGui::PushID(i); // Use field index as identifier.
+ if (i < 2)
+ {
+ ShowPlaceholderObject("Child", 424242);
+ }
+ else
+ {
+ // Here we use a TreeNode to highlight on hover (we could use e.g. Selectable as well)
+ ImGui::TableNextRow();
+ ImGui::TableSetColumnIndex(0);
+ ImGui::AlignTextToFramePadding();
+ ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_Bullet;
+ ImGui::TreeNodeEx("Field", flags, "Field_%d", i);
+
+ ImGui::TableSetColumnIndex(1);
+ ImGui::SetNextItemWidth(-FLT_MIN);
+ if (i >= 5)
+ ImGui::InputFloat("##value", &placeholder_members[i], 1.0f);
+ else
+ ImGui::DragFloat("##value", &placeholder_members[i], 0.01f);
+ ImGui::NextColumn();
+ }
+ ImGui::PopID();
+ }
+ ImGui::TreePop();
+ }
+ ImGui::PopID();
+}
+
// Demonstrate create a simple property editor.
static void ShowExampleAppPropertyEditor(bool* p_open)
{
- ImGui::SetNextWindowSize(ImVec2(430,450), ImGuiCond_FirstUseEver);
+ ImGui::SetNextWindowSize(ImVec2(430, 450), ImGuiCond_FirstUseEver);
if (!ImGui::Begin("Example: Property editor", p_open))
{
ImGui::End();
return;
}
- HelpMarker("This example shows how you may implement a property editor using two columns.\nAll objects/fields data are dummies here.\nRemember that in many simple cases, you can use ImGui::SameLine(xxx) to position\nyour cursor horizontally instead of using the Columns() API.");
+ HelpMarker(
+ "This example shows how you may implement a property editor using two columns.\n"
+ "All objects/fields data are dummies here.\n"
+ "Remember that in many simple cases, you can use ImGui::SameLine(xxx) to position\n"
+ "your cursor horizontally instead of using the Columns() API.");
- ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2,2));
- ImGui::Columns(2);
- ImGui::Separator();
-
- struct funcs
+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2, 2));
+ if (ImGui::BeginTable("split", 2, ImGuiTableFlags_BordersOuter | ImGuiTableFlags_Resizable))
{
- static void ShowDummyObject(const char* prefix, int uid)
+ // Iterate placeholder objects (all the same data)
+ for (int obj_i = 0; obj_i < 4; obj_i++)
{
- ImGui::PushID(uid); // Use object uid as identifier. Most commonly you could also use the object pointer as a base ID.
- ImGui::AlignTextToFramePadding(); // Text and Tree nodes are less high than regular widgets, here we add vertical spacing to make the tree lines equal high.
- bool node_open = ImGui::TreeNode("Object", "%s_%u", prefix, uid);
- ImGui::NextColumn();
- ImGui::AlignTextToFramePadding();
- ImGui::Text("my sailor is rich");
- ImGui::NextColumn();
- if (node_open)
- {
- static float dummy_members[8] = { 0.0f,0.0f,1.0f,3.1416f,100.0f,999.0f };
- for (int i = 0; i < 8; i++)
- {
- ImGui::PushID(i); // Use field index as identifier.
- if (i < 2)
- {
- ShowDummyObject("Child", 424242);
- }
- else
- {
- // Here we use a TreeNode to highlight on hover (we could use e.g. Selectable as well)
- ImGui::AlignTextToFramePadding();
- ImGui::TreeNodeEx("Field", ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_Bullet, "Field_%d", i);
- ImGui::NextColumn();
- ImGui::SetNextItemWidth(-1);
- if (i >= 5)
- ImGui::InputFloat("##value", &dummy_members[i], 1.0f);
- else
- ImGui::DragFloat("##value", &dummy_members[i], 0.01f);
- ImGui::NextColumn();
- }
- ImGui::PopID();
- }
- ImGui::TreePop();
- }
- ImGui::PopID();
+ ShowPlaceholderObject("Object", obj_i);
+ //ImGui::Separator();
}
- };
-
- // Iterate dummy objects with dummy members (all the same data)
- for (int obj_i = 0; obj_i < 3; obj_i++)
- funcs::ShowDummyObject("Object", obj_i);
-
- ImGui::Columns(1);
- ImGui::Separator();
+ ImGui::EndTable();
+ }
ImGui::PopStyleVar();
ImGui::End();
}
@@ -4272,7 +6798,7 @@ static void ShowExampleAppPropertyEditor(bool* p_open)
// Demonstrate/test rendering huge amount of text, and the incidence of clipping.
static void ShowExampleAppLongText(bool* p_open)
{
- ImGui::SetNextWindowSize(ImVec2(520,600), ImGuiCond_FirstUseEver);
+ ImGui::SetNextWindowSize(ImVec2(520, 600), ImGuiCond_FirstUseEver);
if (!ImGui::Begin("Example: Long text display", p_open))
{
ImGui::End();
@@ -4283,14 +6809,17 @@ static void ShowExampleAppLongText(bool* p_open)
static ImGuiTextBuffer log;
static int lines = 0;
ImGui::Text("Printing unusually long amount of text.");
- ImGui::Combo("Test type", &test_type, "Single call to TextUnformatted()\0Multiple calls to Text(), clipped\0Multiple calls to Text(), not clipped (slow)\0");
+ ImGui::Combo("Test type", &test_type,
+ "Single call to TextUnformatted()\0"
+ "Multiple calls to Text(), clipped\0"
+ "Multiple calls to Text(), not clipped (slow)\0");
ImGui::Text("Buffer contents: %d lines, %d bytes", lines, log.size());
if (ImGui::Button("Clear")) { log.clear(); lines = 0; }
ImGui::SameLine();
if (ImGui::Button("Add 1000 lines"))
{
for (int i = 0; i < 1000; i++)
- log.appendf("%i The quick brown fox jumps over the lazy dog\n", lines+i);
+ log.appendf("%i The quick brown fox jumps over the lazy dog\n", lines + i);
lines += 1000;
}
ImGui::BeginChild("Log");
@@ -4303,8 +6832,9 @@ static void ShowExampleAppLongText(bool* p_open)
case 1:
{
// Multiple calls to Text(), manually coarsely clipped - demonstrate how to use the ImGuiListClipper helper.
- ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0));
- ImGuiListClipper clipper(lines);
+ ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
+ ImGuiListClipper clipper;
+ clipper.Begin(lines);
while (clipper.Step())
for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
ImGui::Text("%i The quick brown fox jumps over the lazy dog", i);
@@ -4313,7 +6843,7 @@ static void ShowExampleAppLongText(bool* p_open)
}
case 2:
// Multiple calls to Text(), not clipped (slow)
- ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0));
+ ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
for (int i = 0; i < lines; i++)
ImGui::Text("%i The quick brown fox jumps over the lazy dog", i);
ImGui::PopStyleVar();
@@ -4337,7 +6867,10 @@ static void ShowExampleAppAutoResize(bool* p_open)
}
static int lines = 10;
- ImGui::Text("Window will resize every-frame to the size of its content.\nNote that you probably don't want to query the window size to\noutput your content because that would create a feedback loop.");
+ ImGui::TextUnformatted(
+ "Window will resize every-frame to the size of its content.\n"
+ "Note that you probably don't want to query the window size to\n"
+ "output your content because that would create a feedback loop.");
ImGui::SliderInt("Number of lines", &lines, 1, 20);
for (int i = 0; i < lines; i++)
ImGui::Text("%*sThis is line %d", i * 4, "", i); // Pad with space to extend size horizontally
@@ -4351,12 +6884,24 @@ static void ShowExampleAppAutoResize(bool* p_open)
// Demonstrate creating a window with custom resize constraints.
static void ShowExampleAppConstrainedResize(bool* p_open)
{
- struct CustomConstraints // Helper functions to demonstrate programmatic constraints
+ struct CustomConstraints
{
- static void Square(ImGuiSizeCallbackData* data) { data->DesiredSize.x = data->DesiredSize.y = (data->DesiredSize.x > data->DesiredSize.y ? data->DesiredSize.x : data->DesiredSize.y); }
+ // Helper functions to demonstrate programmatic constraints
+ static void Square(ImGuiSizeCallbackData* data) { 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); }
};
+ const char* test_desc[] =
+ {
+ "Resize vertical only",
+ "Resize horizontal only",
+ "Width > 100, Height > 100",
+ "Width 400-500",
+ "Height 400-500",
+ "Custom: Always Square",
+ "Custom: Fixed Steps (100)",
+ };
+
static bool auto_resize = false;
static int type = 0;
static int display_lines = 10;
@@ -4371,23 +6916,11 @@ static void ShowExampleAppConstrainedResize(bool* p_open)
ImGuiWindowFlags flags = auto_resize ? ImGuiWindowFlags_AlwaysAutoResize : 0;
if (ImGui::Begin("Example: Constrained Resize", p_open, flags))
{
- const char* desc[] =
- {
- "Resize vertical only",
- "Resize horizontal only",
- "Width > 100, Height > 100",
- "Width 400-500",
- "Height 400-500",
- "Custom: Always Square",
- "Custom: Fixed Steps (100)",
- };
- if (ImGui::IsWindowDocked())
- ImGui::Text("Warning: Sizing Constraints won't work if the window is docked!");
if (ImGui::Button("200x200")) { ImGui::SetWindowSize(ImVec2(200, 200)); } ImGui::SameLine();
if (ImGui::Button("500x500")) { ImGui::SetWindowSize(ImVec2(500, 500)); } ImGui::SameLine();
if (ImGui::Button("800x200")) { ImGui::SetWindowSize(ImVec2(800, 200)); }
ImGui::SetNextItemWidth(200);
- ImGui::Combo("Constraint", &type, desc, IM_ARRAYSIZE(desc));
+ ImGui::Combo("Constraint", &type, test_desc, IM_ARRAYSIZE(test_desc));
ImGui::SetNextItemWidth(200);
ImGui::DragInt("Lines", &display_lines, 0.2f, 1, 100);
ImGui::Checkbox("Auto-resize", &auto_resize);
@@ -4401,23 +6934,23 @@ static void ShowExampleAppConstrainedResize(bool* p_open)
// [SECTION] Example App: Simple Overlay / ShowExampleAppSimpleOverlay()
//-----------------------------------------------------------------------------
-// Demonstrate creating a simple static window with no decoration + a context-menu to choose which corner of the screen to use.
+// Demonstrate creating a simple static window with no decoration
+// + a context-menu to choose which corner of the screen to use.
static void ShowExampleAppSimpleOverlay(bool* p_open)
{
- // FIXME-VIEWPORT: Select a default viewport
const float DISTANCE = 10.0f;
static int corner = 0;
ImGuiIO& io = ImGui::GetIO();
+ ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav;
if (corner != -1)
{
- ImGuiViewport* viewport = ImGui::GetMainViewport();
- ImVec2 window_pos = ImVec2((corner & 1) ? (viewport->Pos.x + viewport->Size.x - DISTANCE) : (viewport->Pos.x + DISTANCE), (corner & 2) ? (viewport->Pos.y + viewport->Size.y - DISTANCE) : (viewport->Pos.y + DISTANCE));
+ window_flags |= ImGuiWindowFlags_NoMove;
+ ImVec2 window_pos = ImVec2((corner & 1) ? io.DisplaySize.x - DISTANCE : DISTANCE, (corner & 2) ? io.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::SetNextWindowViewport(viewport->ID);
}
ImGui::SetNextWindowBgAlpha(0.35f); // Transparent background
- if (ImGui::Begin("Example: Simple overlay", p_open, (corner != -1 ? ImGuiWindowFlags_NoMove : 0) | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav))
+ if (ImGui::Begin("Example: Simple overlay", p_open, window_flags))
{
ImGui::Text("Simple overlay\n" "in the corner of the screen.\n" "(right-click to change position)");
ImGui::Separator();
@@ -4444,7 +6977,8 @@ static void ShowExampleAppSimpleOverlay(bool* p_open)
//-----------------------------------------------------------------------------
// Demonstrate using "##" and "###" in identifiers to manipulate ID generation.
-// This apply to all regular items as well. Read FAQ section "How can I have multiple widgets with the same label? Can I have widget without a label? (Yes). A primer on the purpose of labels/IDs." for details.
+// This apply to all regular items as well.
+// Read FAQ section "How can I have multiple widgets with the same label?" for details.
static void ShowExampleAppWindowTitles(bool*)
{
// By default, Windows are uniquely identified by their title.
@@ -4483,111 +7017,208 @@ static void ShowExampleAppCustomRendering(bool* p_open)
return;
}
- // Tip: If you do a lot of custom rendering, you probably want to use your own geometrical types and benefit of overloaded operators, etc.
- // Define IM_VEC2_CLASS_EXTRA in imconfig.h to create implicit conversions between your types and ImVec2/ImVec4.
- // ImGui defines overloaded operators but they are internal to imgui.cpp and not exposed outside (to avoid messing with your types)
- // In this example we are not using the maths operators!
- ImDrawList* draw_list = ImGui::GetWindowDrawList();
+ // Tip: If you do a lot of custom rendering, you probably want to use your own geometrical types and benefit of
+ // overloaded operators, etc. Define IM_VEC2_CLASS_EXTRA in imconfig.h to create implicit conversions between your
+ // types and ImVec2/ImVec4. Dear ImGui defines overloaded operators but they are internal to imgui.cpp and not
+ // exposed outside (to avoid messing with your types) In this example we are not using the maths operators!
if (ImGui::BeginTabBar("##TabBar"))
{
- // Primitives
if (ImGui::BeginTabItem("Primitives"))
{
+ ImGui::PushItemWidth(-ImGui::GetFontSize() * 15);
+ ImDrawList* draw_list = ImGui::GetWindowDrawList();
+
+ // Draw gradients
+ // (note that those are currently exacerbating our sRGB/Linear issues)
+ // Calling ImGui::GetColorU32() multiplies the given colors by the current Style Alpha, but you may pass the IM_COL32() directly as well..
+ ImGui::Text("Gradients");
+ ImVec2 gradient_size = ImVec2(ImGui::CalcItemWidth(), ImGui::GetFrameHeight());
+ {
+ ImVec2 p0 = ImGui::GetCursorScreenPos();
+ ImVec2 p1 = ImVec2(p0.x + gradient_size.x, p0.y + gradient_size.y);
+ ImU32 col_a = ImGui::GetColorU32(IM_COL32(0, 0, 0, 255));
+ ImU32 col_b = ImGui::GetColorU32(IM_COL32(255, 255, 255, 255));
+ draw_list->AddRectFilledMultiColor(p0, p1, col_a, col_b, col_b, col_a);
+ ImGui::InvisibleButton("##gradient1", gradient_size);
+ }
+ {
+ ImVec2 p0 = ImGui::GetCursorScreenPos();
+ ImVec2 p1 = ImVec2(p0.x + gradient_size.x, p0.y + gradient_size.y);
+ ImU32 col_a = ImGui::GetColorU32(IM_COL32(0, 255, 0, 255));
+ ImU32 col_b = ImGui::GetColorU32(IM_COL32(255, 0, 0, 255));
+ draw_list->AddRectFilledMultiColor(p0, p1, col_a, col_b, col_b, col_a);
+ ImGui::InvisibleButton("##gradient2", gradient_size);
+ }
+
+ // Draw a bunch of primitives
+ ImGui::Text("All primitives");
static float sz = 36.0f;
static float thickness = 3.0f;
+ static int ngon_sides = 6;
+ static bool circle_segments_override = false;
+ static int circle_segments_override_v = 12;
+ static bool curve_segments_override = false;
+ static int curve_segments_override_v = 8;
static ImVec4 colf = ImVec4(1.0f, 1.0f, 0.4f, 1.0f);
ImGui::DragFloat("Size", &sz, 0.2f, 2.0f, 72.0f, "%.0f");
ImGui::DragFloat("Thickness", &thickness, 0.05f, 1.0f, 8.0f, "%.02f");
+ ImGui::SliderInt("N-gon sides", &ngon_sides, 3, 12);
+ ImGui::Checkbox("##circlesegmentoverride", &circle_segments_override);
+ ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x);
+ circle_segments_override |= ImGui::SliderInt("Circle segments override", &circle_segments_override_v, 3, 40);
+ ImGui::Checkbox("##curvessegmentoverride", &curve_segments_override);
+ ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x);
+ curve_segments_override |= ImGui::SliderInt("Curves segments override", &curve_segments_override_v, 3, 40);
ImGui::ColorEdit4("Color", &colf.x);
+
const ImVec2 p = ImGui::GetCursorScreenPos();
const ImU32 col = ImColor(colf);
- float x = p.x + 4.0f, y = p.y + 4.0f;
- float spacing = 10.0f;
- ImDrawCornerFlags corners_none = 0;
- ImDrawCornerFlags corners_all = ImDrawCornerFlags_All;
- ImDrawCornerFlags corners_tl_br = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotRight;
+ const float spacing = 10.0f;
+ const ImDrawCornerFlags corners_none = 0;
+ const ImDrawCornerFlags corners_all = ImDrawCornerFlags_All;
+ const ImDrawCornerFlags corners_tl_br = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotRight;
+ const int circle_segments = circle_segments_override ? circle_segments_override_v : 0;
+ const int curve_segments = curve_segments_override ? curve_segments_override_v : 0;
+ float x = p.x + 4.0f;
+ float y = p.y + 4.0f;
for (int n = 0; n < 2; n++)
{
// First line uses a thickness of 1.0f, second line uses the configurable thickness
float th = (n == 0) ? 1.0f : thickness;
- draw_list->AddCircle(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, 6, th); x += sz + spacing; // Hexagon
- draw_list->AddCircle(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, 20, th); x += sz + spacing; // Circle
- draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 0.0f, corners_none, th); x += sz + spacing; // Square
- draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f, corners_all, th); x += sz + spacing; // Square with all rounded corners
- draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f, corners_tl_br, th); x += sz + spacing; // Square with two rounded corners
- draw_list->AddTriangle(ImVec2(x+sz*0.5f,y), ImVec2(x+sz, y+sz-0.5f), ImVec2(x, y+sz-0.5f), col, th); x += sz + spacing; // Triangle
- draw_list->AddTriangle(ImVec2(x+sz*0.2f,y), ImVec2(x, y+sz-0.5f), ImVec2(x+sz*0.4f, y+sz-0.5f), col, th); x += sz*0.4f + spacing; // Thin triangle
- draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y), col, th); x += sz + spacing; // Horizontal line (note: drawing a filled rectangle will be faster!)
- draw_list->AddLine(ImVec2(x, y), ImVec2(x, y + sz), col, th); x += spacing; // Vertical line (note: drawing a filled rectangle will be faster!)
- draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y + sz), col, th); x += sz + spacing; // Diagonal line
- draw_list->AddBezierCurve(ImVec2(x, y), ImVec2(x + sz*1.3f, y + sz*0.3f), ImVec2(x + sz - sz*1.3f, y + sz - sz*0.3f), ImVec2(x + sz, y + sz), col, th);
+ draw_list->AddNgon(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, ngon_sides, th); x += sz + spacing; // N-gon
+ draw_list->AddCircle(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, circle_segments, th); x += sz + spacing; // Circle
+ draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 0.0f, corners_none, th); x += sz + spacing; // Square
+ draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f, corners_all, th); x += sz + spacing; // Square with all rounded corners
+ draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f, corners_tl_br, th); x += sz + spacing; // Square with two rounded corners
+ draw_list->AddTriangle(ImVec2(x+sz*0.5f,y), ImVec2(x+sz, y+sz-0.5f), ImVec2(x, y+sz-0.5f), col, th);x += sz + spacing; // Triangle
+ //draw_list->AddTriangle(ImVec2(x+sz*0.2f,y), ImVec2(x, y+sz-0.5f), ImVec2(x+sz*0.4f, y+sz-0.5f), col, th);x+= sz*0.4f + spacing; // Thin triangle
+ draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y), col, th); x += sz + spacing; // Horizontal line (note: drawing a filled rectangle will be faster!)
+ draw_list->AddLine(ImVec2(x, y), ImVec2(x, y + sz), col, th); x += spacing; // Vertical line (note: drawing a filled rectangle will be faster!)
+ draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y + sz), col, th); x += sz + spacing; // Diagonal line
+
+ // Quadratic Bezier Curve (3 control points)
+ ImVec2 cp3[3] = { ImVec2(x, y + sz * 0.6f), ImVec2(x + sz * 0.5f, y - sz * 0.4f), ImVec2(x + sz, y + sz) };
+ draw_list->AddBezierQuadratic(cp3[0], cp3[1], cp3[2], col, th, curve_segments); x += sz + spacing;
+
+ // Cubic Bezier Curve (4 control points)
+ ImVec2 cp4[4] = { ImVec2(x, y), ImVec2(x + sz * 1.3f, y + sz * 0.3f), ImVec2(x + sz - sz * 1.3f, y + sz - sz * 0.3f), ImVec2(x + sz, y + sz) };
+ draw_list->AddBezierCubic(cp4[0], cp4[1], cp4[2], cp4[3], col, th, curve_segments);
+
x = p.x + 4;
y += sz + spacing;
}
- draw_list->AddCircleFilled(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, 6); x += sz + spacing; // Hexagon
- draw_list->AddCircleFilled(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, 32); x += sz + spacing; // Circle
- draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col); x += sz + spacing; // Square
- draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f); x += sz + spacing; // Square with all rounded corners
- draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f, corners_tl_br); x += sz + spacing; // Square with two rounded corners
- draw_list->AddTriangleFilled(ImVec2(x+sz*0.5f,y), ImVec2(x+sz, y+sz-0.5f), ImVec2(x, y+sz-0.5f), col); x += sz + spacing; // Triangle
- draw_list->AddTriangleFilled(ImVec2(x+sz*0.2f,y), ImVec2(x, y+sz-0.5f), ImVec2(x+sz*0.4f, y+sz-0.5f), col); x += sz*0.4f + spacing; // Thin triangle
- draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + thickness), col); x += sz + spacing; // Horizontal line (faster than AddLine, but only handle integer thickness)
- draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + thickness, y + sz), col); x += spacing*2.0f; // Vertical line (faster than AddLine, but only handle integer thickness)
- draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + 1, y + 1), col); x += sz; // Pixel (faster than AddLine)
+ draw_list->AddNgonFilled(ImVec2(x + sz * 0.5f, y + sz * 0.5f), sz*0.5f, col, ngon_sides); x += sz + spacing; // N-gon
+ draw_list->AddCircleFilled(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, circle_segments); x += sz + spacing; // Circle
+ draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col); x += sz + spacing; // Square
+ draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f); x += sz + spacing; // Square with all rounded corners
+ draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f, corners_tl_br); x += sz + spacing; // Square with two rounded corners
+ draw_list->AddTriangleFilled(ImVec2(x+sz*0.5f,y), ImVec2(x+sz, y+sz-0.5f), ImVec2(x, y+sz-0.5f), col); x += sz + spacing; // Triangle
+ //draw_list->AddTriangleFilled(ImVec2(x+sz*0.2f,y), ImVec2(x, y+sz-0.5f), ImVec2(x+sz*0.4f, y+sz-0.5f), col); x += sz*0.4f + spacing; // Thin triangle
+ draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + thickness), col); x += sz + spacing; // Horizontal line (faster than AddLine, but only handle integer thickness)
+ draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + thickness, y + sz), col); x += spacing * 2.0f;// Vertical line (faster than AddLine, but only handle integer thickness)
+ draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + 1, y + 1), col); x += sz; // Pixel (faster than AddLine)
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) * 9.8f, (sz + spacing) * 3));
+
+ ImGui::Dummy(ImVec2((sz + spacing) * 10.2f, (sz + spacing) * 3.0f));
+ ImGui::PopItemWidth();
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("Canvas"))
{
static ImVector points;
+ static ImVec2 scrolling(0.0f, 0.0f);
+ static bool opt_enable_grid = true;
+ static bool opt_enable_context_menu = true;
static bool adding_line = false;
- if (ImGui::Button("Clear")) points.clear();
- if (points.Size >= 2) { ImGui::SameLine(); if (ImGui::Button("Undo")) { points.pop_back(); points.pop_back(); } }
- ImGui::Text("Left-click and drag to add lines,\nRight-click to undo");
- // Here we are using InvisibleButton() as a convenience to 1) advance the cursor and 2) allows us to use IsItemHovered()
- // But you can also draw directly and poll mouse/keyboard by yourself. You can manipulate the cursor using GetCursorPos() and SetCursorPos().
- // If you only use the ImDrawList API, you can notify the owner window of its extends by using SetCursorPos(max).
- ImVec2 canvas_pos = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates!
- 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), 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));
+ ImGui::Checkbox("Enable grid", &opt_enable_grid);
+ ImGui::Checkbox("Enable context menu", &opt_enable_context_menu);
+ ImGui::Text("Mouse Left: drag to add lines,\nMouse Right: drag to scroll, click for context menu.");
- bool adding_preview = false;
- ImGui::InvisibleButton("canvas", canvas_size);
- ImVec2 mouse_pos_in_canvas = ImVec2(ImGui::GetIO().MousePos.x - canvas_pos.x, ImGui::GetIO().MousePos.y - canvas_pos.y);
+ // Typically you would use a BeginChild()/EndChild() pair to benefit from a clipping region + own scrolling.
+ // Here we demonstrate that this can be replaced by simple offsetting + custom drawing + PushClipRect/PopClipRect() calls.
+ // To use a child window instead we could use, e.g:
+ // ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); // Disable padding
+ // ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(50, 50, 50, 255)); // Set a background color
+ // ImGui::BeginChild("canvas", ImVec2(0.0f, 0.0f), true, ImGuiWindowFlags_NoMove);
+ // ImGui::PopStyleColor();
+ // ImGui::PopStyleVar();
+ // [...]
+ // ImGui::EndChild();
+
+ // Using InvisibleButton() as a convenience 1) it will advance the layout cursor and 2) allows us to use IsItemHovered()/IsItemActive()
+ ImVec2 canvas_p0 = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates!
+ ImVec2 canvas_sz = ImGui::GetContentRegionAvail(); // Resize canvas to what's available
+ if (canvas_sz.x < 50.0f) canvas_sz.x = 50.0f;
+ if (canvas_sz.y < 50.0f) canvas_sz.y = 50.0f;
+ ImVec2 canvas_p1 = ImVec2(canvas_p0.x + canvas_sz.x, canvas_p0.y + canvas_sz.y);
+
+ // Draw border and background color
+ ImGuiIO& io = ImGui::GetIO();
+ ImDrawList* draw_list = ImGui::GetWindowDrawList();
+ draw_list->AddRectFilled(canvas_p0, canvas_p1, IM_COL32(50, 50, 50, 255));
+ draw_list->AddRect(canvas_p0, canvas_p1, IM_COL32(255, 255, 255, 255));
+
+ // This will catch our interactions
+ ImGui::InvisibleButton("canvas", canvas_sz, ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonRight);
+ const bool is_hovered = ImGui::IsItemHovered(); // Hovered
+ const bool is_active = ImGui::IsItemActive(); // Held
+ const ImVec2 origin(canvas_p0.x + scrolling.x, canvas_p0.y + scrolling.y); // Lock scrolled origin
+ const ImVec2 mouse_pos_in_canvas(io.MousePos.x - origin.x, io.MousePos.y - origin.y);
+
+ // Add first and second point
+ if (is_hovered && !adding_line && ImGui::IsMouseClicked(ImGuiMouseButton_Left))
+ {
+ points.push_back(mouse_pos_in_canvas);
+ points.push_back(mouse_pos_in_canvas);
+ adding_line = true;
+ }
if (adding_line)
{
- adding_preview = true;
- points.push_back(mouse_pos_in_canvas);
- if (!ImGui::IsMouseDown(0))
- adding_line = adding_preview = false;
+ points.back() = mouse_pos_in_canvas;
+ if (!ImGui::IsMouseDown(ImGuiMouseButton_Left))
+ adding_line = false;
}
- if (ImGui::IsItemHovered())
+
+ // Pan (we use a zero mouse threshold when there's no context menu)
+ // You may decide to make that threshold dynamic based on whether the mouse is hovering something etc.
+ const float mouse_threshold_for_pan = opt_enable_context_menu ? -1.0f : 0.0f;
+ if (is_active && ImGui::IsMouseDragging(ImGuiMouseButton_Right, mouse_threshold_for_pan))
{
- if (!adding_line && ImGui::IsMouseClicked(0))
- {
- points.push_back(mouse_pos_in_canvas);
- adding_line = true;
- }
- if (ImGui::IsMouseClicked(1) && !points.empty())
- {
- adding_line = adding_preview = false;
- points.pop_back();
- points.pop_back();
- }
+ scrolling.x += io.MouseDelta.x;
+ scrolling.y += io.MouseDelta.y;
}
- draw_list->PushClipRect(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), true); // clip lines within the canvas (if we resize it, etc.)
- for (int i = 0; i < points.Size - 1; i += 2)
- draw_list->AddLine(ImVec2(canvas_pos.x + points[i].x, canvas_pos.y + points[i].y), ImVec2(canvas_pos.x + points[i + 1].x, canvas_pos.y + points[i + 1].y), IM_COL32(255, 255, 0, 255), 2.0f);
+
+ // Context menu (under default mouse threshold)
+ ImVec2 drag_delta = ImGui::GetMouseDragDelta(ImGuiMouseButton_Right);
+ if (opt_enable_context_menu && ImGui::IsMouseReleased(ImGuiMouseButton_Right) && drag_delta.x == 0.0f && drag_delta.y == 0.0f)
+ ImGui::OpenPopupOnItemClick("context");
+ if (ImGui::BeginPopup("context"))
+ {
+ if (adding_line)
+ points.resize(points.size() - 2);
+ adding_line = false;
+ if (ImGui::MenuItem("Remove one", NULL, false, points.Size > 0)) { points.resize(points.size() - 2); }
+ if (ImGui::MenuItem("Remove all", NULL, false, points.Size > 0)) { points.clear(); }
+ ImGui::EndPopup();
+ }
+
+ // Draw grid + all lines in the canvas
+ draw_list->PushClipRect(canvas_p0, canvas_p1, true);
+ if (opt_enable_grid)
+ {
+ const float GRID_STEP = 64.0f;
+ for (float x = fmodf(scrolling.x, GRID_STEP); x < canvas_sz.x; x += GRID_STEP)
+ draw_list->AddLine(ImVec2(canvas_p0.x + x, canvas_p0.y), ImVec2(canvas_p0.x + x, canvas_p1.y), IM_COL32(200, 200, 200, 40));
+ for (float y = fmodf(scrolling.y, GRID_STEP); y < canvas_sz.y; y += GRID_STEP)
+ draw_list->AddLine(ImVec2(canvas_p0.x, canvas_p0.y + y), ImVec2(canvas_p1.x, canvas_p0.y + y), IM_COL32(200, 200, 200, 40));
+ }
+ for (int n = 0; n < points.Size; n += 2)
+ draw_list->AddLine(ImVec2(origin.x + points[n].x, origin.y + points[n].y), ImVec2(origin.x + points[n + 1].x, origin.y + points[n + 1].y), IM_COL32(255, 255, 0, 255), 2.0f);
draw_list->PopClipRect();
- if (adding_preview)
- points.pop_back();
+
ImGui::EndTabItem();
}
@@ -4603,9 +7234,9 @@ static void ShowExampleAppCustomRendering(bool* p_open)
ImVec2 window_size = ImGui::GetWindowSize();
ImVec2 window_center = ImVec2(window_pos.x + window_size.x * 0.5f, window_pos.y + window_size.y * 0.5f);
if (draw_bg)
- ImGui::GetBackgroundDrawList()->AddCircle(window_center, window_size.x * 0.6f, IM_COL32(255, 0, 0, 200), 48, 10+4);
+ ImGui::GetBackgroundDrawList()->AddCircle(window_center, window_size.x * 0.6f, IM_COL32(255, 0, 0, 200), 0, 10 + 4);
if (draw_fg)
- ImGui::GetForegroundDrawList()->AddCircle(window_center, window_size.y * 0.6f, IM_COL32(0, 255, 0, 200), 48, 10);
+ ImGui::GetForegroundDrawList()->AddCircle(window_center, window_size.y * 0.6f, IM_COL32(0, 255, 0, 200), 0, 10);
ImGui::EndTabItem();
}
@@ -4615,99 +7246,6 @@ static void ShowExampleAppCustomRendering(bool* p_open)
ImGui::End();
}
-//-----------------------------------------------------------------------------
-// [SECTION] Example App: Docking, DockSpace / ShowExampleAppDockSpace()
-//-----------------------------------------------------------------------------
-
-// Demonstrate using DockSpace() to create an explicit docking node within an existing window.
-// Note that you already dock windows into each others _without_ a DockSpace() by just moving windows
-// from their title bar (or by holding SHIFT if io.ConfigDockingWithShift is set).
-// DockSpace() is only useful to construct to a central location for your application.
-void ShowExampleAppDockSpace(bool* p_open)
-{
- static bool opt_fullscreen_persistant = true;
- bool opt_fullscreen = opt_fullscreen_persistant;
- static ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_None;
-
- // We are using the ImGuiWindowFlags_NoDocking flag to make the parent window not dockable into,
- // because it would be confusing to have two docking targets within each others.
- ImGuiWindowFlags window_flags = ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking;
- if (opt_fullscreen)
- {
- ImGuiViewport* viewport = ImGui::GetMainViewport();
- ImGui::SetNextWindowPos(viewport->Pos);
- ImGui::SetNextWindowSize(viewport->Size);
- ImGui::SetNextWindowViewport(viewport->ID);
- ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
- ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
- window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove;
- window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
- }
-
- // When using ImGuiDockNodeFlags_PassthruCentralNode, DockSpace() will render our background and handle the pass-thru hole, so we ask Begin() to not render a background.
- if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
- window_flags |= ImGuiWindowFlags_NoBackground;
-
- // Important: note that we proceed even if Begin() returns false (aka window is collapsed).
- // This is because we want to keep our DockSpace() active. If a DockSpace() is inactive,
- // all active windows docked into it will lose their parent and become undocked.
- // We cannot preserve the docking relationship between an active window and an inactive docking, otherwise
- // any change of dockspace/settings would lead to windows being stuck in limbo and never being visible.
- ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
- ImGui::Begin("DockSpace Demo", p_open, window_flags);
- ImGui::PopStyleVar();
-
- if (opt_fullscreen)
- ImGui::PopStyleVar(2);
-
- // DockSpace
- ImGuiIO& io = ImGui::GetIO();
- if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable)
- {
- ImGuiID dockspace_id = ImGui::GetID("MyDockSpace");
- ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags);
- }
- else
- {
- ShowDockingDisabledMessage();
- }
-
- if (ImGui::BeginMenuBar())
- {
- if (ImGui::BeginMenu("Docking"))
- {
- // Disabling fullscreen would allow the window to be moved to the front of other windows,
- // which we can't undo at the moment without finer window depth/z control.
- //ImGui::MenuItem("Fullscreen", NULL, &opt_fullscreen_persistant);
-
- if (ImGui::MenuItem("Flag: NoSplit", "", (dockspace_flags & ImGuiDockNodeFlags_NoSplit) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_NoSplit;
- if (ImGui::MenuItem("Flag: NoResize", "", (dockspace_flags & ImGuiDockNodeFlags_NoResize) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_NoResize;
- if (ImGui::MenuItem("Flag: NoDockingInCentralNode", "", (dockspace_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_NoDockingInCentralNode;
- if (ImGui::MenuItem("Flag: PassthruCentralNode", "", (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_PassthruCentralNode;
- if (ImGui::MenuItem("Flag: AutoHideTabBar", "", (dockspace_flags & ImGuiDockNodeFlags_AutoHideTabBar) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_AutoHideTabBar;
- ImGui::Separator();
- if (ImGui::MenuItem("Close DockSpace", NULL, false, p_open != NULL))
- *p_open = false;
- ImGui::EndMenu();
- }
- HelpMarker(
- "When docking is enabled, you can ALWAYS dock MOST window into another! Try it now!" "\n\n"
- " > if io.ConfigDockingWithShift==false (default):" "\n"
- " drag windows from title bar to dock" "\n"
- " > if io.ConfigDockingWithShift==true:" "\n"
- " drag windows from anywhere and hold Shift to dock" "\n\n"
- "This demo app has nothing to do with it!" "\n\n"
- "This demo app only demonstrate the use of ImGui::DockSpace() which allows you to manually create a docking node _within_ another window. This is useful so you can decorate your main application window (e.g. with a menu bar)." "\n\n"
- "ImGui::DockSpace() comes with one hard constraint: it needs to be submitted _before_ any window which may be docked into it. Therefore, if you use a dock spot as the central point of your application, you'll probably want it to be part of the very first window you are submitting to imgui every frame." "\n\n"
- "(NB: because of this constraint, the implicit \"Debug\" window can not be docked into an explicit DockSpace() node, because that window is submitted as part of the NewFrame() call. An easy workaround is that you can create your own implicit \"Debug##2\" window after calling DockSpace() and leave it in the window stack for anyone to use.)"
- );
-
- ImGui::EndMenuBar();
- }
-
- ImGui::End();
-}
-
//-----------------------------------------------------------------------------
// [SECTION] Example App: Documents Handling / ShowExampleAppDocuments()
//-----------------------------------------------------------------------------
@@ -4715,14 +7253,14 @@ void ShowExampleAppDockSpace(bool* p_open)
// Simplified structure to mimic a Document model
struct MyDocument
{
- const char* Name; // Document title
- bool Open; // Set when the document is open (in this demo, we keep an array of all available documents to simplify the demo)
- bool OpenPrev; // Copy of Open from last update.
- bool Dirty; // Set when the document has been modified
- bool WantClose; // Set when the document
- ImVec4 Color; // An arbitrary variable associated to the document
+ const char* Name; // Document title
+ bool Open; // Set when open (we keep an array of all available documents to simplify demo code!)
+ bool OpenPrev; // Copy of Open from last update.
+ bool Dirty; // Set when the document has been modified
+ bool WantClose; // Set when the document
+ ImVec4 Color; // An arbitrary variable associated to the document
- MyDocument(const char* name, bool open = true, const ImVec4& color = ImVec4(1.0f,1.0f,1.0f,1.0f))
+ MyDocument(const char* name, bool open = true, const ImVec4& color = ImVec4(1.0f, 1.0f, 1.0f, 1.0f))
{
Name = name;
Open = OpenPrev = open;
@@ -4735,7 +7273,7 @@ struct MyDocument
void DoForceClose() { Open = false; Dirty = false; }
void DoSave() { Dirty = false; }
- // Display dummy contents for the Document
+ // Display placeholder contents for the Document
static void DisplayContents(MyDocument* doc)
{
ImGui::PushID(doc);
@@ -4784,10 +7322,11 @@ struct ExampleAppDocuments
};
// [Optional] Notify the system of Tabs/Windows closure that happened outside the regular tab interface.
-// If a tab has been closed programmatically (aka closed from another source such as the Checkbox() in the demo, as opposed
-// to clicking on the regular tab closing button) and stops being submitted, it will take a frame for the tab bar to notice its absence.
-// During this frame there will be a gap in the tab bar, and if the tab that has disappeared was the selected one, the tab bar
-// will report no selected tab during the frame. This will effectively give the impression of a flicker for one frame.
+// If a tab has been closed programmatically (aka closed from another source such as the Checkbox() in the demo,
+// as opposed to clicking on the regular tab closing button) and stops being submitted, it will take a frame for
+// the tab bar to notice its absence. During this frame there will be a gap in the tab bar, and if the tab that has
+// disappeared was the selected one, the tab bar will report no selected tab during the frame. This will effectively
+// give the impression of a flicker for one frame.
// We call SetTabItemClosed() to manually notify the Tab Bar or Docking system of removed tabs to avoid this glitch.
// Note that this completely optional, and only affect tab bars with the ImGuiTabBarFlags_Reorderable flag.
static void NotifyOfDocumentsClosedElsewhere(ExampleAppDocuments& app)
@@ -4806,25 +7345,11 @@ void ShowExampleAppDocuments(bool* p_open)
static ExampleAppDocuments app;
// Options
- enum Target
- {
- Target_None,
- Target_Tab, // Create documents as local tab into a local tab bar
- Target_DockSpaceAndWindow // Create documents as regular windows, and create an embedded dockspace
- };
- static Target opt_target = Target_Tab;
- static bool opt_reorderable = true;
+ static bool opt_reorderable = true;
static ImGuiTabBarFlags opt_fitting_flags = ImGuiTabBarFlags_FittingPolicyDefault_;
- // When (opt_target == Target_DockSpaceAndWindow) there is the possibily that one of our child Document window (e.g. "Eggplant")
- // that we emit gets docked into the same spot as the parent window ("Example: Documents").
- // This would create a problematic feedback loop because selecting the "Eggplant" tab would make the "Example: Documents" tab
- // not visible, which in turn would stop submitting the "Eggplant" window.
- // We avoid this problem by submitting our documents window even if our parent window is not currently visible.
- // Another solution may be to make the "Example: Documents" window use the ImGuiWindowFlags_NoDocking.
-
bool window_contents_visible = ImGui::Begin("Example: Documents", p_open, ImGuiWindowFlags_MenuBar);
- if (!window_contents_visible && opt_target != Target_DockSpaceAndWindow)
+ if (!window_contents_visible)
{
ImGui::End();
return;
@@ -4871,17 +7396,10 @@ void ShowExampleAppDocuments(bool* p_open)
doc->DoForceClose();
ImGui::PopID();
}
- ImGui::PushItemWidth(ImGui::GetFontSize() * 12);
- ImGui::Combo("Output", (int*)&opt_target, "None\0TabBar+Tabs\0DockSpace+Window\0");
- ImGui::PopItemWidth();
- bool redock_all = false;
- if (opt_target == Target_Tab) { ImGui::SameLine(); ImGui::Checkbox("Reorderable Tabs", &opt_reorderable); }
- if (opt_target == Target_DockSpaceAndWindow) { ImGui::SameLine(); redock_all = ImGui::Button("Redock all"); }
ImGui::Separator();
- // Tabs
- if (opt_target == Target_Tab)
+ // Submit Tab Bar and Tabs
{
ImGuiTabBarFlags tab_bar_flags = (opt_fitting_flags) | (opt_reorderable ? ImGuiTabBarFlags_Reorderable : 0);
if (ImGui::BeginTabBar("##tabs", tab_bar_flags))
@@ -4921,53 +7439,6 @@ void ShowExampleAppDocuments(bool* p_open)
ImGui::EndTabBar();
}
}
- else if (opt_target == Target_DockSpaceAndWindow)
- {
- if (ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_DockingEnable)
- {
- NotifyOfDocumentsClosedElsewhere(app);
-
- // Create a DockSpace node where any window can be docked
- ImGuiID dockspace_id = ImGui::GetID("MyDockSpace");
- ImGui::DockSpace(dockspace_id);
-
- // Create Windows
- for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++)
- {
- MyDocument* doc = &app.Documents[doc_n];
- if (!doc->Open)
- continue;
-
- ImGui::SetNextWindowDockID(dockspace_id, redock_all ? ImGuiCond_Always : ImGuiCond_FirstUseEver);
- ImGuiWindowFlags window_flags = (doc->Dirty ? ImGuiWindowFlags_UnsavedDocument : 0);
- bool visible = ImGui::Begin(doc->Name, &doc->Open, window_flags);
-
- // Cancel attempt to close when unsaved add to save queue so we can display a popup.
- if (!doc->Open && doc->Dirty)
- {
- doc->Open = true;
- doc->DoQueueClose();
- }
-
- MyDocument::DisplayContextMenu(doc);
- if (visible)
- MyDocument::DisplayContents(doc);
-
- ImGui::End();
- }
- }
- else
- {
- ShowDockingDisabledMessage();
- }
- }
-
- // Early out other contents
- if (!window_contents_visible)
- {
- ImGui::End();
- return;
- }
// Update closing queue
static ImVector close_queue;
@@ -5058,3 +7529,5 @@ void ImGui::ShowUserGuide() {}
void ImGui::ShowStyleEditor(ImGuiStyle*) {}
#endif
+
+#endif // #ifndef IMGUI_DISABLE
diff --git a/dep/imgui/src/imgui_draw.cpp b/dep/imgui/src/imgui_draw.cpp
index ec27dacdf..ad106c3c0 100644
--- a/dep/imgui/src/imgui_draw.cpp
+++ b/dep/imgui/src/imgui_draw.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.74 WIP
+// dear imgui, v1.81 WIP
// (drawing and font code)
/*
@@ -16,7 +16,7 @@ Index of this file:
// [SECTION] ImFontAtlas glyph ranges helpers
// [SECTION] ImFontGlyphRangesBuilder
// [SECTION] ImFont
-// [SECTION] Internal Render Helpers
+// [SECTION] ImGui Internal Render Helpers
// [SECTION] Decompression code
// [SECTION] Default font data (ProggyClean.ttf)
@@ -27,14 +27,20 @@ Index of this file:
#endif
#include "imgui.h"
+#ifndef IMGUI_DISABLE
+
#ifndef IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_MATH_OPERATORS
#endif
+
#include "imgui_internal.h"
+#ifdef IMGUI_ENABLE_FREETYPE
+#include "misc/freetype/imgui_freetype.h"
+#endif
#include // vsnprintf, sscanf, printf
#if !defined(alloca)
-#if defined(__GLIBC__) || defined(__sun) || defined(__CYGWIN__) || defined(__APPLE__) || defined(__SWITCH__)
+#if defined(__GLIBC__) || defined(__sun) || defined(__APPLE__) || defined(__NEWLIB__)
#include // alloca (glibc uses . Note that Cygwin may have _WIN32 defined, so the order matters here)
#elif defined(_WIN32)
#include // alloca
@@ -55,22 +61,22 @@ Index of this file:
// Clang/GCC warnings with -Weverything
#if defined(__clang__)
-#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse.
-#pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants ok.
-#pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference is.
-#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness //
-#if __has_warning("-Wzero-as-null-pointer-constant")
-#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning : zero as null pointer constant // some standard header variations use #define NULL 0
+#if __has_warning("-Wunknown-warning-option")
+#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
#endif
-#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
-#if __has_warning("-Wdouble-promotion")
-#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
+#if __has_warning("-Walloca")
+#pragma clang diagnostic ignored "-Walloca" // warning: use of function '__builtin_alloca' is discouraged
#endif
+#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
+#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
+#pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants ok.
+#pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is.
+#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
+#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
+#pragma clang diagnostic ignored "-Wcomma" // warning: possible misuse of comma operator here
+#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning: macro name is a reserved identifier
+#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
+#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
#elif defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
@@ -106,7 +112,7 @@ 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 //
+#pragma clang diagnostic ignored "-Wcast-qual" // warning: cast from 'const xxxx *' to 'xxx *' drops const qualifier
#endif
#if defined(__GNUC__)
@@ -116,9 +122,9 @@ namespace IMGUI_STB_NAMESPACE
#endif
#ifndef STB_RECT_PACK_IMPLEMENTATION // in case the user already have an implementation in the _same_ compilation unit (e.g. unity builds)
-#ifndef IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION
+#ifndef IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION // in case the user already have an implementation in another compilation unit
#define STBRP_STATIC
-#define STBRP_ASSERT(x) IM_ASSERT(x)
+#define STBRP_ASSERT(x) do { IM_ASSERT(x); } while (0)
#define STBRP_SORT ImQsort
#define STB_RECT_PACK_IMPLEMENTATION
#endif
@@ -129,11 +135,12 @@ namespace IMGUI_STB_NAMESPACE
#endif
#endif
+#ifdef IMGUI_ENABLE_STB_TRUETYPE
#ifndef STB_TRUETYPE_IMPLEMENTATION // in case the user already have an implementation in the _same_ compilation unit (e.g. unity builds)
-#ifndef IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION
+#ifndef IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION // in case the user already have an implementation in another compilation unit
#define STBTT_malloc(x,u) ((void)(u), IM_ALLOC(x))
#define STBTT_free(x,u) ((void)(u), IM_FREE(x))
-#define STBTT_assert(x) IM_ASSERT(x)
+#define STBTT_assert(x) do { IM_ASSERT(x); } while(0)
#define STBTT_fmod(x,y) ImFmod(x,y)
#define STBTT_sqrt(x) ImSqrt(x)
#define STBTT_pow(x,y) ImPow(x,y)
@@ -151,6 +158,7 @@ namespace IMGUI_STB_NAMESPACE
#include "imstb_truetype.h"
#endif
#endif
+#endif // IMGUI_ENABLE_STB_TRUETYPE
#if defined(__GNUC__)
#pragma GCC diagnostic pop
@@ -208,7 +216,7 @@ void ImGui::StyleColorsDark(ImGuiStyle* dst)
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_ResizeGrip] = ImVec4(0.26f, 0.59f, 0.98f, 0.20f);
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_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.80f);
@@ -216,12 +224,15 @@ void ImGui::StyleColorsDark(ImGuiStyle* dst)
colors[ImGuiCol_TabActive] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f);
colors[ImGuiCol_TabUnfocused] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f);
colors[ImGuiCol_TabUnfocusedActive] = ImLerp(colors[ImGuiCol_TabActive], colors[ImGuiCol_TitleBg], 0.40f);
- colors[ImGuiCol_DockingPreview] = colors[ImGuiCol_HeaderActive] * ImVec4(1.0f, 1.0f, 1.0f, 0.7f);
- colors[ImGuiCol_DockingEmptyBg] = ImVec4(0.20f, 0.20f, 0.20f, 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_TableHeaderBg] = ImVec4(0.19f, 0.19f, 0.20f, 1.00f);
+ colors[ImGuiCol_TableBorderStrong] = ImVec4(0.31f, 0.31f, 0.35f, 1.00f); // Prefer using Alpha=1.0 here
+ colors[ImGuiCol_TableBorderLight] = ImVec4(0.23f, 0.23f, 0.25f, 1.00f); // Prefer using Alpha=1.0 here
+ colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
+ colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.06f);
colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 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);
@@ -237,7 +248,7 @@ void ImGui::StyleColorsClassic(ImGuiStyle* dst)
colors[ImGuiCol_Text] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);
colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f);
- colors[ImGuiCol_WindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.70f);
+ colors[ImGuiCol_WindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.85f);
colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
colors[ImGuiCol_PopupBg] = ImVec4(0.11f, 0.11f, 0.14f, 0.92f);
colors[ImGuiCol_Border] = ImVec4(0.50f, 0.50f, 0.50f, 0.50f);
@@ -265,7 +276,7 @@ void ImGui::StyleColorsClassic(ImGuiStyle* dst)
colors[ImGuiCol_Separator] = ImVec4(0.50f, 0.50f, 0.50f, 0.60f);
colors[ImGuiCol_SeparatorHovered] = ImVec4(0.60f, 0.60f, 0.70f, 1.00f);
colors[ImGuiCol_SeparatorActive] = ImVec4(0.70f, 0.70f, 0.90f, 1.00f);
- colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.16f);
+ colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.10f);
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_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.80f);
@@ -273,12 +284,15 @@ void ImGui::StyleColorsClassic(ImGuiStyle* dst)
colors[ImGuiCol_TabActive] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f);
colors[ImGuiCol_TabUnfocused] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f);
colors[ImGuiCol_TabUnfocusedActive] = ImLerp(colors[ImGuiCol_TabActive], colors[ImGuiCol_TitleBg], 0.40f);
- colors[ImGuiCol_DockingPreview] = colors[ImGuiCol_Header] * ImVec4(1.0f, 1.0f, 1.0f, 0.7f);
- colors[ImGuiCol_DockingEmptyBg] = ImVec4(0.20f, 0.20f, 0.20f, 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);
colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f);
+ colors[ImGuiCol_TableHeaderBg] = ImVec4(0.27f, 0.27f, 0.38f, 1.00f);
+ colors[ImGuiCol_TableBorderStrong] = ImVec4(0.31f, 0.31f, 0.45f, 1.00f); // Prefer using Alpha=1.0 here
+ colors[ImGuiCol_TableBorderLight] = ImVec4(0.26f, 0.26f, 0.28f, 1.00f); // Prefer using Alpha=1.0 here
+ colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
+ colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.07f);
colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f);
colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f);
colors[ImGuiCol_NavHighlight] = colors[ImGuiCol_HeaderHovered];
@@ -323,7 +337,7 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst)
colors[ImGuiCol_Separator] = ImVec4(0.39f, 0.39f, 0.39f, 0.62f);
colors[ImGuiCol_SeparatorHovered] = ImVec4(0.14f, 0.44f, 0.80f, 0.78f);
colors[ImGuiCol_SeparatorActive] = ImVec4(0.14f, 0.44f, 0.80f, 1.00f);
- colors[ImGuiCol_ResizeGrip] = ImVec4(0.80f, 0.80f, 0.80f, 0.56f);
+ colors[ImGuiCol_ResizeGrip] = ImVec4(0.35f, 0.35f, 0.35f, 0.17f);
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_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.90f);
@@ -331,12 +345,15 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst)
colors[ImGuiCol_TabActive] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f);
colors[ImGuiCol_TabUnfocused] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f);
colors[ImGuiCol_TabUnfocusedActive] = ImLerp(colors[ImGuiCol_TabActive], colors[ImGuiCol_TitleBg], 0.40f);
- colors[ImGuiCol_DockingPreview] = colors[ImGuiCol_Header] * ImVec4(1.0f, 1.0f, 1.0f, 0.7f);
- colors[ImGuiCol_DockingEmptyBg] = ImVec4(0.20f, 0.20f, 0.20f, 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);
colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.45f, 0.00f, 1.00f);
+ colors[ImGuiCol_TableHeaderBg] = ImVec4(0.78f, 0.87f, 0.98f, 1.00f);
+ colors[ImGuiCol_TableBorderStrong] = ImVec4(0.57f, 0.57f, 0.64f, 1.00f); // Prefer using Alpha=1.0 here
+ colors[ImGuiCol_TableBorderLight] = ImVec4(0.68f, 0.68f, 0.74f, 1.00f); // Prefer using Alpha=1.0 here
+ colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
+ colors[ImGuiCol_TableRowBgAlt] = ImVec4(0.30f, 0.30f, 0.30f, 0.09f);
colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f);
colors[ImGuiCol_DragDropTarget] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f);
colors[ImGuiCol_NavHighlight] = colors[ImGuiCol_HeaderHovered];
@@ -346,32 +363,46 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst)
}
//-----------------------------------------------------------------------------
-// ImDrawList
+// [SECTION] ImDrawList
//-----------------------------------------------------------------------------
ImDrawListSharedData::ImDrawListSharedData()
{
- Font = NULL;
- FontSize = 0.0f;
- CurveTessellationTol = 0.0f;
- ClipRectFullscreen = ImVec4(-8192.0f, -8192.0f, +8192.0f, +8192.0f);
- InitialFlags = ImDrawListFlags_None;
-
- // Const data
- for (int i = 0; i < IM_ARRAYSIZE(CircleVtx12); i++)
+ memset(this, 0, sizeof(*this));
+ for (int i = 0; i < IM_ARRAYSIZE(ArcFastVtx); i++)
{
- const float a = ((float)i * 2 * IM_PI) / (float)IM_ARRAYSIZE(CircleVtx12);
- CircleVtx12[i] = ImVec2(ImCos(a), ImSin(a));
+ const float a = ((float)i * 2 * IM_PI) / (float)IM_ARRAYSIZE(ArcFastVtx);
+ ArcFastVtx[i] = ImVec2(ImCos(a), ImSin(a));
}
}
-void ImDrawList::Clear()
+void ImDrawListSharedData::SetCircleSegmentMaxError(float max_error)
{
+ if (CircleSegmentMaxError == max_error)
+ return;
+ CircleSegmentMaxError = max_error;
+ for (int i = 0; i < IM_ARRAYSIZE(CircleSegmentCounts); i++)
+ {
+ const float radius = (float)i;
+ const int segment_count = IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(radius, CircleSegmentMaxError);
+ CircleSegmentCounts[i] = (ImU8)ImMin(segment_count, 255);
+ }
+}
+
+// Initialize before use in a new frame. We always have a command ready in the buffer.
+void ImDrawList::_ResetForNewFrame()
+{
+ // Verify that the ImDrawCmd fields we want to memcmp() are contiguous in memory.
+ // (those should be IM_STATIC_ASSERT() in theory but with our pre C++11 setup the whole check doesn't compile with GCC)
+ IM_ASSERT(IM_OFFSETOF(ImDrawCmd, ClipRect) == 0);
+ IM_ASSERT(IM_OFFSETOF(ImDrawCmd, TextureId) == sizeof(ImVec4));
+ IM_ASSERT(IM_OFFSETOF(ImDrawCmd, VtxOffset) == sizeof(ImVec4) + sizeof(ImTextureID));
+
CmdBuffer.resize(0);
IdxBuffer.resize(0);
VtxBuffer.resize(0);
- Flags = _Data ? _Data->InitialFlags : ImDrawListFlags_None;
- _VtxCurrentOffset = 0;
+ Flags = _Data->InitialFlags;
+ memset(&_CmdHeader, 0, sizeof(_CmdHeader));
_VtxCurrentIdx = 0;
_VtxWritePtr = NULL;
_IdxWritePtr = NULL;
@@ -379,13 +410,16 @@ void ImDrawList::Clear()
_TextureIdStack.resize(0);
_Path.resize(0);
_Splitter.Clear();
+ CmdBuffer.push_back(ImDrawCmd());
+ _FringeScale = 1.0f;
}
-void ImDrawList::ClearFreeMemory()
+void ImDrawList::_ClearFreeMemory()
{
CmdBuffer.clear();
IdxBuffer.clear();
VtxBuffer.clear();
+ Flags = ImDrawListFlags_None;
_VtxCurrentIdx = 0;
_VtxWritePtr = NULL;
_IdxWritePtr = NULL;
@@ -405,86 +439,117 @@ ImDrawList* ImDrawList::CloneOutput() const
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] : (ImTextureID)NULL)
-
void ImDrawList::AddDrawCmd()
{
ImDrawCmd draw_cmd;
- draw_cmd.ClipRect = GetCurrentClipRect();
- draw_cmd.TextureId = GetCurrentTextureId();
- draw_cmd.VtxOffset = _VtxCurrentOffset;
+ draw_cmd.ClipRect = _CmdHeader.ClipRect; // Same as calling ImDrawCmd_HeaderCopy()
+ draw_cmd.TextureId = _CmdHeader.TextureId;
+ draw_cmd.VtxOffset = _CmdHeader.VtxOffset;
draw_cmd.IdxOffset = IdxBuffer.Size;
IM_ASSERT(draw_cmd.ClipRect.x <= draw_cmd.ClipRect.z && draw_cmd.ClipRect.y <= draw_cmd.ClipRect.w);
CmdBuffer.push_back(draw_cmd);
}
+// Pop trailing draw command (used before merging or presenting to user)
+// Note that this leaves the ImDrawList in a state unfit for further commands, as most code assume that CmdBuffer.Size > 0 && CmdBuffer.back().UserCallback == NULL
+void ImDrawList::_PopUnusedDrawCmd()
+{
+ if (CmdBuffer.Size == 0)
+ return;
+ ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];
+ if (curr_cmd->ElemCount == 0 && curr_cmd->UserCallback == NULL)
+ CmdBuffer.pop_back();
+}
+
void ImDrawList::AddCallback(ImDrawCallback callback, void* callback_data)
{
- ImDrawCmd* current_cmd = CmdBuffer.Size ? &CmdBuffer.back() : NULL;
- if (!current_cmd || current_cmd->ElemCount != 0 || current_cmd->UserCallback != NULL)
+ ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];
+ IM_ASSERT(curr_cmd->UserCallback == NULL);
+ if (curr_cmd->ElemCount != 0)
{
AddDrawCmd();
- current_cmd = &CmdBuffer.back();
+ curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];
}
- current_cmd->UserCallback = callback;
- current_cmd->UserCallbackData = callback_data;
+ curr_cmd->UserCallback = callback;
+ curr_cmd->UserCallbackData = callback_data;
AddDrawCmd(); // Force a new command after us (see comment below)
}
+// Compare ClipRect, TextureId and VtxOffset with a single memcmp()
+#define ImDrawCmd_HeaderSize (IM_OFFSETOF(ImDrawCmd, VtxOffset) + sizeof(unsigned int))
+#define ImDrawCmd_HeaderCompare(CMD_LHS, CMD_RHS) (memcmp(CMD_LHS, CMD_RHS, ImDrawCmd_HeaderSize)) // Compare ClipRect, TextureId, VtxOffset
+#define ImDrawCmd_HeaderCopy(CMD_DST, CMD_SRC) (memcpy(CMD_DST, CMD_SRC, ImDrawCmd_HeaderSize)) // Copy ClipRect, TextureId, VtxOffset
+
// Our scheme may appears a bit unusual, basically we want the most-common calls AddLine AddRect etc. to not have to perform any check so we always have a command ready in the stack.
// The cost of figuring out if a new command has to be added or if we can merge is paid in those Update** functions only.
-void ImDrawList::UpdateClipRect()
+void ImDrawList::_OnChangedClipRect()
{
// If current command is used with different settings we need to add a new command
- const ImVec4 curr_clip_rect = GetCurrentClipRect();
- ImDrawCmd* curr_cmd = CmdBuffer.Size > 0 ? &CmdBuffer.Data[CmdBuffer.Size-1] : NULL;
- if (!curr_cmd || (curr_cmd->ElemCount != 0 && memcmp(&curr_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) != 0) || curr_cmd->UserCallback != NULL)
+ ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];
+ if (curr_cmd->ElemCount != 0 && memcmp(&curr_cmd->ClipRect, &_CmdHeader.ClipRect, sizeof(ImVec4)) != 0)
{
AddDrawCmd();
return;
}
+ IM_ASSERT(curr_cmd->UserCallback == NULL);
// Try to merge with previous command if it matches, else use current command
- ImDrawCmd* prev_cmd = CmdBuffer.Size > 1 ? curr_cmd - 1 : NULL;
- if (curr_cmd->ElemCount == 0 && prev_cmd && memcmp(&prev_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) == 0 && prev_cmd->TextureId == GetCurrentTextureId() && prev_cmd->UserCallback == NULL)
+ ImDrawCmd* prev_cmd = curr_cmd - 1;
+ if (curr_cmd->ElemCount == 0 && CmdBuffer.Size > 1 && ImDrawCmd_HeaderCompare(&_CmdHeader, prev_cmd) == 0 && prev_cmd->UserCallback == NULL)
+ {
CmdBuffer.pop_back();
- else
- curr_cmd->ClipRect = curr_clip_rect;
+ return;
+ }
+
+ curr_cmd->ClipRect = _CmdHeader.ClipRect;
}
-void ImDrawList::UpdateTextureID()
+void ImDrawList::_OnChangedTextureID()
{
// If current command is used with different settings we need to add a new command
- const ImTextureID curr_texture_id = GetCurrentTextureId();
- ImDrawCmd* curr_cmd = CmdBuffer.Size ? &CmdBuffer.back() : NULL;
- if (!curr_cmd || (curr_cmd->ElemCount != 0 && curr_cmd->TextureId != curr_texture_id) || curr_cmd->UserCallback != NULL)
+ ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];
+ if (curr_cmd->ElemCount != 0 && curr_cmd->TextureId != _CmdHeader.TextureId)
{
AddDrawCmd();
return;
}
+ IM_ASSERT(curr_cmd->UserCallback == NULL);
// Try to merge with previous command if it matches, else use current command
- ImDrawCmd* prev_cmd = CmdBuffer.Size > 1 ? curr_cmd - 1 : NULL;
- if (curr_cmd->ElemCount == 0 && prev_cmd && prev_cmd->TextureId == curr_texture_id && memcmp(&prev_cmd->ClipRect, &GetCurrentClipRect(), sizeof(ImVec4)) == 0 && prev_cmd->UserCallback == NULL)
+ ImDrawCmd* prev_cmd = curr_cmd - 1;
+ if (curr_cmd->ElemCount == 0 && CmdBuffer.Size > 1 && ImDrawCmd_HeaderCompare(&_CmdHeader, prev_cmd) == 0 && prev_cmd->UserCallback == NULL)
+ {
CmdBuffer.pop_back();
- else
- curr_cmd->TextureId = curr_texture_id;
+ return;
+ }
+
+ curr_cmd->TextureId = _CmdHeader.TextureId;
}
-#undef GetCurrentClipRect
-#undef GetCurrentTextureId
+void ImDrawList::_OnChangedVtxOffset()
+{
+ // We don't need to compare curr_cmd->VtxOffset != _CmdHeader.VtxOffset because we know it'll be different at the time we call this.
+ _VtxCurrentIdx = 0;
+ ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];
+ //IM_ASSERT(curr_cmd->VtxOffset != _CmdHeader.VtxOffset); // See #3349
+ if (curr_cmd->ElemCount != 0)
+ {
+ AddDrawCmd();
+ return;
+ }
+ IM_ASSERT(curr_cmd->UserCallback == NULL);
+ curr_cmd->VtxOffset = _CmdHeader.VtxOffset;
+}
// 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)
void ImDrawList::PushClipRect(ImVec2 cr_min, ImVec2 cr_max, bool intersect_with_current_clip_rect)
{
ImVec4 cr(cr_min.x, cr_min.y, cr_max.x, cr_max.y);
- if (intersect_with_current_clip_rect && _ClipRectStack.Size)
+ if (intersect_with_current_clip_rect)
{
- ImVec4 current = _ClipRectStack.Data[_ClipRectStack.Size-1];
+ ImVec4 current = _CmdHeader.ClipRect;
if (cr.x < current.x) cr.x = current.x;
if (cr.y < current.y) cr.y = current.y;
if (cr.z > current.z) cr.z = current.z;
@@ -494,7 +559,8 @@ void ImDrawList::PushClipRect(ImVec2 cr_min, ImVec2 cr_max, bool intersect_with_
cr.w = ImMax(cr.y, cr.w);
_ClipRectStack.push_back(cr);
- UpdateClipRect();
+ _CmdHeader.ClipRect = cr;
+ _OnChangedClipRect();
}
void ImDrawList::PushClipRectFullScreen()
@@ -504,37 +570,43 @@ void ImDrawList::PushClipRectFullScreen()
void ImDrawList::PopClipRect()
{
- IM_ASSERT(_ClipRectStack.Size > 0);
_ClipRectStack.pop_back();
- UpdateClipRect();
+ _CmdHeader.ClipRect = (_ClipRectStack.Size == 0) ? _Data->ClipRectFullscreen : _ClipRectStack.Data[_ClipRectStack.Size - 1];
+ _OnChangedClipRect();
}
void ImDrawList::PushTextureID(ImTextureID texture_id)
{
_TextureIdStack.push_back(texture_id);
- UpdateTextureID();
+ _CmdHeader.TextureId = texture_id;
+ _OnChangedTextureID();
}
void ImDrawList::PopTextureID()
{
- IM_ASSERT(_TextureIdStack.Size > 0);
_TextureIdStack.pop_back();
- UpdateTextureID();
+ _CmdHeader.TextureId = (_TextureIdStack.Size == 0) ? (ImTextureID)NULL : _TextureIdStack.Data[_TextureIdStack.Size - 1];
+ _OnChangedTextureID();
}
-// NB: this can be called with negative count for removing primitives (as long as the result does not underflow)
+// Reserve space for a number of vertices and indices.
+// You must finish filling your reserved data before calling PrimReserve() again, as it may reallocate or
+// submit the intermediate results. PrimUnreserve() can be used to release unused allocations.
void ImDrawList::PrimReserve(int idx_count, int vtx_count)
{
// Large mesh support (when enabled)
+ IM_ASSERT_PARANOID(idx_count >= 0 && vtx_count >= 0);
if (sizeof(ImDrawIdx) == 2 && (_VtxCurrentIdx + vtx_count >= (1 << 16)) && (Flags & ImDrawListFlags_AllowVtxOffset))
{
- _VtxCurrentOffset = VtxBuffer.Size;
- _VtxCurrentIdx = 0;
- AddDrawCmd();
+ // FIXME: In theory we should be testing that vtx_count <64k here.
+ // In practice, RenderText() relies on reserving ahead for a worst case scenario so it is currently useful for us
+ // to not make that check until we rework the text functions to handle clipping and large horizontal lines better.
+ _CmdHeader.VtxOffset = VtxBuffer.Size;
+ _OnChangedVtxOffset();
}
- ImDrawCmd& draw_cmd = CmdBuffer.Data[CmdBuffer.Size-1];
- draw_cmd.ElemCount += idx_count;
+ ImDrawCmd* draw_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];
+ draw_cmd->ElemCount += idx_count;
int vtx_buffer_old_size = VtxBuffer.Size;
VtxBuffer.resize(vtx_buffer_old_size + vtx_count);
@@ -545,6 +617,17 @@ void ImDrawList::PrimReserve(int idx_count, int vtx_count)
_IdxWritePtr = IdxBuffer.Data + idx_buffer_old_size;
}
+// Release the a number of reserved vertices/indices from the end of the last reservation made with PrimReserve().
+void ImDrawList::PrimUnreserve(int idx_count, int vtx_count)
+{
+ IM_ASSERT_PARANOID(idx_count >= 0 && vtx_count >= 0);
+
+ ImDrawCmd* draw_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];
+ draw_cmd->ElemCount -= idx_count;
+ VtxBuffer.shrink(VtxBuffer.Size - vtx_count);
+ IdxBuffer.shrink(IdxBuffer.Size - idx_count);
+}
+
// Fully unrolled with inline call to keep our debug builds decently fast.
void ImDrawList::PrimRect(const ImVec2& a, const ImVec2& c, ImU32 col)
{
@@ -590,10 +673,10 @@ void ImDrawList::PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, c
_IdxWritePtr += 6;
}
-// On AddPolyline() and AddConvexPolyFilled() we intentionally avoid using ImVec2 and superflous function calls to optimize debug/non-inlined builds.
+// On AddPolyline() and AddConvexPolyFilled() we intentionally avoid using ImVec2 and superfluous function calls to optimize debug/non-inlined builds.
// Those macros expects l-values.
-#define IM_NORMALIZE2F_OVER_ZERO(VX,VY) { float d2 = VX*VX + VY*VY; if (d2 > 0.0f) { float inv_len = 1.0f / ImSqrt(d2); VX *= inv_len; VY *= inv_len; } }
-#define IM_FIXNORMAL2F(VX,VY) { float d2 = VX*VX + VY*VY; if (d2 < 0.5f) d2 = 0.5f; float inv_lensq = 1.0f / d2; VX *= inv_lensq; VY *= inv_lensq; }
+#define IM_NORMALIZE2F_OVER_ZERO(VX,VY) do { float d2 = VX*VX + VY*VY; if (d2 > 0.0f) { float inv_len = 1.0f / ImSqrt(d2); VX *= inv_len; VY *= inv_len; } } while (0)
+#define IM_FIXNORMAL2F(VX,VY) do { float d2 = VX*VX + VY*VY; if (d2 < 0.5f) d2 = 0.5f; float inv_lensq = 1.0f / d2; VX *= inv_lensq; VY *= inv_lensq; } while (0)
// TODO: Thickness anti-aliased lines cap are missing their AA fringe.
// We avoid using the ImVec2 math operators here to reduce cost to a minimum for debug/non-inlined builds.
@@ -602,30 +685,42 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32
if (points_count < 2)
return;
- const ImVec2 uv = _Data->TexUvWhitePixel;
+ const ImVec2 opaque_uv = _Data->TexUvWhitePixel;
+ const int count = closed ? points_count : points_count - 1; // The number of line segments we need to draw
+ const bool thick_line = (thickness > _FringeScale);
- int count = points_count;
- if (!closed)
- count = points_count-1;
-
- const bool thick_line = thickness > 1.0f;
if (Flags & ImDrawListFlags_AntiAliasedLines)
{
// Anti-aliased stroke
- const float AA_SIZE = 1.0f;
+ const float AA_SIZE = _FringeScale;
const ImU32 col_trans = col & ~IM_COL32_A_MASK;
- const int idx_count = thick_line ? count*18 : count*12;
- const int vtx_count = thick_line ? points_count*4 : points_count*3;
+ // Thicknesses <1.0 should behave like thickness 1.0
+ thickness = ImMax(thickness, 1.0f);
+ const int integer_thickness = (int)thickness;
+ const float fractional_thickness = thickness - integer_thickness;
+
+ // Do we want to draw this line using a texture?
+ // - For now, only draw integer-width lines using textures to avoid issues with the way scaling occurs, could be improved.
+ // - If AA_SIZE is not 1.0f we cannot use the texture path.
+ const bool use_texture = (Flags & ImDrawListFlags_AntiAliasedLinesUseTex) && (integer_thickness < IM_DRAWLIST_TEX_LINES_WIDTH_MAX) && (fractional_thickness <= 0.00001f) && (AA_SIZE == 1.0f);
+
+ // We should never hit this, because NewFrame() doesn't set ImDrawListFlags_AntiAliasedLinesUseTex unless ImFontAtlasFlags_NoBakedLines is off
+ IM_ASSERT_PARANOID(!use_texture || !(_Data->Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines));
+
+ const int idx_count = use_texture ? (count * 6) : (thick_line ? count * 18 : count * 12);
+ const int vtx_count = use_texture ? (points_count * 2) : (thick_line ? points_count * 4 : points_count * 3);
PrimReserve(idx_count, vtx_count);
// Temporary buffer
- ImVec2* temp_normals = (ImVec2*)alloca(points_count * (thick_line ? 5 : 3) * sizeof(ImVec2)); //-V630
+ // The first items are normals at each line point, then after that there are either 2 or 4 temp points for each line point
+ ImVec2* temp_normals = (ImVec2*)alloca(points_count * ((use_texture || !thick_line) ? 3 : 5) * sizeof(ImVec2)); //-V630
ImVec2* temp_points = temp_normals + points_count;
+ // Calculate normals (tangents) for each line segment
for (int i1 = 0; i1 < count; i1++)
{
- const int i2 = (i1+1) == points_count ? 0 : i1+1;
+ const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1;
float dx = points[i2].x - points[i1].x;
float dy = points[i2].y - points[i1].y;
IM_NORMALIZE2F_OVER_ZERO(dx, dy);
@@ -633,79 +728,134 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32
temp_normals[i1].y = -dx;
}
if (!closed)
- temp_normals[points_count-1] = temp_normals[points_count-2];
+ temp_normals[points_count - 1] = temp_normals[points_count - 2];
- if (!thick_line)
+ // If we are drawing a one-pixel-wide line without a texture, or a textured line of any width, we only need 2 or 3 vertices per point
+ if (use_texture || !thick_line)
{
+ // [PATH 1] Texture-based lines (thick or non-thick)
+ // [PATH 2] Non texture-based lines (non-thick)
+
+ // The width of the geometry we need to draw - this is essentially pixels for the line itself, plus "one pixel" for AA.
+ // - In the texture-based path, we don't use AA_SIZE here because the +1 is tied to the generated texture
+ // (see ImFontAtlasBuildRenderLinesTexData() function), and so alternate values won't work without changes to that code.
+ // - In the non texture-based paths, we would allow AA_SIZE to potentially be != 1.0f with a patch (e.g. fringe_scale patch to
+ // allow scaling geometry while preserving one-screen-pixel AA fringe).
+ const float half_draw_size = use_texture ? ((thickness * 0.5f) + 1) : AA_SIZE;
+
+ // If line is not closed, the first and last points need to be generated differently as there are no normals to blend
if (!closed)
{
- temp_points[0] = points[0] + temp_normals[0] * AA_SIZE;
- temp_points[1] = points[0] - temp_normals[0] * AA_SIZE;
- temp_points[(points_count-1)*2+0] = points[points_count-1] + temp_normals[points_count-1] * AA_SIZE;
- temp_points[(points_count-1)*2+1] = points[points_count-1] - temp_normals[points_count-1] * AA_SIZE;
+ temp_points[0] = points[0] + temp_normals[0] * half_draw_size;
+ temp_points[1] = points[0] - temp_normals[0] * half_draw_size;
+ temp_points[(points_count-1)*2+0] = points[points_count-1] + temp_normals[points_count-1] * half_draw_size;
+ temp_points[(points_count-1)*2+1] = points[points_count-1] - temp_normals[points_count-1] * half_draw_size;
}
+ // Generate the indices to form a number of triangles for each line segment, and the vertices for the line edges
+ // This takes points n and n+1 and writes into n+1, with the first point in a closed line being generated from the final one (as n+1 wraps)
// FIXME-OPT: Merge the different loops, possibly remove the temporary buffer.
- unsigned int idx1 = _VtxCurrentIdx;
- for (int i1 = 0; i1 < count; i1++)
+ unsigned int idx1 = _VtxCurrentIdx; // Vertex index for start of line segment
+ for (int i1 = 0; i1 < count; i1++) // i1 is the first point of the line segment
{
- const int i2 = (i1+1) == points_count ? 0 : i1+1;
- unsigned int idx2 = (i1+1) == points_count ? _VtxCurrentIdx : idx1+3;
+ const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; // i2 is the second point of the line segment
+ const unsigned int idx2 = ((i1 + 1) == points_count) ? _VtxCurrentIdx : (idx1 + (use_texture ? 2 : 3)); // Vertex index for end of segment
// Average normals
float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f;
float dm_y = (temp_normals[i1].y + temp_normals[i2].y) * 0.5f;
- IM_FIXNORMAL2F(dm_x, dm_y)
- dm_x *= AA_SIZE;
- dm_y *= AA_SIZE;
+ IM_FIXNORMAL2F(dm_x, dm_y);
+ dm_x *= half_draw_size; // dm_x, dm_y are offset to the outer edge of the AA area
+ dm_y *= half_draw_size;
- // Add temporary vertexes
- ImVec2* out_vtx = &temp_points[i2*2];
+ // Add temporary vertexes for the outer edges
+ ImVec2* out_vtx = &temp_points[i2 * 2];
out_vtx[0].x = points[i2].x + dm_x;
out_vtx[0].y = points[i2].y + dm_y;
out_vtx[1].x = points[i2].x - dm_x;
out_vtx[1].y = points[i2].y - dm_y;
- // Add indexes
- _IdxWritePtr[0] = (ImDrawIdx)(idx2+0); _IdxWritePtr[1] = (ImDrawIdx)(idx1+0); _IdxWritePtr[2] = (ImDrawIdx)(idx1+2);
- _IdxWritePtr[3] = (ImDrawIdx)(idx1+2); _IdxWritePtr[4] = (ImDrawIdx)(idx2+2); _IdxWritePtr[5] = (ImDrawIdx)(idx2+0);
- _IdxWritePtr[6] = (ImDrawIdx)(idx2+1); _IdxWritePtr[7] = (ImDrawIdx)(idx1+1); _IdxWritePtr[8] = (ImDrawIdx)(idx1+0);
- _IdxWritePtr[9] = (ImDrawIdx)(idx1+0); _IdxWritePtr[10]= (ImDrawIdx)(idx2+0); _IdxWritePtr[11]= (ImDrawIdx)(idx2+1);
- _IdxWritePtr += 12;
+ if (use_texture)
+ {
+ // Add indices for two triangles
+ _IdxWritePtr[0] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[1] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[2] = (ImDrawIdx)(idx1 + 1); // Right tri
+ _IdxWritePtr[3] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[4] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[5] = (ImDrawIdx)(idx2 + 0); // Left tri
+ _IdxWritePtr += 6;
+ }
+ else
+ {
+ // Add indexes for four triangles
+ _IdxWritePtr[0] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[1] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[2] = (ImDrawIdx)(idx1 + 2); // Right tri 1
+ _IdxWritePtr[3] = (ImDrawIdx)(idx1 + 2); _IdxWritePtr[4] = (ImDrawIdx)(idx2 + 2); _IdxWritePtr[5] = (ImDrawIdx)(idx2 + 0); // Right tri 2
+ _IdxWritePtr[6] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[7] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[8] = (ImDrawIdx)(idx1 + 0); // Left tri 1
+ _IdxWritePtr[9] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[10] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[11] = (ImDrawIdx)(idx2 + 1); // Left tri 2
+ _IdxWritePtr += 12;
+ }
idx1 = idx2;
}
- // Add vertexes
- for (int i = 0; i < points_count; i++)
+ // Add vertexes for each point on the line
+ if (use_texture)
{
- _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col;
- _VtxWritePtr[1].pos = temp_points[i*2+0]; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col_trans;
- _VtxWritePtr[2].pos = temp_points[i*2+1]; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col_trans;
- _VtxWritePtr += 3;
+ // If we're using textures we only need to emit the left/right edge vertices
+ ImVec4 tex_uvs = _Data->TexUvLines[integer_thickness];
+ /*if (fractional_thickness != 0.0f) // Currently always zero when use_texture==false!
+ {
+ const ImVec4 tex_uvs_1 = _Data->TexUvLines[integer_thickness + 1];
+ tex_uvs.x = tex_uvs.x + (tex_uvs_1.x - tex_uvs.x) * fractional_thickness; // inlined ImLerp()
+ tex_uvs.y = tex_uvs.y + (tex_uvs_1.y - tex_uvs.y) * fractional_thickness;
+ tex_uvs.z = tex_uvs.z + (tex_uvs_1.z - tex_uvs.z) * fractional_thickness;
+ tex_uvs.w = tex_uvs.w + (tex_uvs_1.w - tex_uvs.w) * fractional_thickness;
+ }*/
+ ImVec2 tex_uv0(tex_uvs.x, tex_uvs.y);
+ ImVec2 tex_uv1(tex_uvs.z, tex_uvs.w);
+ for (int i = 0; i < points_count; i++)
+ {
+ _VtxWritePtr[0].pos = temp_points[i * 2 + 0]; _VtxWritePtr[0].uv = tex_uv0; _VtxWritePtr[0].col = col; // Left-side outer edge
+ _VtxWritePtr[1].pos = temp_points[i * 2 + 1]; _VtxWritePtr[1].uv = tex_uv1; _VtxWritePtr[1].col = col; // Right-side outer edge
+ _VtxWritePtr += 2;
+ }
+ }
+ else
+ {
+ // If we're not using a texture, we need the center vertex as well
+ for (int i = 0; i < points_count; i++)
+ {
+ _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col; // Center of line
+ _VtxWritePtr[1].pos = temp_points[i * 2 + 0]; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col_trans; // Left-side outer edge
+ _VtxWritePtr[2].pos = temp_points[i * 2 + 1]; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col_trans; // Right-side outer edge
+ _VtxWritePtr += 3;
+ }
}
}
else
{
+ // [PATH 2] Non texture-based lines (thick): we need to draw the solid line core and thus require four vertices per point
const float half_inner_thickness = (thickness - AA_SIZE) * 0.5f;
+
+ // If line is not closed, the first and last points need to be generated differently as there are no normals to blend
if (!closed)
{
+ const int points_last = points_count - 1;
temp_points[0] = points[0] + temp_normals[0] * (half_inner_thickness + AA_SIZE);
temp_points[1] = points[0] + temp_normals[0] * (half_inner_thickness);
temp_points[2] = points[0] - temp_normals[0] * (half_inner_thickness);
temp_points[3] = points[0] - temp_normals[0] * (half_inner_thickness + AA_SIZE);
- temp_points[(points_count-1)*4+0] = points[points_count-1] + temp_normals[points_count-1] * (half_inner_thickness + AA_SIZE);
- temp_points[(points_count-1)*4+1] = points[points_count-1] + temp_normals[points_count-1] * (half_inner_thickness);
- temp_points[(points_count-1)*4+2] = points[points_count-1] - temp_normals[points_count-1] * (half_inner_thickness);
- temp_points[(points_count-1)*4+3] = points[points_count-1] - temp_normals[points_count-1] * (half_inner_thickness + AA_SIZE);
+ temp_points[points_last * 4 + 0] = points[points_last] + temp_normals[points_last] * (half_inner_thickness + AA_SIZE);
+ temp_points[points_last * 4 + 1] = points[points_last] + temp_normals[points_last] * (half_inner_thickness);
+ temp_points[points_last * 4 + 2] = points[points_last] - temp_normals[points_last] * (half_inner_thickness);
+ temp_points[points_last * 4 + 3] = points[points_last] - temp_normals[points_last] * (half_inner_thickness + AA_SIZE);
}
+ // Generate the indices to form a number of triangles for each line segment, and the vertices for the line edges
+ // This takes points n and n+1 and writes into n+1, with the first point in a closed line being generated from the final one (as n+1 wraps)
// FIXME-OPT: Merge the different loops, possibly remove the temporary buffer.
- unsigned int idx1 = _VtxCurrentIdx;
- for (int i1 = 0; i1 < count; i1++)
+ unsigned int idx1 = _VtxCurrentIdx; // Vertex index for start of line segment
+ for (int i1 = 0; i1 < count; i1++) // i1 is the first point of the line segment
{
- const int i2 = (i1+1) == points_count ? 0 : i1+1;
- unsigned int idx2 = (i1+1) == points_count ? _VtxCurrentIdx : idx1+4;
+ const int i2 = (i1 + 1) == points_count ? 0 : (i1 + 1); // i2 is the second point of the line segment
+ const unsigned int idx2 = (i1 + 1) == points_count ? _VtxCurrentIdx : (idx1 + 4); // Vertex index for end of segment
// Average normals
float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f;
@@ -716,8 +866,8 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32
float dm_in_x = dm_x * half_inner_thickness;
float dm_in_y = dm_y * half_inner_thickness;
- // Add temporary vertexes
- ImVec2* out_vtx = &temp_points[i2*4];
+ // Add temporary vertices
+ ImVec2* out_vtx = &temp_points[i2 * 4];
out_vtx[0].x = points[i2].x + dm_out_x;
out_vtx[0].y = points[i2].y + dm_out_y;
out_vtx[1].x = points[i2].x + dm_in_x;
@@ -728,24 +878,24 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32
out_vtx[3].y = points[i2].y - dm_out_y;
// Add indexes
- _IdxWritePtr[0] = (ImDrawIdx)(idx2+1); _IdxWritePtr[1] = (ImDrawIdx)(idx1+1); _IdxWritePtr[2] = (ImDrawIdx)(idx1+2);
- _IdxWritePtr[3] = (ImDrawIdx)(idx1+2); _IdxWritePtr[4] = (ImDrawIdx)(idx2+2); _IdxWritePtr[5] = (ImDrawIdx)(idx2+1);
- _IdxWritePtr[6] = (ImDrawIdx)(idx2+1); _IdxWritePtr[7] = (ImDrawIdx)(idx1+1); _IdxWritePtr[8] = (ImDrawIdx)(idx1+0);
- _IdxWritePtr[9] = (ImDrawIdx)(idx1+0); _IdxWritePtr[10] = (ImDrawIdx)(idx2+0); _IdxWritePtr[11] = (ImDrawIdx)(idx2+1);
- _IdxWritePtr[12] = (ImDrawIdx)(idx2+2); _IdxWritePtr[13] = (ImDrawIdx)(idx1+2); _IdxWritePtr[14] = (ImDrawIdx)(idx1+3);
- _IdxWritePtr[15] = (ImDrawIdx)(idx1+3); _IdxWritePtr[16] = (ImDrawIdx)(idx2+3); _IdxWritePtr[17] = (ImDrawIdx)(idx2+2);
+ _IdxWritePtr[0] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[1] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[2] = (ImDrawIdx)(idx1 + 2);
+ _IdxWritePtr[3] = (ImDrawIdx)(idx1 + 2); _IdxWritePtr[4] = (ImDrawIdx)(idx2 + 2); _IdxWritePtr[5] = (ImDrawIdx)(idx2 + 1);
+ _IdxWritePtr[6] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[7] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[8] = (ImDrawIdx)(idx1 + 0);
+ _IdxWritePtr[9] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[10] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[11] = (ImDrawIdx)(idx2 + 1);
+ _IdxWritePtr[12] = (ImDrawIdx)(idx2 + 2); _IdxWritePtr[13] = (ImDrawIdx)(idx1 + 2); _IdxWritePtr[14] = (ImDrawIdx)(idx1 + 3);
+ _IdxWritePtr[15] = (ImDrawIdx)(idx1 + 3); _IdxWritePtr[16] = (ImDrawIdx)(idx2 + 3); _IdxWritePtr[17] = (ImDrawIdx)(idx2 + 2);
_IdxWritePtr += 18;
idx1 = idx2;
}
- // Add vertexes
+ // Add vertices
for (int i = 0; i < points_count; i++)
{
- _VtxWritePtr[0].pos = temp_points[i*4+0]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col_trans;
- _VtxWritePtr[1].pos = temp_points[i*4+1]; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col;
- _VtxWritePtr[2].pos = temp_points[i*4+2]; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col;
- _VtxWritePtr[3].pos = temp_points[i*4+3]; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col_trans;
+ _VtxWritePtr[0].pos = temp_points[i * 4 + 0]; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col_trans;
+ _VtxWritePtr[1].pos = temp_points[i * 4 + 1]; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col;
+ _VtxWritePtr[2].pos = temp_points[i * 4 + 2]; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col;
+ _VtxWritePtr[3].pos = temp_points[i * 4 + 3]; _VtxWritePtr[3].uv = opaque_uv; _VtxWritePtr[3].col = col_trans;
_VtxWritePtr += 4;
}
}
@@ -753,14 +903,14 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32
}
else
{
- // Non Anti-aliased Stroke
- const int idx_count = count*6;
- const int vtx_count = count*4; // FIXME-OPT: Not sharing edges
+ // [PATH 4] Non texture-based, Non anti-aliased lines
+ const int idx_count = count * 6;
+ const int vtx_count = count * 4; // FIXME-OPT: Not sharing edges
PrimReserve(idx_count, vtx_count);
for (int i1 = 0; i1 < count; i1++)
{
- const int i2 = (i1+1) == points_count ? 0 : i1+1;
+ const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1;
const ImVec2& p1 = points[i1];
const ImVec2& p2 = points[i2];
@@ -770,14 +920,14 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32
dx *= (thickness * 0.5f);
dy *= (thickness * 0.5f);
- _VtxWritePtr[0].pos.x = p1.x + dy; _VtxWritePtr[0].pos.y = p1.y - dx; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col;
- _VtxWritePtr[1].pos.x = p2.x + dy; _VtxWritePtr[1].pos.y = p2.y - dx; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col;
- _VtxWritePtr[2].pos.x = p2.x - dy; _VtxWritePtr[2].pos.y = p2.y + dx; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col;
- _VtxWritePtr[3].pos.x = p1.x - dy; _VtxWritePtr[3].pos.y = p1.y + dx; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col;
+ _VtxWritePtr[0].pos.x = p1.x + dy; _VtxWritePtr[0].pos.y = p1.y - dx; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col;
+ _VtxWritePtr[1].pos.x = p2.x + dy; _VtxWritePtr[1].pos.y = p2.y - dx; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col;
+ _VtxWritePtr[2].pos.x = p2.x - dy; _VtxWritePtr[2].pos.y = p2.y + dx; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col;
+ _VtxWritePtr[3].pos.x = p1.x - dy; _VtxWritePtr[3].pos.y = p1.y + dx; _VtxWritePtr[3].uv = opaque_uv; _VtxWritePtr[3].col = col;
_VtxWritePtr += 4;
- _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx+1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx+2);
- _IdxWritePtr[3] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[4] = (ImDrawIdx)(_VtxCurrentIdx+2); _IdxWritePtr[5] = (ImDrawIdx)(_VtxCurrentIdx+3);
+ _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx + 1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx + 2);
+ _IdxWritePtr[3] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[4] = (ImDrawIdx)(_VtxCurrentIdx + 2); _IdxWritePtr[5] = (ImDrawIdx)(_VtxCurrentIdx + 3);
_IdxWritePtr += 6;
_VtxCurrentIdx += 4;
}
@@ -795,24 +945,24 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun
if (Flags & ImDrawListFlags_AntiAliasedFill)
{
// Anti-aliased Fill
- const float AA_SIZE = 1.0f;
+ const float AA_SIZE = _FringeScale;
const ImU32 col_trans = col & ~IM_COL32_A_MASK;
- const int idx_count = (points_count-2)*3 + points_count*6;
- const int vtx_count = (points_count*2);
+ const int idx_count = (points_count - 2)*3 + points_count * 6;
+ const int vtx_count = (points_count * 2);
PrimReserve(idx_count, vtx_count);
// Add indexes for fill
unsigned int vtx_inner_idx = _VtxCurrentIdx;
- unsigned int vtx_outer_idx = _VtxCurrentIdx+1;
+ unsigned int vtx_outer_idx = _VtxCurrentIdx + 1;
for (int i = 2; i < points_count; i++)
{
- _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx+((i-1)<<1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_inner_idx+(i<<1));
+ _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx + ((i - 1) << 1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_inner_idx + (i << 1));
_IdxWritePtr += 3;
}
// Compute normals
ImVec2* temp_normals = (ImVec2*)alloca(points_count * sizeof(ImVec2)); //-V630
- for (int i0 = points_count-1, i1 = 0; i1 < points_count; i0 = i1++)
+ for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++)
{
const ImVec2& p0 = points[i0];
const ImVec2& p1 = points[i1];
@@ -823,7 +973,7 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun
temp_normals[i0].y = -dx;
}
- for (int i0 = points_count-1, i1 = 0; i1 < points_count; i0 = i1++)
+ for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++)
{
// Average normals
const ImVec2& n0 = temp_normals[i0];
@@ -840,8 +990,8 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun
_VtxWritePtr += 2;
// Add indexes for fringes
- _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx+(i1<<1)); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx+(i0<<1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_outer_idx+(i0<<1));
- _IdxWritePtr[3] = (ImDrawIdx)(vtx_outer_idx+(i0<<1)); _IdxWritePtr[4] = (ImDrawIdx)(vtx_outer_idx+(i1<<1)); _IdxWritePtr[5] = (ImDrawIdx)(vtx_inner_idx+(i1<<1));
+ _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx + (i1 << 1)); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx + (i0 << 1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_outer_idx + (i0 << 1));
+ _IdxWritePtr[3] = (ImDrawIdx)(vtx_outer_idx + (i0 << 1)); _IdxWritePtr[4] = (ImDrawIdx)(vtx_outer_idx + (i1 << 1)); _IdxWritePtr[5] = (ImDrawIdx)(vtx_inner_idx + (i1 << 1));
_IdxWritePtr += 6;
}
_VtxCurrentIdx += (ImDrawIdx)vtx_count;
@@ -849,7 +999,7 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun
else
{
// Non Anti-aliased Fill
- const int idx_count = (points_count-2)*3;
+ const int idx_count = (points_count - 2)*3;
const int vtx_count = points_count;
PrimReserve(idx_count, vtx_count);
for (int i = 0; i < vtx_count; i++)
@@ -859,7 +1009,7 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun
}
for (int i = 2; i < points_count; i++)
{
- _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx+i-1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx+i);
+ _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx + i - 1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx + i);
_IdxWritePtr += 3;
}
_VtxCurrentIdx += (ImDrawIdx)vtx_count;
@@ -873,10 +1023,18 @@ void ImDrawList::PathArcToFast(const ImVec2& center, float radius, int a_min_of_
_Path.push_back(center);
return;
}
+
+ // For legacy reason the PathArcToFast() always takes angles where 2*PI is represented by 12,
+ // but it is possible to set IM_DRAWLIST_ARCFAST_TESSELATION_MULTIPLIER to a higher value. This should compile to a no-op otherwise.
+#if IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER != 1
+ a_min_of_12 *= IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER;
+ a_max_of_12 *= IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER;
+#endif
+
_Path.reserve(_Path.Size + (a_max_of_12 - a_min_of_12 + 1));
for (int a = a_min_of_12; a <= a_max_of_12; a++)
{
- const ImVec2& c = _Data->CircleVtx12[a % IM_ARRAYSIZE(_Data->CircleVtx12)];
+ const ImVec2& c = _Data->ArcFastVtx[a % IM_ARRAYSIZE(_Data->ArcFastVtx)];
_Path.push_back(ImVec2(center.x + c.x * radius, center.y + c.y * radius));
}
}
@@ -899,53 +1057,96 @@ void ImDrawList::PathArcTo(const ImVec2& center, float radius, float a_min, floa
}
}
-static void PathBezierToCasteljau(ImVector* path, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
+ImVec2 ImBezierCubicCalc(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, float t)
+{
+ float u = 1.0f - t;
+ float w1 = u * u * u;
+ float w2 = 3 * u * u * t;
+ float w3 = 3 * u * t * t;
+ float w4 = t * t * t;
+ return ImVec2(w1 * p1.x + w2 * p2.x + w3 * p3.x + w4 * p4.x, w1 * p1.y + w2 * p2.y + w3 * p3.y + w4 * p4.y);
+}
+
+ImVec2 ImBezierQuadraticCalc(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, float t)
+{
+ float u = 1.0f - t;
+ float w1 = u * u;
+ float w2 = 2 * u * t;
+ float w3 = t * t;
+ return ImVec2(w1 * p1.x + w2 * p2.x + w3 * p3.x, w1 * p1.y + w2 * p2.y + w3 * p3.y);
+}
+
+// Closely mimics ImBezierCubicClosestPointCasteljau() in imgui.cpp
+static void PathBezierCubicCurveToCasteljau(ImVector* path, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
{
float dx = x4 - x1;
float dy = y4 - y1;
- float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
- float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
+ float d2 = (x2 - x4) * dy - (y2 - y4) * dx;
+ float d3 = (x3 - x4) * dy - (y3 - y4) * dx;
d2 = (d2 >= 0) ? d2 : -d2;
d3 = (d3 >= 0) ? d3 : -d3;
- if ((d2+d3) * (d2+d3) < tess_tol * (dx*dx + dy*dy))
+ if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
{
path->push_back(ImVec2(x4, y4));
}
else if (level < 10)
{
- float x12 = (x1+x2)*0.5f, y12 = (y1+y2)*0.5f;
- float x23 = (x2+x3)*0.5f, y23 = (y2+y3)*0.5f;
- float x34 = (x3+x4)*0.5f, y34 = (y3+y4)*0.5f;
- float x123 = (x12+x23)*0.5f, y123 = (y12+y23)*0.5f;
- float x234 = (x23+x34)*0.5f, y234 = (y23+y34)*0.5f;
- float x1234 = (x123+x234)*0.5f, y1234 = (y123+y234)*0.5f;
-
- PathBezierToCasteljau(path, x1,y1, x12,y12, x123,y123, x1234,y1234, tess_tol, level+1);
- PathBezierToCasteljau(path, x1234,y1234, x234,y234, x34,y34, x4,y4, tess_tol, level+1);
+ float x12 = (x1 + x2) * 0.5f, y12 = (y1 + y2) * 0.5f;
+ float x23 = (x2 + x3) * 0.5f, y23 = (y2 + y3) * 0.5f;
+ float x34 = (x3 + x4) * 0.5f, y34 = (y3 + y4) * 0.5f;
+ float x123 = (x12 + x23) * 0.5f, y123 = (y12 + y23) * 0.5f;
+ float x234 = (x23 + x34) * 0.5f, y234 = (y23 + y34) * 0.5f;
+ float x1234 = (x123 + x234) * 0.5f, y1234 = (y123 + y234) * 0.5f;
+ PathBezierCubicCurveToCasteljau(path, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
+ PathBezierCubicCurveToCasteljau(path, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
}
}
-void ImDrawList::PathBezierCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments)
+static void PathBezierQuadraticCurveToCasteljau(ImVector* path, float x1, float y1, float x2, float y2, float x3, float y3, float tess_tol, int level)
+{
+ float dx = x3 - x1, dy = y3 - y1;
+ float det = (x2 - x3) * dy - (y2 - y3) * dx;
+ if (det * det * 4.0f < tess_tol * (dx * dx + dy * dy))
+ {
+ path->push_back(ImVec2(x3, y3));
+ }
+ else if (level < 10)
+ {
+ float x12 = (x1 + x2) * 0.5f, y12 = (y1 + y2) * 0.5f;
+ float x23 = (x2 + x3) * 0.5f, y23 = (y2 + y3) * 0.5f;
+ float x123 = (x12 + x23) * 0.5f, y123 = (y12 + y23) * 0.5f;
+ PathBezierQuadraticCurveToCasteljau(path, x1, y1, x12, y12, x123, y123, tess_tol, level + 1);
+ PathBezierQuadraticCurveToCasteljau(path, x123, y123, x23, y23, x3, y3, tess_tol, level + 1);
+ }
+}
+
+void ImDrawList::PathBezierCubicCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments)
{
ImVec2 p1 = _Path.back();
if (num_segments == 0)
{
- // Auto-tessellated
- PathBezierToCasteljau(&_Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, _Data->CurveTessellationTol, 0);
+ PathBezierCubicCurveToCasteljau(&_Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, _Data->CurveTessellationTol, 0); // Auto-tessellated
}
else
{
float t_step = 1.0f / (float)num_segments;
for (int i_step = 1; i_step <= num_segments; i_step++)
- {
- float t = t_step * i_step;
- float u = 1.0f - t;
- float w1 = u*u*u;
- float w2 = 3*u*u*t;
- float w3 = 3*u*t*t;
- float w4 = t*t*t;
- _Path.push_back(ImVec2(w1*p1.x + w2*p2.x + w3*p3.x + w4*p4.x, w1*p1.y + w2*p2.y + w3*p3.y + w4*p4.y));
- }
+ _Path.push_back(ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step));
+ }
+}
+
+void ImDrawList::PathBezierQuadraticCurveTo(const ImVec2& p2, const ImVec2& p3, int num_segments)
+{
+ ImVec2 p1 = _Path.back();
+ if (num_segments == 0)
+ {
+ PathBezierQuadraticCurveToCasteljau(&_Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, _Data->CurveTessellationTol, 0);// Auto-tessellated
+ }
+ else
+ {
+ float t_step = 1.0f / (float)num_segments;
+ for (int i_step = 1; i_step <= num_segments; i_step++)
+ _Path.push_back(ImBezierQuadraticCalc(p1, p2, p3, t_step * i_step));
}
}
@@ -990,9 +1191,9 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl
if ((col & IM_COL32_A_MASK) == 0)
return;
if (Flags & ImDrawListFlags_AntiAliasedLines)
- PathRect(p_min + ImVec2(0.50f,0.50f), p_max - ImVec2(0.50f,0.50f), rounding, rounding_corners);
+ PathRect(p_min + ImVec2(0.50f, 0.50f), p_max - ImVec2(0.50f, 0.50f), rounding, rounding_corners);
else
- PathRect(p_min + ImVec2(0.50f,0.50f), p_max - ImVec2(0.49f,0.49f), rounding, rounding_corners); // Better looking lower-right corner and rounded non-AA shapes.
+ PathRect(p_min + ImVec2(0.50f, 0.50f), p_max - ImVec2(0.49f, 0.49f), rounding, rounding_corners); // Better looking lower-right corner and rounded non-AA shapes.
PathStroke(col, true, thickness);
}
@@ -1020,8 +1221,8 @@ void ImDrawList::AddRectFilledMultiColor(const ImVec2& p_min, const ImVec2& p_ma
const ImVec2 uv = _Data->TexUvWhitePixel;
PrimReserve(6, 4);
- PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+1)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+2));
- PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+2)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+3));
+ PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx + 1)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx + 2));
+ PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx + 2)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx + 3));
PrimWriteVtx(p_min, uv, col_upr_left);
PrimWriteVtx(ImVec2(p_max.x, p_min.y), uv, col_upr_right);
PrimWriteVtx(p_max, uv, col_bot_right);
@@ -1075,6 +1276,67 @@ void ImDrawList::AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImV
}
void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness)
+{
+ if ((col & IM_COL32_A_MASK) == 0 || radius <= 0.0f)
+ return;
+
+ // Obtain segment count
+ if (num_segments <= 0)
+ {
+ // Automatic segment count
+ const int radius_idx = (int)radius;
+ if (radius_idx < IM_ARRAYSIZE(_Data->CircleSegmentCounts))
+ num_segments = _Data->CircleSegmentCounts[radius_idx]; // Use cached value
+ else
+ num_segments = IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(radius, _Data->CircleSegmentMaxError);
+ }
+ else
+ {
+ // Explicit segment count (still clamp to avoid drawing insanely tessellated shapes)
+ num_segments = ImClamp(num_segments, 3, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX);
+ }
+
+ // Because we are filling a closed shape we remove 1 from the count of segments/points
+ const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments;
+ if (num_segments == 12)
+ PathArcToFast(center, radius - 0.5f, 0, 12 - 1);
+ else
+ PathArcTo(center, radius - 0.5f, 0.0f, a_max, num_segments - 1);
+ PathStroke(col, true, thickness);
+}
+
+void ImDrawList::AddCircleFilled(const ImVec2& center, float radius, ImU32 col, int num_segments)
+{
+ if ((col & IM_COL32_A_MASK) == 0 || radius <= 0.0f)
+ return;
+
+ // Obtain segment count
+ if (num_segments <= 0)
+ {
+ // Automatic segment count
+ const int radius_idx = (int)radius;
+ if (radius_idx < IM_ARRAYSIZE(_Data->CircleSegmentCounts))
+ num_segments = _Data->CircleSegmentCounts[radius_idx]; // Use cached value
+ else
+ num_segments = IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(radius, _Data->CircleSegmentMaxError);
+ }
+ else
+ {
+ // Explicit segment count (still clamp to avoid drawing insanely tessellated shapes)
+ num_segments = ImClamp(num_segments, 3, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX);
+ }
+
+ // Because we are filling a closed shape we remove 1 from the count of segments/points
+ const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments;
+ if (num_segments == 12)
+ PathArcToFast(center, radius, 0, 12 - 1);
+ else
+ PathArcTo(center, radius, 0.0f, a_max, num_segments - 1);
+ PathFillConvex(col);
+}
+
+// Guaranteed to honor 'num_segments'
+void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness)
{
if ((col & IM_COL32_A_MASK) == 0 || num_segments <= 2)
return;
@@ -1085,7 +1347,8 @@ void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int nu
PathStroke(col, true, thickness);
}
-void ImDrawList::AddCircleFilled(const ImVec2& center, float radius, ImU32 col, int num_segments)
+// Guaranteed to honor 'num_segments'
+void ImDrawList::AddNgonFilled(const ImVec2& center, float radius, ImU32 col, int num_segments)
{
if ((col & IM_COL32_A_MASK) == 0 || num_segments <= 2)
return;
@@ -1096,13 +1359,25 @@ void ImDrawList::AddCircleFilled(const ImVec2& center, float radius, ImU32 col,
PathFillConvex(col);
}
-void ImDrawList::AddBezierCurve(const ImVec2& pos0, const ImVec2& cp0, const ImVec2& cp1, const ImVec2& pos1, ImU32 col, float thickness, int num_segments)
+// Cubic Bezier takes 4 controls points
+void ImDrawList::AddBezierCubic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments)
{
if ((col & IM_COL32_A_MASK) == 0)
return;
- PathLineTo(pos0);
- PathBezierCurveTo(cp0, cp1, pos1, num_segments);
+ PathLineTo(p1);
+ PathBezierCubicCurveTo(p2, p3, p4, num_segments);
+ PathStroke(col, false, thickness);
+}
+
+// Quadratic Bezier takes 3 controls points
+void ImDrawList::AddBezierQuadratic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness, int num_segments)
+{
+ if ((col & IM_COL32_A_MASK) == 0)
+ return;
+
+ PathLineTo(p1);
+ PathBezierQuadraticCurveTo(p2, p3, num_segments);
PathStroke(col, false, thickness);
}
@@ -1122,9 +1397,9 @@ void ImDrawList::AddText(const ImFont* font, float font_size, const ImVec2& pos,
if (font_size == 0.0f)
font_size = _Data->FontSize;
- IM_ASSERT(font->ContainerAtlas->TexID == _TextureIdStack.back()); // Use high-level ImGui::PushFont() or low-level ImDrawList::PushTextureId() to change font.
+ IM_ASSERT(font->ContainerAtlas->TexID == _CmdHeader.TextureId); // Use high-level ImGui::PushFont() or low-level ImDrawList::PushTextureId() to change font.
- ImVec4 clip_rect = _ClipRectStack.back();
+ ImVec4 clip_rect = _CmdHeader.ClipRect;
if (cpu_fine_clip_rect)
{
clip_rect.x = ImMax(clip_rect.x, cpu_fine_clip_rect->x);
@@ -1145,7 +1420,7 @@ void ImDrawList::AddImage(ImTextureID user_texture_id, const ImVec2& p_min, cons
if ((col & IM_COL32_A_MASK) == 0)
return;
- const bool push_texture_id = _TextureIdStack.empty() || user_texture_id != _TextureIdStack.back();
+ const bool push_texture_id = user_texture_id != _CmdHeader.TextureId;
if (push_texture_id)
PushTextureID(user_texture_id);
@@ -1161,7 +1436,7 @@ void ImDrawList::AddImageQuad(ImTextureID user_texture_id, const ImVec2& p1, con
if ((col & IM_COL32_A_MASK) == 0)
return;
- const bool push_texture_id = _TextureIdStack.empty() || user_texture_id != _TextureIdStack.back();
+ const bool push_texture_id = user_texture_id != _CmdHeader.TextureId;
if (push_texture_id)
PushTextureID(user_texture_id);
@@ -1199,7 +1474,7 @@ void ImDrawList::AddImageRounded(ImTextureID user_texture_id, const ImVec2& p_mi
//-----------------------------------------------------------------------------
-// ImDrawListSplitter
+// [SECTION] ImDrawListSplitter
//-----------------------------------------------------------------------------
// FIXME: This may be a little confusing, trying to be a little too low-level/optimal instead of just doing vector swap..
//-----------------------------------------------------------------------------
@@ -1220,10 +1495,14 @@ void ImDrawListSplitter::ClearFreeMemory()
void ImDrawListSplitter::Split(ImDrawList* draw_list, int channels_count)
{
- IM_ASSERT(_Current == 0 && _Count <= 1);
+ IM_UNUSED(draw_list);
+ IM_ASSERT(_Current == 0 && _Count <= 1 && "Nested channel splitting is not supported. Please use separate instances of ImDrawListSplitter.");
int old_channels_count = _Channels.Size;
if (old_channels_count < channels_count)
+ {
+ _Channels.reserve(channels_count); // Avoid over reserving since this is likely to stay stable
_Channels.resize(channels_count);
+ }
_Count = channels_count;
// Channels[] (24/32 bytes each) hold storage that we'll swap with draw_list->_CmdBuffer/_IdxBuffer
@@ -1241,30 +1520,17 @@ void ImDrawListSplitter::Split(ImDrawList* draw_list, int channels_count)
_Channels[i]._CmdBuffer.resize(0);
_Channels[i]._IdxBuffer.resize(0);
}
- if (_Channels[i]._CmdBuffer.Size == 0)
- {
- ImDrawCmd draw_cmd;
- draw_cmd.ClipRect = draw_list->_ClipRectStack.back();
- draw_cmd.TextureId = draw_list->_TextureIdStack.back();
- _Channels[i]._CmdBuffer.push_back(draw_cmd);
- }
}
}
-static inline bool CanMergeDrawCommands(ImDrawCmd* a, ImDrawCmd* b)
-{
- return memcmp(&a->ClipRect, &b->ClipRect, sizeof(a->ClipRect)) == 0 && a->TextureId == b->TextureId && a->VtxOffset == b->VtxOffset && !a->UserCallback && !b->UserCallback;
-}
-
void ImDrawListSplitter::Merge(ImDrawList* draw_list)
{
- // Note that we never use or rely on channels.Size because it is merely a buffer that we never shrink back to 0 to keep all sub-buffers ready for use.
+ // Note that we never use or rely on _Channels.Size because it is merely a buffer that we never shrink back to 0 to keep all sub-buffers ready for use.
if (_Count <= 1)
return;
SetCurrentChannel(draw_list, 0);
- if (draw_list->CmdBuffer.Size != 0 && draw_list->CmdBuffer.back().ElemCount == 0)
- draw_list->CmdBuffer.pop_back();
+ draw_list->_PopUnusedDrawCmd();
// Calculate our final buffer sizes. Also fix the incorrect IdxOffset values in each command.
int new_cmd_buffer_count = 0;
@@ -1274,14 +1540,21 @@ void ImDrawListSplitter::Merge(ImDrawList* draw_list)
for (int i = 1; i < _Count; i++)
{
ImDrawChannel& ch = _Channels[i];
+
+ // Equivalent of PopUnusedDrawCmd() for this channel's cmdbuffer and except we don't need to test for UserCallback.
if (ch._CmdBuffer.Size > 0 && ch._CmdBuffer.back().ElemCount == 0)
ch._CmdBuffer.pop_back();
- if (ch._CmdBuffer.Size > 0 && last_cmd != NULL && CanMergeDrawCommands(last_cmd, &ch._CmdBuffer[0]))
+
+ if (ch._CmdBuffer.Size > 0 && last_cmd != NULL)
{
- // Merge previous channel last draw command with current channel first draw command if matching.
- last_cmd->ElemCount += ch._CmdBuffer[0].ElemCount;
- idx_offset += ch._CmdBuffer[0].ElemCount;
- ch._CmdBuffer.erase(ch._CmdBuffer.Data);
+ ImDrawCmd* next_cmd = &ch._CmdBuffer[0];
+ if (ImDrawCmd_HeaderCompare(last_cmd, next_cmd) == 0 && last_cmd->UserCallback == NULL && next_cmd->UserCallback == NULL)
+ {
+ // Merge previous channel last draw command with current channel first draw command if matching.
+ last_cmd->ElemCount += next_cmd->ElemCount;
+ idx_offset += next_cmd->ElemCount;
+ ch._CmdBuffer.erase(ch._CmdBuffer.Data); // FIXME-OPT: Improve for multiple merges.
+ }
}
if (ch._CmdBuffer.Size > 0)
last_cmd = &ch._CmdBuffer.back();
@@ -1306,8 +1579,18 @@ void ImDrawListSplitter::Merge(ImDrawList* draw_list)
if (int sz = ch._IdxBuffer.Size) { memcpy(idx_write, ch._IdxBuffer.Data, sz * sizeof(ImDrawIdx)); idx_write += sz; }
}
draw_list->_IdxWritePtr = idx_write;
- draw_list->UpdateClipRect(); // We call this instead of AddDrawCmd(), so that empty channels won't produce an extra draw call.
- draw_list->UpdateTextureID();
+
+ // Ensure there's always a non-callback draw command trailing the command-buffer
+ if (draw_list->CmdBuffer.Size == 0 || draw_list->CmdBuffer.back().UserCallback != NULL)
+ draw_list->AddDrawCmd();
+
+ // If current command is used with different settings we need to add a new command
+ ImDrawCmd* curr_cmd = &draw_list->CmdBuffer.Data[draw_list->CmdBuffer.Size - 1];
+ if (curr_cmd->ElemCount == 0)
+ ImDrawCmd_HeaderCopy(curr_cmd, &draw_list->_CmdHeader); // Copy ClipRect, TextureId, VtxOffset
+ else if (ImDrawCmd_HeaderCompare(curr_cmd, &draw_list->_CmdHeader) != 0)
+ draw_list->AddDrawCmd();
+
_Count = 1;
}
@@ -1316,6 +1599,7 @@ void ImDrawListSplitter::SetCurrentChannel(ImDrawList* draw_list, int idx)
IM_ASSERT(idx >= 0 && idx < _Count);
if (_Current == idx)
return;
+
// Overwrite ImVector (12/16 bytes), four times. This is merely a silly optimization instead of doing .swap()
memcpy(&_Channels.Data[_Current]._CmdBuffer, &draw_list->CmdBuffer, sizeof(draw_list->CmdBuffer));
memcpy(&_Channels.Data[_Current]._IdxBuffer, &draw_list->IdxBuffer, sizeof(draw_list->IdxBuffer));
@@ -1323,6 +1607,15 @@ void ImDrawListSplitter::SetCurrentChannel(ImDrawList* draw_list, int idx)
memcpy(&draw_list->CmdBuffer, &_Channels.Data[idx]._CmdBuffer, sizeof(draw_list->CmdBuffer));
memcpy(&draw_list->IdxBuffer, &_Channels.Data[idx]._IdxBuffer, sizeof(draw_list->IdxBuffer));
draw_list->_IdxWritePtr = draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size;
+
+ // If current command is used with different settings we need to add a new command
+ ImDrawCmd* curr_cmd = (draw_list->CmdBuffer.Size == 0) ? NULL : &draw_list->CmdBuffer.Data[draw_list->CmdBuffer.Size - 1];
+ if (curr_cmd == NULL)
+ draw_list->AddDrawCmd();
+ else if (curr_cmd->ElemCount == 0)
+ ImDrawCmd_HeaderCopy(curr_cmd, &draw_list->_CmdHeader); // Copy ClipRect, TextureId, VtxOffset
+ else if (ImDrawCmd_HeaderCompare(curr_cmd, &draw_list->_CmdHeader) != 0)
+ draw_list->AddDrawCmd();
}
//-----------------------------------------------------------------------------
@@ -1375,13 +1668,19 @@ void ImGui::ShadeVertsLinearColorGradientKeepAlpha(ImDrawList* draw_list, int ve
float gradient_inv_length2 = 1.0f / ImLengthSqr(gradient_extent);
ImDrawVert* vert_start = draw_list->VtxBuffer.Data + vert_start_idx;
ImDrawVert* vert_end = draw_list->VtxBuffer.Data + vert_end_idx;
+ const int col0_r = (int)(col0 >> IM_COL32_R_SHIFT) & 0xFF;
+ const int col0_g = (int)(col0 >> IM_COL32_G_SHIFT) & 0xFF;
+ const int col0_b = (int)(col0 >> IM_COL32_B_SHIFT) & 0xFF;
+ const int col_delta_r = ((int)(col1 >> IM_COL32_R_SHIFT) & 0xFF) - col0_r;
+ const int col_delta_g = ((int)(col1 >> IM_COL32_G_SHIFT) & 0xFF) - col0_g;
+ const int col_delta_b = ((int)(col1 >> IM_COL32_B_SHIFT) & 0xFF) - col0_b;
for (ImDrawVert* vert = vert_start; vert < vert_end; vert++)
{
float d = ImDot(vert->pos - gradient_p0, gradient_extent);
float t = ImClamp(d * gradient_inv_length2, 0.0f, 1.0f);
- int r = ImLerp((int)(col0 >> IM_COL32_R_SHIFT) & 0xFF, (int)(col1 >> IM_COL32_R_SHIFT) & 0xFF, t);
- int g = ImLerp((int)(col0 >> IM_COL32_G_SHIFT) & 0xFF, (int)(col1 >> IM_COL32_G_SHIFT) & 0xFF, t);
- int b = ImLerp((int)(col0 >> IM_COL32_B_SHIFT) & 0xFF, (int)(col1 >> IM_COL32_B_SHIFT) & 0xFF, t);
+ int r = (int)(col0_r + col_delta_r * t);
+ int g = (int)(col0_g + col_delta_g * t);
+ int b = (int)(col0_b + col_delta_b * t);
vert->col = (r << IM_COL32_R_SHIFT) | (g << IM_COL32_G_SHIFT) | (b << IM_COL32_B_SHIFT) | (vert->col & IM_COL32_A_MASK);
}
}
@@ -1417,25 +1716,13 @@ void ImGui::ShadeVertsLinearUV(ImDrawList* draw_list, int vert_start_idx, int ve
ImFontConfig::ImFontConfig()
{
- FontData = NULL;
- FontDataSize = 0;
+ memset(this, 0, sizeof(*this));
FontDataOwnedByAtlas = true;
- FontNo = 0;
- SizePixels = 0.0f;
OversampleH = 3; // FIXME: 2 may be a better default?
OversampleV = 1;
- PixelSnapH = false;
- GlyphExtraSpacing = ImVec2(0.0f, 0.0f);
- GlyphOffset = ImVec2(0.0f, 0.0f);
- GlyphRanges = NULL;
- GlyphMinAdvanceX = 0.0f;
GlyphMaxAdvanceX = FLT_MAX;
- MergeMode = false;
- RasterizerFlags = 0x00;
RasterizerMultiply = 1.0f;
EllipsisChar = (ImWchar)-1;
- memset(Name, 0, sizeof(Name));
- DstFont = NULL;
}
//-----------------------------------------------------------------------------
@@ -1443,11 +1730,10 @@ ImFontConfig::ImFontConfig()
//-----------------------------------------------------------------------------
// A work of art lies ahead! (. = white layer, X = black layer, others are blank)
-// The white texels on the top left are the ones we'll use everywhere in Dear ImGui to render filled shapes.
-const int FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF = 108;
-const int FONT_ATLAS_DEFAULT_TEX_DATA_H = 27;
-const unsigned int FONT_ATLAS_DEFAULT_TEX_DATA_ID = 0x80000000;
-static const char FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * FONT_ATLAS_DEFAULT_TEX_DATA_H + 1] =
+// The 2x2 white texels on the top left are the ones we'll use everywhere in Dear ImGui to render filled shapes.
+const int FONT_ATLAS_DEFAULT_TEX_DATA_W = 108; // Actual texture will be 2 times that + 1 spacing.
+const int FONT_ATLAS_DEFAULT_TEX_DATA_H = 27;
+static const char FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[FONT_ATLAS_DEFAULT_TEX_DATA_W * FONT_ATLAS_DEFAULT_TEX_DATA_H + 1] =
{
"..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX- XX "
"..- -X.....X- X.X - X.X -X.....X - X.....X- X..X "
@@ -1493,19 +1779,9 @@ static const ImVec2 FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[ImGuiMouseCursor_COUNT][3
ImFontAtlas::ImFontAtlas()
{
- Locked = false;
- Flags = ImFontAtlasFlags_None;
- TexID = (ImTextureID)NULL;
- TexDesiredWidth = 0;
+ memset(this, 0, sizeof(*this));
TexGlyphPadding = 1;
-
- TexPixelsAlpha8 = NULL;
- TexPixelsRGBA32 = NULL;
- TexWidth = TexHeight = 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;
+ PackIdMouseCursors = PackIdLines = -1;
}
ImFontAtlas::~ImFontAtlas()
@@ -1533,8 +1809,7 @@ void ImFontAtlas::ClearInputData()
}
ConfigData.clear();
CustomRects.clear();
- for (int n = 0; n < IM_ARRAYSIZE(CustomRectIds); n++)
- CustomRectIds[n] = -1;
+ PackIdMouseCursors = PackIdLines = -1;
}
void ImFontAtlas::ClearTexData()
@@ -1635,15 +1910,15 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg)
}
// 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 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)
{
while (*src)
{
- unsigned int tmp = Decode85Byte(src[0]) + 85*(Decode85Byte(src[1]) + 85*(Decode85Byte(src[2]) + 85*(Decode85Byte(src[3]) + 85*Decode85Byte(src[4]))));
+ unsigned int tmp = Decode85Byte(src[0]) + 85 * (Decode85Byte(src[1]) + 85 * (Decode85Byte(src[2]) + 85 * (Decode85Byte(src[3]) + 85 * Decode85Byte(src[4]))));
dst[0] = ((tmp >> 0) & 0xFF); dst[1] = ((tmp >> 8) & 0xFF); dst[2] = ((tmp >> 16) & 0xFF); dst[3] = ((tmp >> 24) & 0xFF); // We can't assume little-endianness.
src += 5;
dst += 4;
@@ -1664,11 +1939,11 @@ ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template)
if (font_cfg.Name[0] == '\0')
ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "ProggyClean.ttf, %dpx", (int)font_cfg.SizePixels);
font_cfg.EllipsisChar = (ImWchar)0x0085;
+ font_cfg.GlyphOffset.y = 1.0f * IM_FLOOR(font_cfg.SizePixels / 13.0f); // Add +1 offset per 13 units
const char* ttf_compressed_base85 = GetDefaultCompressedFontDataTTFBase85();
const ImWchar* glyph_ranges = font_cfg.GlyphRanges != NULL ? font_cfg.GlyphRanges : GetGlyphRangesDefault();
ImFont* font = AddFontFromMemoryCompressedBase85TTF(ttf_compressed_base85, font_cfg.SizePixels, &font_cfg, glyph_ranges);
- font->DisplayOffset.y = 1.0f;
return font;
}
@@ -1679,7 +1954,7 @@ ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels,
void* data = ImFileLoadToMemory(filename, "rb", &data_size, 0);
if (!data)
{
- IM_ASSERT(0); // Could not load file.
+ IM_ASSERT_USER_ERROR(0, "Could not load font file!");
return NULL;
}
ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig();
@@ -1710,7 +1985,7 @@ 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((const unsigned char*)compressed_ttf_data);
- unsigned char* buf_decompressed_data = (unsigned char *)IM_ALLOC(buf_decompressed_size);
+ unsigned char* buf_decompressed_data = (unsigned char*)IM_ALLOC(buf_decompressed_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();
@@ -1729,13 +2004,11 @@ ImFont* ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char* compressed
return font;
}
-int ImFontAtlas::AddCustomRectRegular(unsigned int id, int width, int height)
+int ImFontAtlas::AddCustomRectRegular(int width, int height)
{
- IM_ASSERT(id >= 0x10000);
IM_ASSERT(width > 0 && width <= 0xFFFF);
IM_ASSERT(height > 0 && height <= 0xFFFF);
ImFontAtlasCustomRect r;
- r.ID = id;
r.Width = (unsigned short)width;
r.Height = (unsigned short)height;
CustomRects.push_back(r);
@@ -1744,13 +2017,16 @@ int ImFontAtlas::AddCustomRectRegular(unsigned int id, int width, int height)
int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset)
{
+#ifdef IMGUI_USE_WCHAR32
+ IM_ASSERT(id <= IM_UNICODE_CODEPOINT_MAX);
+#endif
IM_ASSERT(font != NULL);
IM_ASSERT(width > 0 && width <= 0xFFFF);
IM_ASSERT(height > 0 && height <= 0xFFFF);
ImFontAtlasCustomRect r;
- r.ID = id;
r.Width = (unsigned short)width;
r.Height = (unsigned short)height;
+ r.GlyphID = id;
r.GlyphAdvanceX = advance_x;
r.GlyphOffset = offset;
r.Font = font;
@@ -1758,7 +2034,7 @@ int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int
return CustomRects.Size - 1; // Return index
}
-void ImFontAtlas::CalcCustomRectUV(const ImFontAtlasCustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max)
+void ImFontAtlas::CalcCustomRectUV(const ImFontAtlasCustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const
{
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
@@ -1773,16 +2049,15 @@ bool ImFontAtlas::GetMouseCursorTexData(ImGuiMouseCursor cursor_type, ImVec2* ou
if (Flags & ImFontAtlasFlags_NoMouseCursors)
return false;
- IM_ASSERT(CustomRectIds[0] != -1);
- ImFontAtlasCustomRect& 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);
+ IM_ASSERT(PackIdMouseCursors != -1);
+ ImFontAtlasCustomRect* r = GetCustomRectByIndex(PackIdMouseCursors);
+ 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;
+ pos.x += FONT_ATLAS_DEFAULT_TEX_DATA_W + 1;
out_uv_fill[0] = (pos) * TexUvScale;
out_uv_fill[1] = (pos + size) * TexUvScale;
return true;
@@ -1791,7 +2066,26 @@ bool ImFontAtlas::GetMouseCursorTexData(ImGuiMouseCursor cursor_type, ImVec2* ou
bool ImFontAtlas::Build()
{
IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!");
- return ImFontAtlasBuildWithStbTruetype(this);
+
+ // Select builder
+ // - Note that we do not reassign to atlas->FontBuilderIO, since it is likely to point to static data which
+ // may mess with some hot-reloading schemes. If you need to assign to this (for dynamic selection) AND are
+ // using a hot-reloading scheme that messes up static data, store your own instance of ImFontBuilderIO somewhere
+ // and point to it instead of pointing directly to return value of the GetBuilderXXX functions.
+ const ImFontBuilderIO* builder_io = FontBuilderIO;
+ if (builder_io == NULL)
+ {
+#ifdef IMGUI_ENABLE_FREETYPE
+ builder_io = ImGuiFreeType::GetBuilderForFreeType();
+#elif defined(IMGUI_ENABLE_STB_TRUETYPE)
+ builder_io = ImFontAtlasGetBuilderForStbTruetype();
+#else
+ IM_ASSERT(0); // Invalid Build function
+#endif
+ }
+
+ // Build
+ return builder_io->FontBuilder_Build(this);
}
void ImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256], float in_brighten_factor)
@@ -1811,6 +2105,7 @@ void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsig
data[i] = table[data[i]];
}
+#ifdef IMGUI_ENABLE_STB_TRUETYPE
// Temporary data for one source font (multiple source fonts can be merged into one destination ImFont)
// (C++03 doesn't allow instancing ImVector<> with function-local types so we declare the type here.)
struct ImFontBuildSrcData
@@ -1823,7 +2118,7 @@ struct ImFontBuildSrcData
int DstIndex; // Index into atlas->Fonts[] and dst_tmp_array[]
int GlyphsHighest; // Highest requested codepoint
int GlyphsCount; // Glyph count (excluding missing glyphs and glyphs already set by an earlier source font)
- ImBoolVector GlyphsSet; // Glyph bit map (random access, 1-bit per codepoint. This will be a maximum of 8KB)
+ ImBitVector GlyphsSet; // Glyph bit map (random access, 1-bit per codepoint. This will be a maximum of 8KB)
ImVector GlyphsList; // Glyph codepoints list (flattened version of GlyphsMap)
};
@@ -1833,26 +2128,26 @@ struct ImFontBuildDstData
int SrcCount; // Number of source fonts targeting this destination font.
int GlyphsHighest;
int GlyphsCount;
- ImBoolVector GlyphsSet; // This is used to resolve collision when multiple sources are merged into a same destination font.
+ ImBitVector GlyphsSet; // This is used to resolve collision when multiple sources are merged into a same destination font.
};
-static void UnpackBoolVectorToFlatIndexList(const ImBoolVector* in, ImVector* out)
+static void UnpackBitVectorToFlatIndexList(const ImBitVector* in, ImVector* out)
{
IM_ASSERT(sizeof(in->Storage.Data[0]) == sizeof(int));
- const int* it_begin = in->Storage.begin();
- const int* it_end = in->Storage.end();
- for (const int* it = it_begin; it < it_end; it++)
- if (int entries_32 = *it)
- for (int bit_n = 0; bit_n < 32; bit_n++)
- if (entries_32 & (1u << bit_n))
- out->push_back((int)((it - it_begin) << 5) + bit_n);
+ const ImU32* it_begin = in->Storage.begin();
+ const ImU32* it_end = in->Storage.end();
+ for (const ImU32* it = it_begin; it < it_end; it++)
+ if (ImU32 entries_32 = *it)
+ for (ImU32 bit_n = 0; bit_n < 32; bit_n++)
+ if (entries_32 & ((ImU32)1 << bit_n))
+ out->push_back((int)(((it - it_begin) << 5) + bit_n));
}
-bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
+static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
{
IM_ASSERT(atlas->ConfigData.Size > 0);
- ImFontAtlasBuildRegisterDefaultCustomRects(atlas);
+ ImFontAtlasBuildInit(atlas);
// Clear atlas
atlas->TexID = (ImTextureID)NULL;
@@ -1881,10 +2176,11 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
for (int output_i = 0; output_i < atlas->Fonts.Size && src_tmp.DstIndex == -1; output_i++)
if (cfg.DstFont == atlas->Fonts[output_i])
src_tmp.DstIndex = output_i;
- IM_ASSERT(src_tmp.DstIndex != -1); // cfg.DstFont not pointing within atlas->Fonts[] array?
if (src_tmp.DstIndex == -1)
+ {
+ IM_ASSERT(src_tmp.DstIndex != -1); // cfg.DstFont not pointing within atlas->Fonts[] array?
return false;
-
+ }
// Initialize helper structure for font loading and verify that the TTF/OTF data is correct
const int font_offset = stbtt_GetFontOffsetForIndex((unsigned char*)cfg.FontData, cfg.FontNo);
IM_ASSERT(font_offset >= 0 && "FontData is incorrect, or FontNo cannot be found.");
@@ -1906,14 +2202,14 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
{
ImFontBuildSrcData& src_tmp = src_tmp_array[src_i];
ImFontBuildDstData& dst_tmp = dst_tmp_array[src_tmp.DstIndex];
- src_tmp.GlyphsSet.Resize(src_tmp.GlyphsHighest + 1);
+ src_tmp.GlyphsSet.Create(src_tmp.GlyphsHighest + 1);
if (dst_tmp.GlyphsSet.Storage.empty())
- dst_tmp.GlyphsSet.Resize(dst_tmp.GlyphsHighest + 1);
+ dst_tmp.GlyphsSet.Create(dst_tmp.GlyphsHighest + 1);
for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2)
- for (int codepoint = src_range[0]; codepoint <= src_range[1]; codepoint++)
+ for (unsigned int codepoint = src_range[0]; codepoint <= src_range[1]; codepoint++)
{
- if (dst_tmp.GlyphsSet.GetBit(codepoint)) // Don't overwrite existing glyphs. We could make this an option for MergeMode (e.g. MergeOverwrite==true)
+ if (dst_tmp.GlyphsSet.TestBit(codepoint)) // Don't overwrite existing glyphs. We could make this an option for MergeMode (e.g. MergeOverwrite==true)
continue;
if (!stbtt_FindGlyphIndex(&src_tmp.FontInfo, codepoint)) // It is actually in the font?
continue;
@@ -1921,8 +2217,8 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
// Add to avail set/counters
src_tmp.GlyphsCount++;
dst_tmp.GlyphsCount++;
- src_tmp.GlyphsSet.SetBit(codepoint, true);
- dst_tmp.GlyphsSet.SetBit(codepoint, true);
+ src_tmp.GlyphsSet.SetBit(codepoint);
+ dst_tmp.GlyphsSet.SetBit(codepoint);
total_glyphs_count++;
}
}
@@ -1932,7 +2228,7 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
{
ImFontBuildSrcData& src_tmp = src_tmp_array[src_i];
src_tmp.GlyphsList.reserve(src_tmp.GlyphsCount);
- UnpackBoolVectorToFlatIndexList(&src_tmp.GlyphsSet, &src_tmp.GlyphsList);
+ UnpackBitVectorToFlatIndexList(&src_tmp.GlyphsSet, &src_tmp.GlyphsList);
src_tmp.GlyphsSet.Clear();
IM_ASSERT(src_tmp.GlyphsList.Size == src_tmp.GlyphsCount);
}
@@ -1997,7 +2293,7 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
if (atlas->TexDesiredWidth > 0)
atlas->TexWidth = atlas->TexDesiredWidth;
else
- atlas->TexWidth = (surface_sqrt >= 4096*0.7f) ? 4096 : (surface_sqrt >= 2048*0.7f) ? 2048 : (surface_sqrt >= 1024*0.7f) ? 1024 : 512;
+ atlas->TexWidth = (surface_sqrt >= 4096 * 0.7f) ? 4096 : (surface_sqrt >= 2048 * 0.7f) ? 2048 : (surface_sqrt >= 1024 * 0.7f) ? 1024 : 512;
// 5. Start packing
// Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values).
@@ -2064,8 +2360,11 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
if (src_tmp.GlyphsCount == 0)
continue;
+ // When merging fonts with MergeMode=true:
+ // - We can have multiple input fonts writing into a same destination font.
+ // - dst_font->ConfigData is != from cfg which is our source configuration.
ImFontConfig& cfg = atlas->ConfigData[src_i];
- ImFont* dst_font = cfg.DstFont; // We can have multiple input fonts writing into a same destination font (when using MergeMode=true)
+ ImFont* dst_font = cfg.DstFont;
const float font_scale = stbtt_ScaleForPixelHeight(&src_tmp.FontInfo, cfg.SizePixels);
int unscaled_ascent, unscaled_descent, unscaled_line_gap;
@@ -2075,24 +2374,17 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
const float descent = ImFloor(unscaled_descent * font_scale + ((unscaled_descent > 0.0f) ? +1 : -1));
ImFontAtlasBuildSetupFont(atlas, dst_font, &cfg, ascent, descent);
const float font_off_x = cfg.GlyphOffset.x;
- const float font_off_y = cfg.GlyphOffset.y + ImFloor(dst_font->Ascent + 0.5f);
+ const float font_off_y = cfg.GlyphOffset.y + IM_ROUND(dst_font->Ascent);
for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++)
{
+ // Register glyph
const int codepoint = src_tmp.GlyphsList[glyph_i];
const stbtt_packedchar& pc = src_tmp.PackedChars[glyph_i];
-
- const float char_advance_x_org = pc.xadvance;
- const float char_advance_x_mod = ImClamp(char_advance_x_org, cfg.GlyphMinAdvanceX, cfg.GlyphMaxAdvanceX);
- float char_off_x = font_off_x;
- if (char_advance_x_org != char_advance_x_mod)
- char_off_x += cfg.PixelSnapH ? ImFloor((char_advance_x_mod - char_advance_x_org) * 0.5f) : (char_advance_x_mod - char_advance_x_org) * 0.5f;
-
- // Register glyph
stbtt_aligned_quad q;
- float dummy_x = 0.0f, dummy_y = 0.0f;
- stbtt_GetPackedQuad(src_tmp.PackedChars, atlas->TexWidth, atlas->TexHeight, glyph_i, &dummy_x, &dummy_y, &q, 0);
- dst_font->AddGlyph((ImWchar)codepoint, q.x0 + char_off_x, q.y0 + font_off_y, q.x1 + char_off_x, q.y1 + font_off_y, q.s0, q.t0, q.s1, q.t1, char_advance_x_mod);
+ float unused_x = 0.0f, unused_y = 0.0f;
+ stbtt_GetPackedQuad(src_tmp.PackedChars, atlas->TexWidth, atlas->TexHeight, glyph_i, &unused_x, &unused_y, &q, 0);
+ dst_font->AddGlyph(&cfg, (ImWchar)codepoint, q.x0 + font_off_x, q.y0 + font_off_y, q.x1 + font_off_x, q.y1 + font_off_y, q.s0, q.t0, q.s1, q.t1, pc.xadvance);
}
}
@@ -2104,16 +2396,15 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
return true;
}
-void ImFontAtlasBuildRegisterDefaultCustomRects(ImFontAtlas* atlas)
+const ImFontBuilderIO* ImFontAtlasGetBuilderForStbTruetype()
{
- 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);
+ static ImFontBuilderIO io;
+ io.FontBuilder_Build = ImFontAtlasBuildWithStbTruetype;
+ return &io;
}
+#endif // IMGUI_ENABLE_STB_TRUETYPE
+
void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent)
{
if (!font_config->MergeMode)
@@ -2121,6 +2412,7 @@ void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* f
font->ClearOutputData();
font->FontSize = font_config->SizePixels;
font->ConfigData = font_config;
+ font->ConfigDataCount = 0;
font->ContainerAtlas = atlas;
font->Ascent = ascent;
font->Descent = descent;
@@ -2155,53 +2447,113 @@ void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opa
}
}
+void ImFontAtlasBuildRender8bppRectFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char, unsigned char in_marker_pixel_value)
+{
+ IM_ASSERT(x >= 0 && x + w <= atlas->TexWidth);
+ IM_ASSERT(y >= 0 && y + h <= atlas->TexHeight);
+ unsigned char* out_pixel = atlas->TexPixelsAlpha8 + x + (y * atlas->TexWidth);
+ for (int off_y = 0; off_y < h; off_y++, out_pixel += atlas->TexWidth, in_str += w)
+ for (int off_x = 0; off_x < w; off_x++)
+ out_pixel[off_x] = (in_str[off_x] == in_marker_char) ? in_marker_pixel_value : 0x00;
+}
+
static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas)
{
- IM_ASSERT(atlas->CustomRectIds[0] >= 0);
- IM_ASSERT(atlas->TexPixelsAlpha8 != NULL);
- ImFontAtlasCustomRect& r = atlas->CustomRects[atlas->CustomRectIds[0]];
- IM_ASSERT(r.ID == FONT_ATLAS_DEFAULT_TEX_DATA_ID);
- IM_ASSERT(r.IsPacked());
+ ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(atlas->PackIdMouseCursors);
+ IM_ASSERT(r->IsPacked());
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;
- }
+ IM_ASSERT(r->Width == FONT_ATLAS_DEFAULT_TEX_DATA_W * 2 + 1 && r->Height == FONT_ATLAS_DEFAULT_TEX_DATA_H);
+ const int x_for_white = r->X;
+ const int x_for_black = r->X + FONT_ATLAS_DEFAULT_TEX_DATA_W + 1;
+ ImFontAtlasBuildRender8bppRectFromString(atlas, x_for_white, r->Y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, '.', 0xFF);
+ ImFontAtlasBuildRender8bppRectFromString(atlas, x_for_black, r->Y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, 'X', 0xFF);
}
else
{
- IM_ASSERT(r.Width == 2 && r.Height == 2);
- const int offset = (int)(r.X) + (int)(r.Y) * w;
+ // Render 4 white pixels
+ 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);
+ atlas->TexUvWhitePixel = ImVec2((r->X + 0.5f) * atlas->TexUvScale.x, (r->Y + 0.5f) * atlas->TexUvScale.y);
}
+static void ImFontAtlasBuildRenderLinesTexData(ImFontAtlas* atlas)
+{
+ if (atlas->Flags & ImFontAtlasFlags_NoBakedLines)
+ return;
+
+ // This generates a triangular shape in the texture, with the various line widths stacked on top of each other to allow interpolation between them
+ ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(atlas->PackIdLines);
+ IM_ASSERT(r->IsPacked());
+ for (unsigned int n = 0; n < IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1; n++) // +1 because of the zero-width row
+ {
+ // Each line consists of at least two empty pixels at the ends, with a line of solid pixels in the middle
+ unsigned int y = n;
+ unsigned int line_width = n;
+ unsigned int pad_left = (r->Width - line_width) / 2;
+ unsigned int pad_right = r->Width - (pad_left + line_width);
+
+ // Write each slice
+ IM_ASSERT(pad_left + line_width + pad_right == r->Width && y < r->Height); // Make sure we're inside the texture bounds before we start writing pixels
+ unsigned char* write_ptr = &atlas->TexPixelsAlpha8[r->X + ((r->Y + y) * atlas->TexWidth)];
+ memset(write_ptr, 0x00, pad_left);
+ memset(write_ptr + pad_left, 0xFF, line_width);
+ memset(write_ptr + pad_left + line_width, 0x00, pad_right);
+
+ // Calculate UVs for this line
+ ImVec2 uv0 = ImVec2((float)(r->X + pad_left - 1), (float)(r->Y + y)) * atlas->TexUvScale;
+ ImVec2 uv1 = ImVec2((float)(r->X + pad_left + line_width + 1), (float)(r->Y + y + 1)) * atlas->TexUvScale;
+ float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts
+ atlas->TexUvLines[n] = ImVec4(uv0.x, half_v, uv1.x, half_v);
+ }
+}
+
+// Note: this is called / shared by both the stb_truetype and the FreeType builder
+void ImFontAtlasBuildInit(ImFontAtlas* atlas)
+{
+ // Register texture region for mouse cursors or standard white pixels
+ if (atlas->PackIdMouseCursors < 0)
+ {
+ if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors))
+ atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_W * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H);
+ else
+ atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(2, 2);
+ }
+
+ // Register texture region for thick lines
+ // The +2 here is to give space for the end caps, whilst height +1 is to accommodate the fact we have a zero-width row
+ if (atlas->PackIdLines < 0)
+ {
+ if (!(atlas->Flags & ImFontAtlasFlags_NoBakedLines))
+ atlas->PackIdLines = atlas->AddCustomRectRegular(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1);
+ }
+}
+
+// This is called/shared by both the stb_truetype and the FreeType builder.
void ImFontAtlasBuildFinish(ImFontAtlas* atlas)
{
- // Render into our custom data block
+ // Render into our custom data blocks
+ IM_ASSERT(atlas->TexPixelsAlpha8 != NULL);
ImFontAtlasBuildRenderDefaultTexData(atlas);
+ ImFontAtlasBuildRenderLinesTexData(atlas);
// Register custom rectangle glyphs
for (int i = 0; i < atlas->CustomRects.Size; i++)
{
- const ImFontAtlasCustomRect& r = atlas->CustomRects[i];
- if (r.Font == NULL || r.ID > 0x10000)
+ const ImFontAtlasCustomRect* r = &atlas->CustomRects[i];
+ if (r->Font == NULL || r->GlyphID == 0)
continue;
- IM_ASSERT(r.Font->ContainerAtlas == atlas);
+ // Will ignore ImFontConfig settings: GlyphMinAdvanceX, GlyphMinAdvanceY, GlyphExtraSpacing, PixelSnapH
+ IM_ASSERT(r->Font->ContainerAtlas == atlas);
ImVec2 uv0, uv1;
- atlas->CalcCustomRectUV(&r, &uv0, &uv1);
- r.Font->AddGlyph((ImWchar)r.ID, r.GlyphOffset.x, r.GlyphOffset.y, r.GlyphOffset.x + r.Width, r.GlyphOffset.y + r.Height, uv0.x, uv0.y, uv1.x, uv1.y, r.GlyphAdvanceX);
+ atlas->CalcCustomRectUV(r, &uv0, &uv1);
+ r->Font->AddGlyph(NULL, (ImWchar)r->GlyphID, r->GlyphOffset.x, r->GlyphOffset.y, r->GlyphOffset.x + r->Width, r->GlyphOffset.y + r->Height, uv0.x, uv0.y, uv1.x, uv1.y, r->GlyphAdvanceX);
}
// Build all fonts lookup tables
@@ -2211,7 +2563,7 @@ void ImFontAtlasBuildFinish(ImFontAtlas* atlas)
// Ellipsis character is required for rendering elided text. We prefer using U+2026 (horizontal ellipsis).
// However some old fonts may contain ellipsis at U+0085. Here we auto-detect most suitable ellipsis character.
- // FIXME: Also note that 0x2026 is currently seldomly included in our font ranges. Because of this we are more likely to use three individual dots.
+ // FIXME: Also note that 0x2026 is currently seldom included in our font ranges. Because of this we are more likely to use three individual dots.
for (int i = 0; i < atlas->Fonts.size(); i++)
{
ImFont* font = atlas->Fonts[i];
@@ -2244,7 +2596,7 @@ const ImWchar* ImFontAtlas::GetGlyphRangesKorean()
{
0x0020, 0x00FF, // Basic Latin + Latin Supplement
0x3131, 0x3163, // Korean alphabets
- 0xAC00, 0xD79D, // Korean characters
+ 0xAC00, 0xD7A3, // Korean characters
0,
};
return &ranges[0];
@@ -2348,45 +2700,76 @@ const ImWchar* ImFontAtlas::GetGlyphRangesChineseSimplifiedCommon()
const ImWchar* ImFontAtlas::GetGlyphRangesJapanese()
{
- // 1946 common ideograms code points for Japanese
- // Sourced from http://theinstructionlimit.com/common-kanji-character-ranges-for-xna-spritefont-rendering
- // FIXME: Source a list of the revised 2136 Joyo Kanji list from 2010 and rebuild this.
+ // 2999 ideograms code points for Japanese
+ // - 2136 Joyo (meaning "for regular use" or "for common use") Kanji code points
+ // - 863 Jinmeiyo (meaning "for personal name") Kanji code points
+ // - Sourced from the character information database of the Information-technology Promotion Agency, Japan
+ // - https://mojikiban.ipa.go.jp/mji/
+ // - Available under the terms of the Creative Commons Attribution-ShareAlike 2.1 Japan (CC BY-SA 2.1 JP).
+ // - https://creativecommons.org/licenses/by-sa/2.1/jp/deed.en
+ // - https://creativecommons.org/licenses/by-sa/2.1/jp/legalcode
+ // - You can generate this code by the script at:
+ // - https://github.com/vaiorabbit/everyday_use_kanji
+ // - References:
+ // - List of Joyo Kanji
+ // - (Official list by the Agency for Cultural Affairs) https://www.bunka.go.jp/kokugo_nihongo/sisaku/joho/joho/kakuki/14/tosin02/index.html
+ // - (Wikipedia) https://en.wikipedia.org/wiki/List_of_j%C5%8Dy%C5%8D_kanji
+ // - List of Jinmeiyo Kanji
+ // - (Official list by the Ministry of Justice) http://www.moj.go.jp/MINJI/minji86.html
+ // - (Wikipedia) https://en.wikipedia.org/wiki/Jinmeiy%C5%8D_kanji
+ // - Missing 1 Joyo Kanji: U+20B9F (Kun'yomi: Shikaru, On'yomi: Shitsu,shichi), see https://github.com/ocornut/imgui/pull/3627 for details.
// You can use ImFontGlyphRangesBuilder to create your own ranges derived from this, by merging existing ranges or adding new characters.
// (Stored as accumulative offsets from the initial unicode codepoint 0x4E00. This encoding is designed to helps us compact the source code size.)
static const short accumulative_offsets_from_0x4E00[] =
{
- 0,1,2,4,1,1,1,1,2,1,6,2,2,1,8,5,7,11,1,2,10,10,8,2,4,20,2,11,8,2,1,2,1,6,2,1,7,5,3,7,1,1,13,7,9,1,4,6,1,2,1,10,1,1,9,2,2,4,5,6,14,1,1,9,3,18,
- 5,4,2,2,10,7,1,1,1,3,2,4,3,23,2,10,12,2,14,2,4,13,1,6,10,3,1,7,13,6,4,13,5,2,3,17,2,2,5,7,6,4,1,7,14,16,6,13,9,15,1,1,7,16,4,7,1,19,9,2,7,15,
- 2,6,5,13,25,4,14,13,11,25,1,1,1,2,1,2,2,3,10,11,3,3,1,1,4,4,2,1,4,9,1,4,3,5,5,2,7,12,11,15,7,16,4,5,16,2,1,1,6,3,3,1,1,2,7,6,6,7,1,4,7,6,1,1,
- 2,1,12,3,3,9,5,8,1,11,1,2,3,18,20,4,1,3,6,1,7,3,5,5,7,2,2,12,3,1,4,2,3,2,3,11,8,7,4,17,1,9,25,1,1,4,2,2,4,1,2,7,1,1,1,3,1,2,6,16,1,2,1,1,3,12,
- 20,2,5,20,8,7,6,2,1,1,1,1,6,2,1,2,10,1,1,6,1,3,1,2,1,4,1,12,4,1,3,1,1,1,1,1,10,4,7,5,13,1,15,1,1,30,11,9,1,15,38,14,1,32,17,20,1,9,31,2,21,9,
- 4,49,22,2,1,13,1,11,45,35,43,55,12,19,83,1,3,2,3,13,2,1,7,3,18,3,13,8,1,8,18,5,3,7,25,24,9,24,40,3,17,24,2,1,6,2,3,16,15,6,7,3,12,1,9,7,3,3,
- 3,15,21,5,16,4,5,12,11,11,3,6,3,2,31,3,2,1,1,23,6,6,1,4,2,6,5,2,1,1,3,3,22,2,6,2,3,17,3,2,4,5,1,9,5,1,1,6,15,12,3,17,2,14,2,8,1,23,16,4,2,23,
- 8,15,23,20,12,25,19,47,11,21,65,46,4,3,1,5,6,1,2,5,26,2,1,1,3,11,1,1,1,2,1,2,3,1,1,10,2,3,1,1,1,3,6,3,2,2,6,6,9,2,2,2,6,2,5,10,2,4,1,2,1,2,2,
- 3,1,1,3,1,2,9,23,9,2,1,1,1,1,5,3,2,1,10,9,6,1,10,2,31,25,3,7,5,40,1,15,6,17,7,27,180,1,3,2,2,1,1,1,6,3,10,7,1,3,6,17,8,6,2,2,1,3,5,5,8,16,14,
- 15,1,1,4,1,2,1,1,1,3,2,7,5,6,2,5,10,1,4,2,9,1,1,11,6,1,44,1,3,7,9,5,1,3,1,1,10,7,1,10,4,2,7,21,15,7,2,5,1,8,3,4,1,3,1,6,1,4,2,1,4,10,8,1,4,5,
- 1,5,10,2,7,1,10,1,1,3,4,11,10,29,4,7,3,5,2,3,33,5,2,19,3,1,4,2,6,31,11,1,3,3,3,1,8,10,9,12,11,12,8,3,14,8,6,11,1,4,41,3,1,2,7,13,1,5,6,2,6,12,
- 12,22,5,9,4,8,9,9,34,6,24,1,1,20,9,9,3,4,1,7,2,2,2,6,2,28,5,3,6,1,4,6,7,4,2,1,4,2,13,6,4,4,3,1,8,8,3,2,1,5,1,2,2,3,1,11,11,7,3,6,10,8,6,16,16,
- 22,7,12,6,21,5,4,6,6,3,6,1,3,2,1,2,8,29,1,10,1,6,13,6,6,19,31,1,13,4,4,22,17,26,33,10,4,15,12,25,6,67,10,2,3,1,6,10,2,6,2,9,1,9,4,4,1,2,16,2,
- 5,9,2,3,8,1,8,3,9,4,8,6,4,8,11,3,2,1,1,3,26,1,7,5,1,11,1,5,3,5,2,13,6,39,5,1,5,2,11,6,10,5,1,15,5,3,6,19,21,22,2,4,1,6,1,8,1,4,8,2,4,2,2,9,2,
- 1,1,1,4,3,6,3,12,7,1,14,2,4,10,2,13,1,17,7,3,2,1,3,2,13,7,14,12,3,1,29,2,8,9,15,14,9,14,1,3,1,6,5,9,11,3,38,43,20,7,7,8,5,15,12,19,15,81,8,7,
- 1,5,73,13,37,28,8,8,1,15,18,20,165,28,1,6,11,8,4,14,7,15,1,3,3,6,4,1,7,14,1,1,11,30,1,5,1,4,14,1,4,2,7,52,2,6,29,3,1,9,1,21,3,5,1,26,3,11,14,
- 11,1,17,5,1,2,1,3,2,8,1,2,9,12,1,1,2,3,8,3,24,12,7,7,5,17,3,3,3,1,23,10,4,4,6,3,1,16,17,22,3,10,21,16,16,6,4,10,2,1,1,2,8,8,6,5,3,3,3,39,25,
- 15,1,1,16,6,7,25,15,6,6,12,1,22,13,1,4,9,5,12,2,9,1,12,28,8,3,5,10,22,60,1,2,40,4,61,63,4,1,13,12,1,4,31,12,1,14,89,5,16,6,29,14,2,5,49,18,18,
- 5,29,33,47,1,17,1,19,12,2,9,7,39,12,3,7,12,39,3,1,46,4,12,3,8,9,5,31,15,18,3,2,2,66,19,13,17,5,3,46,124,13,57,34,2,5,4,5,8,1,1,1,4,3,1,17,5,
- 3,5,3,1,8,5,6,3,27,3,26,7,12,7,2,17,3,7,18,78,16,4,36,1,2,1,6,2,1,39,17,7,4,13,4,4,4,1,10,4,2,4,6,3,10,1,19,1,26,2,4,33,2,73,47,7,3,8,2,4,15,
- 18,1,29,2,41,14,1,21,16,41,7,39,25,13,44,2,2,10,1,13,7,1,7,3,5,20,4,8,2,49,1,10,6,1,6,7,10,7,11,16,3,12,20,4,10,3,1,2,11,2,28,9,2,4,7,2,15,1,
- 27,1,28,17,4,5,10,7,3,24,10,11,6,26,3,2,7,2,2,49,16,10,16,15,4,5,27,61,30,14,38,22,2,7,5,1,3,12,23,24,17,17,3,3,2,4,1,6,2,7,5,1,1,5,1,1,9,4,
- 1,3,6,1,8,2,8,4,14,3,5,11,4,1,3,32,1,19,4,1,13,11,5,2,1,8,6,8,1,6,5,13,3,23,11,5,3,16,3,9,10,1,24,3,198,52,4,2,2,5,14,5,4,22,5,20,4,11,6,41,
- 1,5,2,2,11,5,2,28,35,8,22,3,18,3,10,7,5,3,4,1,5,3,8,9,3,6,2,16,22,4,5,5,3,3,18,23,2,6,23,5,27,8,1,33,2,12,43,16,5,2,3,6,1,20,4,2,9,7,1,11,2,
- 10,3,14,31,9,3,25,18,20,2,5,5,26,14,1,11,17,12,40,19,9,6,31,83,2,7,9,19,78,12,14,21,76,12,113,79,34,4,1,1,61,18,85,10,2,2,13,31,11,50,6,33,159,
- 179,6,6,7,4,4,2,4,2,5,8,7,20,32,22,1,3,10,6,7,28,5,10,9,2,77,19,13,2,5,1,4,4,7,4,13,3,9,31,17,3,26,2,6,6,5,4,1,7,11,3,4,2,1,6,2,20,4,1,9,2,6,
- 3,7,1,1,1,20,2,3,1,6,2,3,6,2,4,8,1,5,13,8,4,11,23,1,10,6,2,1,3,21,2,2,4,24,31,4,10,10,2,5,192,15,4,16,7,9,51,1,2,1,1,5,1,1,2,1,3,5,3,1,3,4,1,
- 3,1,3,3,9,8,1,2,2,2,4,4,18,12,92,2,10,4,3,14,5,25,16,42,4,14,4,2,21,5,126,30,31,2,1,5,13,3,22,5,6,6,20,12,1,14,12,87,3,19,1,8,2,9,9,3,3,23,2,
- 3,7,6,3,1,2,3,9,1,3,1,6,3,2,1,3,11,3,1,6,10,3,2,3,1,2,1,5,1,1,11,3,6,4,1,7,2,1,2,5,5,34,4,14,18,4,19,7,5,8,2,6,79,1,5,2,14,8,2,9,2,1,36,28,16,
- 4,1,1,1,2,12,6,42,39,16,23,7,15,15,3,2,12,7,21,64,6,9,28,8,12,3,3,41,59,24,51,55,57,294,9,9,2,6,2,15,1,2,13,38,90,9,9,9,3,11,7,1,1,1,5,6,3,2,
- 1,2,2,3,8,1,4,4,1,5,7,1,4,3,20,4,9,1,1,1,5,5,17,1,5,2,6,2,4,1,4,5,7,3,18,11,11,32,7,5,4,7,11,127,8,4,3,3,1,10,1,1,6,21,14,1,16,1,7,1,3,6,9,65,
- 51,4,3,13,3,10,1,1,12,9,21,110,3,19,24,1,1,10,62,4,1,29,42,78,28,20,18,82,6,3,15,6,84,58,253,15,155,264,15,21,9,14,7,58,40,39,
+ 0,1,2,4,1,1,1,1,2,1,3,3,2,2,1,5,3,5,7,5,6,1,2,1,7,2,6,3,1,8,1,1,4,1,1,18,2,11,2,6,2,1,2,1,5,1,2,1,3,1,2,1,2,3,3,1,1,2,3,1,1,1,12,7,9,1,4,5,1,
+ 1,2,1,10,1,1,9,2,2,4,5,6,9,3,1,1,1,1,9,3,18,5,2,2,2,2,1,6,3,7,1,1,1,1,2,2,4,2,1,23,2,10,4,3,5,2,4,10,2,4,13,1,6,1,9,3,1,1,6,6,7,6,3,1,2,11,3,
+ 2,2,3,2,15,2,2,5,4,3,6,4,1,2,5,2,12,16,6,13,9,13,2,1,1,7,16,4,7,1,19,1,5,1,2,2,7,7,8,2,6,5,4,9,18,7,4,5,9,13,11,8,15,2,1,1,1,2,1,2,2,1,2,2,8,
+ 2,9,3,3,1,1,4,4,1,1,1,4,9,1,4,3,5,5,2,7,5,3,4,8,2,1,13,2,3,3,1,14,1,1,4,5,1,3,6,1,5,2,1,1,3,3,3,3,1,1,2,7,6,6,7,1,4,7,6,1,1,1,1,1,12,3,3,9,5,
+ 2,6,1,5,6,1,2,3,18,2,4,14,4,1,3,6,1,1,6,3,5,5,3,2,2,2,2,12,3,1,4,2,3,2,3,11,1,7,4,1,2,1,3,17,1,9,1,24,1,1,4,2,2,4,1,2,7,1,1,1,3,1,2,2,4,15,1,
+ 1,2,1,1,2,1,5,2,5,20,2,5,9,1,10,8,7,6,1,1,1,1,1,1,6,2,1,2,8,1,1,1,1,5,1,1,3,1,1,1,1,3,1,1,12,4,1,3,1,1,1,1,1,10,3,1,7,5,13,1,2,3,4,6,1,1,30,
+ 2,9,9,1,15,38,11,3,1,8,24,7,1,9,8,10,2,1,9,31,2,13,6,2,9,4,49,5,2,15,2,1,10,2,1,1,1,2,2,6,15,30,35,3,14,18,8,1,16,10,28,12,19,45,38,1,3,2,3,
+ 13,2,1,7,3,6,5,3,4,3,1,5,7,8,1,5,3,18,5,3,6,1,21,4,24,9,24,40,3,14,3,21,3,2,1,2,4,2,3,1,15,15,6,5,1,1,3,1,5,6,1,9,7,3,3,2,1,4,3,8,21,5,16,4,
+ 5,2,10,11,11,3,6,3,2,9,3,6,13,1,2,1,1,1,1,11,12,6,6,1,4,2,6,5,2,1,1,3,3,6,13,3,1,1,5,1,2,3,3,14,2,1,2,2,2,5,1,9,5,1,1,6,12,3,12,3,4,13,2,14,
+ 2,8,1,17,5,1,16,4,2,2,21,8,9,6,23,20,12,25,19,9,38,8,3,21,40,25,33,13,4,3,1,4,1,2,4,1,2,5,26,2,1,1,2,1,3,6,2,1,1,1,1,1,1,2,3,1,1,1,9,2,3,1,1,
+ 1,3,6,3,2,1,1,6,6,1,8,2,2,2,1,4,1,2,3,2,7,3,2,4,1,2,1,2,2,1,1,1,1,1,3,1,2,5,4,10,9,4,9,1,1,1,1,1,1,5,3,2,1,6,4,9,6,1,10,2,31,17,8,3,7,5,40,1,
+ 7,7,1,6,5,2,10,7,8,4,15,39,25,6,28,47,18,10,7,1,3,1,1,2,1,1,1,3,3,3,1,1,1,3,4,2,1,4,1,3,6,10,7,8,6,2,2,1,3,3,2,5,8,7,9,12,2,15,1,1,4,1,2,1,1,
+ 1,3,2,1,3,3,5,6,2,3,2,10,1,4,2,8,1,1,1,11,6,1,21,4,16,3,1,3,1,4,2,3,6,5,1,3,1,1,3,3,4,6,1,1,10,4,2,7,10,4,7,4,2,9,4,3,1,1,1,4,1,8,3,4,1,3,1,
+ 6,1,4,2,1,4,7,2,1,8,1,4,5,1,1,2,2,4,6,2,7,1,10,1,1,3,4,11,10,8,21,4,6,1,3,5,2,1,2,28,5,5,2,3,13,1,2,3,1,4,2,1,5,20,3,8,11,1,3,3,3,1,8,10,9,2,
+ 10,9,2,3,1,1,2,4,1,8,3,6,1,7,8,6,11,1,4,29,8,4,3,1,2,7,13,1,4,1,6,2,6,12,12,2,20,3,2,3,6,4,8,9,2,7,34,5,1,18,6,1,1,4,4,5,7,9,1,2,2,4,3,4,1,7,
+ 2,2,2,6,2,3,25,5,3,6,1,4,6,7,4,2,1,4,2,13,6,4,4,3,1,5,3,4,4,3,2,1,1,4,1,2,1,1,3,1,11,1,6,3,1,7,3,6,2,8,8,6,9,3,4,11,3,2,10,12,2,5,11,1,6,4,5,
+ 3,1,8,5,4,6,6,3,5,1,1,3,2,1,2,2,6,17,12,1,10,1,6,12,1,6,6,19,9,6,16,1,13,4,4,15,7,17,6,11,9,15,12,6,7,2,1,2,2,15,9,3,21,4,6,49,18,7,3,2,3,1,
+ 6,8,2,2,6,2,9,1,3,6,4,4,1,2,16,2,5,2,1,6,2,3,5,3,1,2,5,1,2,1,9,3,1,8,6,4,8,11,3,1,1,1,1,3,1,13,8,4,1,3,2,2,1,4,1,11,1,5,2,1,5,2,5,8,6,1,1,7,
+ 4,3,8,3,2,7,2,1,5,1,5,2,4,7,6,2,8,5,1,11,4,5,3,6,18,1,2,13,3,3,1,21,1,1,4,1,4,1,1,1,8,1,2,2,7,1,2,4,2,2,9,2,1,1,1,4,3,6,3,12,5,1,1,1,5,6,3,2,
+ 4,8,2,2,4,2,7,1,8,9,5,2,3,2,1,3,2,13,7,14,6,5,1,1,2,1,4,2,23,2,1,1,6,3,1,4,1,15,3,1,7,3,9,14,1,3,1,4,1,1,5,8,1,3,8,3,8,15,11,4,14,4,4,2,5,5,
+ 1,7,1,6,14,7,7,8,5,15,4,8,6,5,6,2,1,13,1,20,15,11,9,2,5,6,2,11,2,6,2,5,1,5,8,4,13,19,25,4,1,1,11,1,34,2,5,9,14,6,2,2,6,1,1,14,1,3,14,13,1,6,
+ 12,21,14,14,6,32,17,8,32,9,28,1,2,4,11,8,3,1,14,2,5,15,1,1,1,1,3,6,4,1,3,4,11,3,1,1,11,30,1,5,1,4,1,5,8,1,1,3,2,4,3,17,35,2,6,12,17,3,1,6,2,
+ 1,1,12,2,7,3,3,2,1,16,2,8,3,6,5,4,7,3,3,8,1,9,8,5,1,2,1,3,2,8,1,2,9,12,1,1,2,3,8,3,24,12,4,3,7,5,8,3,3,3,3,3,3,1,23,10,3,1,2,2,6,3,1,16,1,16,
+ 22,3,10,4,11,6,9,7,7,3,6,2,2,2,4,10,2,1,1,2,8,7,1,6,4,1,3,3,3,5,10,12,12,2,3,12,8,15,1,1,16,6,6,1,5,9,11,4,11,4,2,6,12,1,17,5,13,1,4,9,5,1,11,
+ 2,1,8,1,5,7,28,8,3,5,10,2,17,3,38,22,1,2,18,12,10,4,38,18,1,4,44,19,4,1,8,4,1,12,1,4,31,12,1,14,7,75,7,5,10,6,6,13,3,2,11,11,3,2,5,28,15,6,18,
+ 18,5,6,4,3,16,1,7,18,7,36,3,5,3,1,7,1,9,1,10,7,2,4,2,6,2,9,7,4,3,32,12,3,7,10,2,23,16,3,1,12,3,31,4,11,1,3,8,9,5,1,30,15,6,12,3,2,2,11,19,9,
+ 14,2,6,2,3,19,13,17,5,3,3,25,3,14,1,1,1,36,1,3,2,19,3,13,36,9,13,31,6,4,16,34,2,5,4,2,3,3,5,1,1,1,4,3,1,17,3,2,3,5,3,1,3,2,3,5,6,3,12,11,1,3,
+ 1,2,26,7,12,7,2,14,3,3,7,7,11,25,25,28,16,4,36,1,2,1,6,2,1,9,3,27,17,4,3,4,13,4,1,3,2,2,1,10,4,2,4,6,3,8,2,1,18,1,1,24,2,2,4,33,2,3,63,7,1,6,
+ 40,7,3,4,4,2,4,15,18,1,16,1,1,11,2,41,14,1,3,18,13,3,2,4,16,2,17,7,15,24,7,18,13,44,2,2,3,6,1,1,7,5,1,7,1,4,3,3,5,10,8,2,3,1,8,1,1,27,4,2,1,
+ 12,1,2,1,10,6,1,6,7,5,2,3,7,11,5,11,3,6,6,2,3,15,4,9,1,1,2,1,2,11,2,8,12,8,5,4,2,3,1,5,2,2,1,14,1,12,11,4,1,11,17,17,4,3,2,5,5,7,3,1,5,9,9,8,
+ 2,5,6,6,13,13,2,1,2,6,1,2,2,49,4,9,1,2,10,16,7,8,4,3,2,23,4,58,3,29,1,14,19,19,11,11,2,7,5,1,3,4,6,2,18,5,12,12,17,17,3,3,2,4,1,6,2,3,4,3,1,
+ 1,1,1,5,1,1,9,1,3,1,3,6,1,8,1,1,2,6,4,14,3,1,4,11,4,1,3,32,1,2,4,13,4,1,2,4,2,1,3,1,11,1,4,2,1,4,4,6,3,5,1,6,5,7,6,3,23,3,5,3,5,3,3,13,3,9,10,
+ 1,12,10,2,3,18,13,7,160,52,4,2,2,3,2,14,5,4,12,4,6,4,1,20,4,11,6,2,12,27,1,4,1,2,2,7,4,5,2,28,3,7,25,8,3,19,3,6,10,2,2,1,10,2,5,4,1,3,4,1,5,
+ 3,2,6,9,3,6,2,16,3,3,16,4,5,5,3,2,1,2,16,15,8,2,6,21,2,4,1,22,5,8,1,1,21,11,2,1,11,11,19,13,12,4,2,3,2,3,6,1,8,11,1,4,2,9,5,2,1,11,2,9,1,1,2,
+ 14,31,9,3,4,21,14,4,8,1,7,2,2,2,5,1,4,20,3,3,4,10,1,11,9,8,2,1,4,5,14,12,14,2,17,9,6,31,4,14,1,20,13,26,5,2,7,3,6,13,2,4,2,19,6,2,2,18,9,3,5,
+ 12,12,14,4,6,2,3,6,9,5,22,4,5,25,6,4,8,5,2,6,27,2,35,2,16,3,7,8,8,6,6,5,9,17,2,20,6,19,2,13,3,1,1,1,4,17,12,2,14,7,1,4,18,12,38,33,2,10,1,1,
+ 2,13,14,17,11,50,6,33,20,26,74,16,23,45,50,13,38,33,6,6,7,4,4,2,1,3,2,5,8,7,8,9,3,11,21,9,13,1,3,10,6,7,1,2,2,18,5,5,1,9,9,2,68,9,19,13,2,5,
+ 1,4,4,7,4,13,3,9,10,21,17,3,26,2,1,5,2,4,5,4,1,7,4,7,3,4,2,1,6,1,1,20,4,1,9,2,2,1,3,3,2,3,2,1,1,1,20,2,3,1,6,2,3,6,2,4,8,1,3,2,10,3,5,3,4,4,
+ 3,4,16,1,6,1,10,2,4,2,1,1,2,10,11,2,2,3,1,24,31,4,10,10,2,5,12,16,164,15,4,16,7,9,15,19,17,1,2,1,1,5,1,1,1,1,1,3,1,4,3,1,3,1,3,1,2,1,1,3,3,7,
+ 2,8,1,2,2,2,1,3,4,3,7,8,12,92,2,10,3,1,3,14,5,25,16,42,4,7,7,4,2,21,5,27,26,27,21,25,30,31,2,1,5,13,3,22,5,6,6,11,9,12,1,5,9,7,5,5,22,60,3,5,
+ 13,1,1,8,1,1,3,3,2,1,9,3,3,18,4,1,2,3,7,6,3,1,2,3,9,1,3,1,3,2,1,3,1,1,1,2,1,11,3,1,6,9,1,3,2,3,1,2,1,5,1,1,4,3,4,1,2,2,4,4,1,7,2,1,2,2,3,5,13,
+ 18,3,4,14,9,9,4,16,3,7,5,8,2,6,48,28,3,1,1,4,2,14,8,2,9,2,1,15,2,4,3,2,10,16,12,8,7,1,1,3,1,1,1,2,7,4,1,6,4,38,39,16,23,7,15,15,3,2,12,7,21,
+ 37,27,6,5,4,8,2,10,8,8,6,5,1,2,1,3,24,1,16,17,9,23,10,17,6,1,51,55,44,13,294,9,3,6,2,4,2,2,15,1,1,1,13,21,17,68,14,8,9,4,1,4,9,3,11,7,1,1,1,
+ 5,6,3,2,1,1,1,2,3,8,1,2,2,4,1,5,5,2,1,4,3,7,13,4,1,4,1,3,1,1,1,5,5,10,1,6,1,5,2,1,5,2,4,1,4,5,7,3,18,2,9,11,32,4,3,3,2,4,7,11,16,9,11,8,13,38,
+ 32,8,4,2,1,1,2,1,2,4,4,1,1,1,4,1,21,3,11,1,16,1,1,6,1,3,2,4,9,8,57,7,44,1,3,3,13,3,10,1,1,7,5,2,7,21,47,63,3,15,4,7,1,16,1,1,2,8,2,3,42,15,4,
+ 1,29,7,22,10,3,78,16,12,20,18,4,67,11,5,1,3,15,6,21,31,32,27,18,13,71,35,5,142,4,10,1,2,50,19,33,16,35,37,16,19,27,7,1,133,19,1,4,8,7,20,1,4,
+ 4,1,10,3,1,6,1,2,51,5,40,15,24,43,22928,11,1,13,154,70,3,1,1,7,4,10,1,2,1,1,2,1,2,1,2,2,1,1,2,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,
+ 3,2,1,1,1,1,2,1,1,
};
static ImWchar base_ranges[] = // not zero-terminated
{
@@ -2459,8 +2842,7 @@ void ImFontGlyphRangesBuilder::AddText(const char* text, const char* text_end)
text += c_len;
if (c_len == 0)
break;
- if (c < 0x10000)
- AddChar((ImWchar)c);
+ AddChar((ImWchar)c);
}
}
@@ -2473,12 +2855,12 @@ void ImFontGlyphRangesBuilder::AddRanges(const ImWchar* ranges)
void ImFontGlyphRangesBuilder::BuildRanges(ImVector* out_ranges)
{
- int max_codepoint = 0x10000;
- for (int n = 0; n < max_codepoint; n++)
+ const int max_codepoint = IM_UNICODE_CODEPOINT_MAX;
+ for (int n = 0; n <= max_codepoint; n++)
if (GetBit(n))
{
out_ranges->push_back((ImWchar)n);
- while (n < max_codepoint - 1 && GetBit(n + 1))
+ while (n < max_codepoint && GetBit(n + 1))
n++;
out_ranges->push_back((ImWchar)n);
}
@@ -2495,7 +2877,6 @@ ImFont::ImFont()
FallbackAdvanceX = 0.0f;
FallbackChar = (ImWchar)'?';
EllipsisChar = (ImWchar)-1;
- DisplayOffset = ImVec2(0.0f, 0.0f);
FallbackGlyph = NULL;
ContainerAtlas = NULL;
ConfigData = NULL;
@@ -2504,6 +2885,7 @@ ImFont::ImFont()
Scale = 1.0f;
Ascent = Descent = 0.0f;
MetricsTotalSurface = 0;
+ memset(Used4kPagesMap, 0, sizeof(Used4kPagesMap));
}
ImFont::~ImFont()
@@ -2531,32 +2913,43 @@ void ImFont::BuildLookupTable()
for (int i = 0; i != Glyphs.Size; i++)
max_codepoint = ImMax(max_codepoint, (int)Glyphs[i].Codepoint);
+ // Build lookup table
IM_ASSERT(Glyphs.Size < 0xFFFF); // -1 is reserved
IndexAdvanceX.clear();
IndexLookup.clear();
DirtyLookupTables = false;
+ memset(Used4kPagesMap, 0, sizeof(Used4kPagesMap));
GrowIndex(max_codepoint + 1);
for (int i = 0; i < Glyphs.Size; i++)
{
int codepoint = (int)Glyphs[i].Codepoint;
IndexAdvanceX[codepoint] = Glyphs[i].AdvanceX;
IndexLookup[codepoint] = (ImWchar)i;
+
+ // Mark 4K page as used
+ const int page_n = codepoint / 4096;
+ Used4kPagesMap[page_n >> 3] |= 1 << (page_n & 7);
}
// Create a glyph to handle TAB
// FIXME: Needs proper TAB handling but it needs to be contextualized (or we could arbitrary say that each string starts at "column 0" ?)
if (FindGlyph((ImWchar)' '))
{
- if (Glyphs.back().Codepoint != '\t') // So we can call this function multiple times
+ if (Glyphs.back().Codepoint != '\t') // So we can call this function multiple times (FIXME: Flaky)
Glyphs.resize(Glyphs.Size + 1);
ImFontGlyph& tab_glyph = Glyphs.back();
tab_glyph = *FindGlyph((ImWchar)' ');
tab_glyph.Codepoint = '\t';
tab_glyph.AdvanceX *= IM_TABSIZE;
IndexAdvanceX[(int)tab_glyph.Codepoint] = (float)tab_glyph.AdvanceX;
- IndexLookup[(int)tab_glyph.Codepoint] = (ImWchar)(Glyphs.Size-1);
+ IndexLookup[(int)tab_glyph.Codepoint] = (ImWchar)(Glyphs.Size - 1);
}
+ // Mark special glyphs as not visible (note that AddGlyph already mark as non-visible glyphs with zero-size polygons)
+ SetGlyphVisible((ImWchar)' ', false);
+ SetGlyphVisible((ImWchar)'\t', false);
+
+ // Setup fall-backs
FallbackGlyph = FindGlyphNoFallback(FallbackChar);
FallbackAdvanceX = FallbackGlyph ? FallbackGlyph->AdvanceX : 0.0f;
for (int i = 0; i < max_codepoint + 1; i++)
@@ -2564,6 +2957,25 @@ void ImFont::BuildLookupTable()
IndexAdvanceX[i] = FallbackAdvanceX;
}
+// API is designed this way to avoid exposing the 4K page size
+// e.g. use with IsGlyphRangeUnused(0, 255)
+bool ImFont::IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last)
+{
+ unsigned int page_begin = (c_begin / 4096);
+ unsigned int page_last = (c_last / 4096);
+ for (unsigned int page_n = page_begin; page_n <= page_last; page_n++)
+ if ((page_n >> 3) < sizeof(Used4kPagesMap))
+ if (Used4kPagesMap[page_n >> 3] & (1 << (page_n & 7)))
+ return false;
+ return true;
+}
+
+void ImFont::SetGlyphVisible(ImWchar c, bool visible)
+{
+ if (ImFontGlyph* glyph = (ImFontGlyph*)(void*)FindGlyph((ImWchar)c))
+ glyph->Visible = visible ? 1 : 0;
+}
+
void ImFont::SetFallbackChar(ImWchar c)
{
FallbackChar = c;
@@ -2581,11 +2993,33 @@ void ImFont::GrowIndex(int new_size)
// x0/y0/x1/y1 are offset from the character upper-left layout position, in pixels. Therefore x0/y0 are often fairly close to zero.
// Not to be mistaken with texture coordinates, which are held by u0/v0/u1/v1 in normalized format (0.0..1.0 on each texture axis).
-void ImFont::AddGlyph(ImWchar codepoint, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x)
+// 'cfg' is not necessarily == 'this->ConfigData' because multiple source fonts+configs can be used to build one target font.
+void ImFont::AddGlyph(const ImFontConfig* cfg, ImWchar codepoint, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x)
{
+ if (cfg != NULL)
+ {
+ // Clamp & recenter if needed
+ const float advance_x_original = advance_x;
+ advance_x = ImClamp(advance_x, cfg->GlyphMinAdvanceX, cfg->GlyphMaxAdvanceX);
+ if (advance_x != advance_x_original)
+ {
+ float char_off_x = cfg->PixelSnapH ? ImFloor((advance_x - advance_x_original) * 0.5f) : (advance_x - advance_x_original) * 0.5f;
+ x0 += char_off_x;
+ x1 += char_off_x;
+ }
+
+ // Snap to pixel
+ if (cfg->PixelSnapH)
+ advance_x = IM_ROUND(advance_x);
+
+ // Bake spacing
+ advance_x += cfg->GlyphExtraSpacing.x;
+ }
+
Glyphs.resize(Glyphs.Size + 1);
ImFontGlyph& glyph = Glyphs.back();
- glyph.Codepoint = (ImWchar)codepoint;
+ glyph.Codepoint = (unsigned int)codepoint;
+ glyph.Visible = (x0 != x1) && (y0 != y1);
glyph.X0 = x0;
glyph.Y0 = y0;
glyph.X1 = x1;
@@ -2594,20 +3028,19 @@ void ImFont::AddGlyph(ImWchar codepoint, float x0, float y0, float x1, float y1,
glyph.V0 = v0;
glyph.U1 = u1;
glyph.V1 = v1;
- glyph.AdvanceX = advance_x + ConfigData->GlyphExtraSpacing.x; // Bake spacing into AdvanceX
-
- if (ConfigData->PixelSnapH)
- glyph.AdvanceX = IM_FLOOR(glyph.AdvanceX + 0.5f);
+ glyph.AdvanceX = advance_x;
// Compute rough surface usage metrics (+1 to account for average padding, +0.99 to round)
+ // We use (U1-U0)*TexWidth instead of X1-X0 to account for oversampling.
+ float pad = ContainerAtlas->TexGlyphPadding + 0.99f;
DirtyLookupTables = true;
- MetricsTotalSurface += (int)((glyph.U1 - glyph.U0) * ContainerAtlas->TexWidth + 1.99f) * (int)((glyph.V1 - glyph.V0) * ContainerAtlas->TexHeight + 1.99f);
+ MetricsTotalSurface += (int)((glyph.U1 - glyph.U0) * ContainerAtlas->TexWidth + pad) * (int)((glyph.V1 - glyph.V0) * ContainerAtlas->TexHeight + pad);
}
void ImFont::AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst)
{
IM_ASSERT(IndexLookup.Size > 0); // Currently this can only be called AFTER the font has been built, aka after calling ImFontAtlas::GetTexDataAs*() function.
- int index_size = IndexLookup.Size;
+ unsigned int index_size = (unsigned int)IndexLookup.Size;
if (dst < index_size && IndexLookup.Data[dst] == (ImWchar)-1 && !overwrite_dst) // 'dst' already exists
return;
@@ -2621,7 +3054,7 @@ void ImFont::AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst)
const ImFontGlyph* ImFont::FindGlyph(ImWchar c) const
{
- if (c >= IndexLookup.Size)
+ if (c >= (size_t)IndexLookup.Size)
return FallbackGlyph;
const ImWchar i = IndexLookup.Data[c];
if (i == (ImWchar)-1)
@@ -2631,7 +3064,7 @@ const ImFontGlyph* ImFont::FindGlyph(ImWchar c) const
const ImFontGlyph* ImFont::FindGlyphNoFallback(ImWchar c) const
{
- if (c >= IndexLookup.Size)
+ if (c >= (size_t)IndexLookup.Size)
return NULL;
const ImWchar i = IndexLookup.Data[c];
if (i == (ImWchar)-1)
@@ -2720,7 +3153,7 @@ const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const c
}
// Allow wrapping after punctuation.
- inside_word = !(c == '.' || c == ',' || c == ';' || c == '!' || c == '?' || c == '\"');
+ inside_word = (c != '.' && c != ',' && c != ';' && c != '!' && c != '?' && c != '\"');
}
// We ignore blank width at the end of the line (they can be skipped)
@@ -2746,7 +3179,7 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons
const float line_height = size;
const float scale = size / FontSize;
- ImVec2 text_size = ImVec2(0,0);
+ ImVec2 text_size = ImVec2(0, 0);
float line_width = 0.0f;
const bool word_wrap_enabled = (wrap_width > 0.0f);
@@ -2834,16 +3267,14 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons
void ImFont::RenderChar(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, ImWchar c) const
{
- if (c == ' ' || c == '\t' || c == '\n' || c == '\r') // Match behavior of RenderText(), those 4 codepoints are hard-coded.
+ const ImFontGlyph* glyph = FindGlyph(c);
+ if (!glyph || !glyph->Visible)
return;
- if (const ImFontGlyph* glyph = FindGlyph(c))
- {
- float scale = (size >= 0.0f) ? (size / FontSize) : 1.0f;
- pos.x = IM_FLOOR(pos.x + DisplayOffset.x);
- pos.y = IM_FLOOR(pos.y + DisplayOffset.y);
- draw_list->PrimReserve(6, 4);
- draw_list->PrimRectUV(ImVec2(pos.x + glyph->X0 * scale, pos.y + glyph->Y0 * scale), ImVec2(pos.x + glyph->X1 * scale, pos.y + glyph->Y1 * scale), ImVec2(glyph->U0, glyph->V0), ImVec2(glyph->U1, glyph->V1), col);
- }
+ float scale = (size >= 0.0f) ? (size / FontSize) : 1.0f;
+ pos.x = IM_FLOOR(pos.x);
+ pos.y = IM_FLOOR(pos.y);
+ draw_list->PrimReserve(6, 4);
+ draw_list->PrimRectUV(ImVec2(pos.x + glyph->X0 * scale, pos.y + glyph->Y0 * scale), ImVec2(pos.x + glyph->X1 * scale, pos.y + glyph->Y1 * scale), ImVec2(glyph->U0, glyph->V0), ImVec2(glyph->U1, glyph->V1), col);
}
void ImFont::RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width, bool cpu_fine_clip) const
@@ -2852,8 +3283,8 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col
text_end = text_begin + strlen(text_begin); // ImGui:: functions generally already provides a valid text_end, so this is merely to handle direct calls.
// Align to be pixel perfect
- pos.x = IM_FLOOR(pos.x + DisplayOffset.x);
- pos.y = IM_FLOOR(pos.y + DisplayOffset.y);
+ pos.x = IM_FLOOR(pos.x);
+ pos.y = IM_FLOOR(pos.y);
float x = pos.x;
float y = pos.y;
if (y > clip_rect.w)
@@ -2956,95 +3387,148 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col
continue;
}
- float char_width = 0.0f;
- if (const ImFontGlyph* glyph = FindGlyph((ImWchar)c))
+ const ImFontGlyph* glyph = FindGlyph((ImWchar)c);
+ if (glyph == NULL)
+ continue;
+
+ float char_width = glyph->AdvanceX * scale;
+ if (glyph->Visible)
{
- char_width = glyph->AdvanceX * scale;
-
- // Arbitrarily assume that both space and tabs are empty glyphs as an optimization
- if (c != ' ' && c != '\t')
+ // We don't do a second finer clipping test on the Y axis as we've already skipped anything before clip_rect.y and exit once we pass clip_rect.w
+ float x1 = x + glyph->X0 * scale;
+ float x2 = x + glyph->X1 * scale;
+ float y1 = y + glyph->Y0 * scale;
+ float y2 = y + glyph->Y1 * scale;
+ if (x1 <= clip_rect.z && x2 >= clip_rect.x)
{
- // We don't do a second finer clipping test on the Y axis as we've already skipped anything before clip_rect.y and exit once we pass clip_rect.w
- float x1 = x + glyph->X0 * scale;
- float x2 = x + glyph->X1 * scale;
- float y1 = y + glyph->Y0 * scale;
- float y2 = y + glyph->Y1 * scale;
- if (x1 <= clip_rect.z && x2 >= clip_rect.x)
+ // Render a character
+ float u1 = glyph->U0;
+ float v1 = glyph->V0;
+ float u2 = glyph->U1;
+ float v2 = glyph->V1;
+
+ // CPU side clipping used to fit text in their frame when the frame is too small. Only does clipping for axis aligned quads.
+ if (cpu_fine_clip)
{
- // Render a character
- float u1 = glyph->U0;
- float v1 = glyph->V0;
- float u2 = glyph->U1;
- float v2 = glyph->V1;
-
- // CPU side clipping used to fit text in their frame when the frame is too small. Only does clipping for axis aligned quads.
- if (cpu_fine_clip)
+ if (x1 < clip_rect.x)
{
- if (x1 < clip_rect.x)
- {
- u1 = u1 + (1.0f - (x2 - clip_rect.x) / (x2 - x1)) * (u2 - u1);
- x1 = clip_rect.x;
- }
- if (y1 < clip_rect.y)
- {
- v1 = v1 + (1.0f - (y2 - clip_rect.y) / (y2 - y1)) * (v2 - v1);
- y1 = clip_rect.y;
- }
- if (x2 > clip_rect.z)
- {
- u2 = u1 + ((clip_rect.z - x1) / (x2 - x1)) * (u2 - u1);
- x2 = clip_rect.z;
- }
- if (y2 > clip_rect.w)
- {
- v2 = v1 + ((clip_rect.w - y1) / (y2 - y1)) * (v2 - v1);
- y2 = clip_rect.w;
- }
- if (y1 >= y2)
- {
- x += char_width;
- continue;
- }
+ u1 = u1 + (1.0f - (x2 - clip_rect.x) / (x2 - x1)) * (u2 - u1);
+ x1 = clip_rect.x;
}
-
- // We are NOT calling PrimRectUV() here because non-inlined causes too much overhead in a debug builds. Inlined here:
+ if (y1 < clip_rect.y)
{
- idx_write[0] = (ImDrawIdx)(vtx_current_idx); idx_write[1] = (ImDrawIdx)(vtx_current_idx+1); idx_write[2] = (ImDrawIdx)(vtx_current_idx+2);
- idx_write[3] = (ImDrawIdx)(vtx_current_idx); idx_write[4] = (ImDrawIdx)(vtx_current_idx+2); idx_write[5] = (ImDrawIdx)(vtx_current_idx+3);
- vtx_write[0].pos.x = x1; vtx_write[0].pos.y = y1; vtx_write[0].col = col; vtx_write[0].uv.x = u1; vtx_write[0].uv.y = v1;
- vtx_write[1].pos.x = x2; vtx_write[1].pos.y = y1; vtx_write[1].col = col; vtx_write[1].uv.x = u2; vtx_write[1].uv.y = v1;
- vtx_write[2].pos.x = x2; vtx_write[2].pos.y = y2; vtx_write[2].col = col; vtx_write[2].uv.x = u2; vtx_write[2].uv.y = v2;
- vtx_write[3].pos.x = x1; vtx_write[3].pos.y = y2; vtx_write[3].col = col; vtx_write[3].uv.x = u1; vtx_write[3].uv.y = v2;
- vtx_write += 4;
- vtx_current_idx += 4;
- idx_write += 6;
+ v1 = v1 + (1.0f - (y2 - clip_rect.y) / (y2 - y1)) * (v2 - v1);
+ y1 = clip_rect.y;
}
+ if (x2 > clip_rect.z)
+ {
+ u2 = u1 + ((clip_rect.z - x1) / (x2 - x1)) * (u2 - u1);
+ x2 = clip_rect.z;
+ }
+ if (y2 > clip_rect.w)
+ {
+ v2 = v1 + ((clip_rect.w - y1) / (y2 - y1)) * (v2 - v1);
+ y2 = clip_rect.w;
+ }
+ if (y1 >= y2)
+ {
+ x += char_width;
+ continue;
+ }
+ }
+
+ // We are NOT calling PrimRectUV() here because non-inlined causes too much overhead in a debug builds. Inlined here:
+ {
+ idx_write[0] = (ImDrawIdx)(vtx_current_idx); idx_write[1] = (ImDrawIdx)(vtx_current_idx+1); idx_write[2] = (ImDrawIdx)(vtx_current_idx+2);
+ idx_write[3] = (ImDrawIdx)(vtx_current_idx); idx_write[4] = (ImDrawIdx)(vtx_current_idx+2); idx_write[5] = (ImDrawIdx)(vtx_current_idx+3);
+ vtx_write[0].pos.x = x1; vtx_write[0].pos.y = y1; vtx_write[0].col = col; vtx_write[0].uv.x = u1; vtx_write[0].uv.y = v1;
+ vtx_write[1].pos.x = x2; vtx_write[1].pos.y = y1; vtx_write[1].col = col; vtx_write[1].uv.x = u2; vtx_write[1].uv.y = v1;
+ vtx_write[2].pos.x = x2; vtx_write[2].pos.y = y2; vtx_write[2].col = col; vtx_write[2].uv.x = u2; vtx_write[2].uv.y = v2;
+ vtx_write[3].pos.x = x1; vtx_write[3].pos.y = y2; vtx_write[3].col = col; vtx_write[3].uv.x = u1; vtx_write[3].uv.y = v2;
+ vtx_write += 4;
+ vtx_current_idx += 4;
+ idx_write += 6;
}
}
}
-
x += char_width;
}
- // Give back unused vertices
- draw_list->VtxBuffer.resize((int)(vtx_write - draw_list->VtxBuffer.Data));
- draw_list->IdxBuffer.resize((int)(idx_write - draw_list->IdxBuffer.Data));
- draw_list->CmdBuffer[draw_list->CmdBuffer.Size-1].ElemCount -= (idx_expected_size - draw_list->IdxBuffer.Size);
+ // Give back unused vertices (clipped ones, blanks) ~ this is essentially a PrimUnreserve() action.
+ draw_list->VtxBuffer.Size = (int)(vtx_write - draw_list->VtxBuffer.Data); // Same as calling shrink()
+ draw_list->IdxBuffer.Size = (int)(idx_write - draw_list->IdxBuffer.Data);
+ draw_list->CmdBuffer[draw_list->CmdBuffer.Size - 1].ElemCount -= (idx_expected_size - draw_list->IdxBuffer.Size);
draw_list->_VtxWritePtr = vtx_write;
draw_list->_IdxWritePtr = idx_write;
draw_list->_VtxCurrentIdx = vtx_current_idx;
}
//-----------------------------------------------------------------------------
-// [SECTION] Internal Render Helpers
-// (progressively moved from imgui.cpp to here when they are redesigned to stop accessing ImGui global state)
+// [SECTION] ImGui Internal Render Helpers
//-----------------------------------------------------------------------------
+// Vaguely redesigned to stop accessing ImGui global state:
+// - RenderArrow()
+// - RenderBullet()
+// - RenderCheckMark()
// - RenderMouseCursor()
-// - RenderArrowDockMenu()
// - RenderArrowPointingAt()
// - RenderRectFilledRangeH()
-// - RenderRectFilledWithHole()
//-----------------------------------------------------------------------------
+// Function in need of a redesign (legacy mess)
+// - RenderColorRectWithAlphaCheckerboard()
+//-----------------------------------------------------------------------------
+
+// Render an arrow aimed to be aligned with text (p_min is a position in the same space text would be positioned). To e.g. denote expanded/collapsed state
+void ImGui::RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImU32 col, ImGuiDir dir, float scale)
+{
+ const float h = draw_list->_Data->FontSize * 1.00f;
+ float r = h * 0.40f * scale;
+ ImVec2 center = pos + ImVec2(h * 0.50f, h * 0.50f * scale);
+
+ ImVec2 a, b, c;
+ switch (dir)
+ {
+ case ImGuiDir_Up:
+ case ImGuiDir_Down:
+ if (dir == ImGuiDir_Up) r = -r;
+ a = ImVec2(+0.000f, +0.750f) * r;
+ b = ImVec2(-0.866f, -0.750f) * r;
+ c = ImVec2(+0.866f, -0.750f) * r;
+ break;
+ case ImGuiDir_Left:
+ case ImGuiDir_Right:
+ if (dir == ImGuiDir_Left) r = -r;
+ a = ImVec2(+0.750f, +0.000f) * r;
+ b = ImVec2(-0.750f, +0.866f) * r;
+ c = ImVec2(-0.750f, -0.866f) * r;
+ break;
+ case ImGuiDir_None:
+ case ImGuiDir_COUNT:
+ IM_ASSERT(0);
+ break;
+ }
+ draw_list->AddTriangleFilled(center + a, center + b, center + c, col);
+}
+
+void ImGui::RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col)
+{
+ draw_list->AddCircleFilled(pos, draw_list->_Data->FontSize * 0.20f, col, 8);
+}
+
+void ImGui::RenderCheckMark(ImDrawList* draw_list, ImVec2 pos, ImU32 col, float sz)
+{
+ float thickness = ImMax(sz / 5.0f, 1.0f);
+ sz -= thickness * 0.5f;
+ pos += ImVec2(thickness * 0.25f, thickness * 0.25f);
+
+ float third = sz / 3.0f;
+ float bx = pos.x + third;
+ float by = pos.y + sz - third * 0.5f;
+ draw_list->PathLineTo(ImVec2(bx - third, by - third));
+ draw_list->PathLineTo(ImVec2(bx, by));
+ draw_list->PathLineTo(ImVec2(bx + third * 2.0f, by - third * 2.0f));
+ draw_list->PathStroke(col, false, thickness);
+}
void ImGui::RenderMouseCursor(ImDrawList* draw_list, ImVec2 pos, float scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
{
@@ -3059,10 +3543,10 @@ void ImGui::RenderMouseCursor(ImDrawList* draw_list, ImVec2 pos, float scale, Im
pos -= offset;
const ImTextureID tex_id = font_atlas->TexID;
draw_list->PushTextureID(tex_id);
- draw_list->AddImage(tex_id, pos + ImVec2(1, 0)*scale, pos + ImVec2(1, 0)*scale + size*scale, uv[2], uv[3], col_shadow);
- draw_list->AddImage(tex_id, pos + ImVec2(2, 0)*scale, pos + ImVec2(2, 0)*scale + size*scale, uv[2], uv[3], col_shadow);
- draw_list->AddImage(tex_id, pos, pos + size*scale, uv[2], uv[3], col_border);
- draw_list->AddImage(tex_id, pos, pos + size*scale, uv[0], uv[1], col_fill);
+ draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow);
+ draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow);
+ draw_list->AddImage(tex_id, pos, pos + size * scale, uv[2], uv[3], col_border);
+ draw_list->AddImage(tex_id, pos, pos + size * scale, uv[0], uv[1], col_fill);
draw_list->PopTextureID();
}
}
@@ -3080,14 +3564,6 @@ void ImGui::RenderArrowPointingAt(ImDrawList* draw_list, ImVec2 pos, ImVec2 half
}
}
-// This is less wide than RenderArrow() and we use in dock nodes instead of the regular RenderArrow() to denote a change of functionality,
-// and because the saved space means that the left-most tab label can stay at exactly the same position as the label of a loose window.
-void ImGui::RenderArrowDockMenu(ImDrawList* draw_list, ImVec2 p_min, float sz, ImU32 col)
-{
- draw_list->AddRectFilled(p_min + ImVec2(sz * 0.10f, sz * 0.15f), p_min + ImVec2(sz * 0.70f, sz * 0.30f), col);
- RenderArrowPointingAt(draw_list, p_min + ImVec2(sz * 0.40f, sz * 0.85f), ImVec2(sz * 0.30f, sz * 0.40f), ImGuiDir_Down, col);
-}
-
static inline float ImAcos01(float x)
{
if (x <= 0.0f) return IM_PI * 0.5f;
@@ -3157,8 +3633,6 @@ void ImGui::RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, Im
draw_list->PathFillConvex(col);
}
-// For CTRL+TAB within a docking node we need to render the dimming background in 8 steps
-// (Because the root node renders the background in one shot, in order to avoid flickering when a child dock node is not submitted)
void ImGui::RenderRectFilledWithHole(ImDrawList* draw_list, ImRect outer, ImRect inner, ImU32 col, float rounding)
{
const bool fill_L = (inner.Min.x > outer.Min.x);
@@ -3175,6 +3649,43 @@ void ImGui::RenderRectFilledWithHole(ImDrawList* draw_list, ImRect outer, ImRect
if (fill_R && fill_D) draw_list->AddRectFilled(ImVec2(inner.Max.x, inner.Max.y), ImVec2(outer.Max.x, outer.Max.y), col, rounding, ImDrawCornerFlags_BotRight);
}
+// Helper for ColorPicker4()
+// NB: This is rather brittle and will show artifact when rounding this enabled if rounded corners overlap multiple cells. Caller currently responsible for avoiding that.
+// Spent a non reasonable amount of time trying to getting this right for ColorButton with rounding+anti-aliasing+ImGuiColorEditFlags_HalfAlphaPreview flag + various grid sizes and offsets, and eventually gave up... probably more reasonable to disable rounding altogether.
+// FIXME: uses ImGui::GetColorU32
+void ImGui::RenderColorRectWithAlphaCheckerboard(ImDrawList* draw_list, ImVec2 p_min, ImVec2 p_max, ImU32 col, float grid_step, ImVec2 grid_off, float rounding, int rounding_corners_flags)
+{
+ if (((col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT) < 0xFF)
+ {
+ ImU32 col_bg1 = ImGui::GetColorU32(ImAlphaBlendColors(IM_COL32(204, 204, 204, 255), col));
+ ImU32 col_bg2 = ImGui::GetColorU32(ImAlphaBlendColors(IM_COL32(128, 128, 128, 255), col));
+ draw_list->AddRectFilled(p_min, p_max, col_bg1, rounding, rounding_corners_flags);
+
+ int yi = 0;
+ for (float y = p_min.y + grid_off.y; y < p_max.y; y += grid_step, yi++)
+ {
+ float y1 = ImClamp(y, p_min.y, p_max.y), y2 = ImMin(y + grid_step, p_max.y);
+ if (y2 <= y1)
+ continue;
+ for (float x = p_min.x + grid_off.x + (yi & 1) * grid_step; x < p_max.x; x += grid_step * 2.0f)
+ {
+ float x1 = ImClamp(x, p_min.x, p_max.x), x2 = ImMin(x + grid_step, p_max.x);
+ if (x2 <= x1)
+ continue;
+ int rounding_corners_flags_cell = 0;
+ if (y1 <= p_min.y) { if (x1 <= p_min.x) rounding_corners_flags_cell |= ImDrawCornerFlags_TopLeft; if (x2 >= p_max.x) rounding_corners_flags_cell |= ImDrawCornerFlags_TopRight; }
+ if (y2 >= p_max.y) { if (x1 <= p_min.x) rounding_corners_flags_cell |= ImDrawCornerFlags_BotLeft; if (x2 >= p_max.x) rounding_corners_flags_cell |= ImDrawCornerFlags_BotRight; }
+ rounding_corners_flags_cell &= rounding_corners_flags;
+ draw_list->AddRectFilled(ImVec2(x1, y1), ImVec2(x2, y2), col_bg2, rounding_corners_flags_cell ? rounding : 0.0f, rounding_corners_flags_cell);
+ }
+ }
+ }
+ else
+ {
+ draw_list->AddRectFilled(p_min, p_max, col, rounding, rounding_corners_flags);
+ }
+}
+
//-----------------------------------------------------------------------------
// [SECTION] Decompression code
//-----------------------------------------------------------------------------
@@ -3235,9 +3746,9 @@ static unsigned int stb_adler32(unsigned int adler32, unsigned char *buffer, uns
{
const unsigned long ADLER_MOD = 65521;
unsigned long s1 = adler32 & 0xffff, s2 = adler32 >> 16;
- unsigned long blocklen, i;
+ unsigned long blocklen = buflen % 5552;
- blocklen = buflen % 5552;
+ unsigned long i;
while (buflen) {
for (i=0; i + 7 < blocklen; i += 8) {
s1 += buffer[0], s2 += s1;
@@ -3264,10 +3775,9 @@ static unsigned int stb_adler32(unsigned int adler32, unsigned char *buffer, uns
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);
+ const unsigned int olen = stb_decompress_length(i);
stb__barrier_in_b = i;
stb__barrier_out_e = output + olen;
stb__barrier_out_b = output;
@@ -3307,7 +3817,7 @@ static unsigned int stb_decompress(unsigned char *output, const unsigned char *i
// Exported using misc/fonts/binary_to_compressed_c.cpp (with compression + base85 string encoding).
// The purpose of encoding as base85 instead of "0x00,0x01,..." style is only save on _source code_ size.
//-----------------------------------------------------------------------------
-static const char proggy_clean_ttf_compressed_data_base85[11980+1] =
+static const char proggy_clean_ttf_compressed_data_base85[11980 + 1] =
"7])#######hV0qs'/###[),##/l:$#Q6>##5[n42>c-TH`->>#/e>11NNV=Bv(*:.F?uu#(gRU.o0XGH`$vhLG1hxt9?W`#,5LsCp#-i>.r$<$6pD>Lb';9Crc6tgXmKVeU2cD4Eo3R/"
"2*>]b(MC;$jPfY.;h^`IWM9Qo#t'X#(v#Y9w0#1D$CIf;W'#pWUPXOuxXuU(H9M(1=Ke$$'5F%)]0^#0X@U.a Right-align from window/work-rect right-most edge. With -FLT_MIN or 0.0f will align exactly on right-most edge.
+// - outer_size.x > 0.0f -> Set Fixed width.
+// Y with ScrollX/ScrollY disabled: we output table directly in current window
+// - outer_size.y < 0.0f -> Bottom-align (but will auto extend, unless _NoHostExtendY is set). Not meaningful is parent window can vertically scroll.
+// - outer_size.y = 0.0f -> No minimum height (but will auto extend, unless _NoHostExtendY is set)
+// - outer_size.y > 0.0f -> Set Minimum height (but will auto extend, unless _NoHostExtenY is set)
+// Y with ScrollX/ScrollY enabled: using a child window for scrolling
+// - outer_size.y < 0.0f -> Bottom-align. Not meaningful is parent window can vertically scroll.
+// - outer_size.y = 0.0f -> Bottom-align, consistent with BeginChild(). Not recommended unless table is last item in parent window.
+// - outer_size.y > 0.0f -> Set Exact height. Recommended when using Scrolling on any axis.
+//-----------------------------------------------------------------------------
+// Outer size is also affected by the NoHostExtendX/NoHostExtendY flags.
+// Important to that note how the two flags have slightly different behaviors!
+// - ImGuiTableFlags_NoHostExtendX -> Make outer width auto-fit to columns (overriding outer_size.x value). Only available when ScrollX/ScrollY are disabled and Stretch columns are not used.
+// - ImGuiTableFlags_NoHostExtendY -> Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible.
+// In theory ImGuiTableFlags_NoHostExtendY could be the default and any non-scrolling tables with outer_size.y != 0.0f would use exact height.
+// This would be consistent but perhaps less useful and more confusing (as vertically clipped items are not easily noticeable)
+//-----------------------------------------------------------------------------
+// About 'inner_width':
+// With ScrollX disabled:
+// - inner_width -> *ignored*
+// With ScrollX enabled:
+// - inner_width < 0.0f -> *illegal* fit in known width (right align from outer_size.x) <-- weird
+// - inner_width = 0.0f -> fit in outer_width: Fixed size columns will take space they need (if avail, otherwise shrink down), Stretch columns becomes Fixed columns.
+// - inner_width > 0.0f -> override scrolling width, generally to be larger than outer_size.x. Fixed column take space they need (if avail, otherwise shrink down), Stretch columns share remaining space!
+//-----------------------------------------------------------------------------
+// Details:
+// - If you want to use Stretch columns with ScrollX, you generally need to specify 'inner_width' otherwise the concept
+// of "available space" doesn't make sense.
+// - Even if not really useful, we allow 'inner_width < outer_size.x' for consistency and to facilitate understanding
+// of what the value does.
+//-----------------------------------------------------------------------------
+
+//-----------------------------------------------------------------------------
+// COLUMNS SIZING POLICIES
+//-----------------------------------------------------------------------------
+// About overriding column sizing policy and width/weight with TableSetupColumn():
+// We use a default parameter of 'init_width_or_weight == -1'.
+// - with ImGuiTableColumnFlags_WidthFixed, init_width <= 0 (default) --> width is automatic
+// - with ImGuiTableColumnFlags_WidthFixed, init_width > 0 (explicit) --> width is custom
+// - with ImGuiTableColumnFlags_WidthStretch, init_weight <= 0 (default) --> weight is 1.0f
+// - with ImGuiTableColumnFlags_WidthStretch, init_weight > 0 (explicit) --> weight is custom
+// Widths are specified _without_ CellPadding. If you specify a width of 100.0f, the column will be cover (100.0f + Padding * 2.0f)
+// and you can fit a 100.0f wide item in it without clipping and with full padding.
+//-----------------------------------------------------------------------------
+// About default sizing policy (if you don't specify a ImGuiTableColumnFlags_WidthXXXX flag)
+// - with Table policy ImGuiTableFlags_SizingFixedFit --> default Column policy is ImGuiTableColumnFlags_WidthFixed, default Width is equal to contents width
+// - with Table policy ImGuiTableFlags_SizingFixedSame --> default Column policy is ImGuiTableColumnFlags_WidthFixed, default Width is max of all contents width
+// - with Table policy ImGuiTableFlags_SizingStretchSame --> default Column policy is ImGuiTableColumnFlags_WidthStretch, default Weight is 1.0f
+// - with Table policy ImGuiTableFlags_SizingStretchWeight --> default Column policy is ImGuiTableColumnFlags_WidthStretch, default Weight is proportional to contents
+// Default Width and default Weight can be overriden when calling TableSetupColumn().
+//-----------------------------------------------------------------------------
+// About mixing Fixed/Auto and Stretch columns together:
+// - the typical use of mixing sizing policies is: any number of LEADING Fixed columns, followed by one or two TRAILING Stretch columns.
+// - using mixed policies with ScrollX does not make much sense, as using Stretch columns with ScrollX does not make much sense in the first place!
+// that is, unless 'inner_width' is passed to BeginTable() to explicitely provide a total width to layout columns in.
+// - when using ImGuiTableFlags_SizingFixedSame with mixed columns, only the Fixed/Auto columns will match their widths to the maximum contents width.
+// - when using ImGuiTableFlags_SizingStretchSame with mixed columns, only the Stretch columns will match their weight/widths.
+//-----------------------------------------------------------------------------
+// About using column width:
+// If a column is manual resizable or has a width specified with TableSetupColumn():
+// - you may use GetContentRegionAvail().x to query the width available in a given column.
+// - right-side alignment features such as SetNextItemWidth(-x) or PushItemWidth(-x) will rely on this width.
+// If the column is not resizable and has no width specified with TableSetupColumn():
+// - its width will be automatic and be the set to the max of items submitted.
+// - therefore you generally cannot have ALL items of the columns use e.g. SetNextItemWidth(-FLT_MIN).
+// - but if the column has one or more item of known/fixed size, this will become the reference width used by SetNextItemWidth(-FLT_MIN).
+//-----------------------------------------------------------------------------
+
+
+//-----------------------------------------------------------------------------
+// TABLES CLIPPING/CULLING
+//-----------------------------------------------------------------------------
+// About clipping/culling of Rows in Tables:
+// - For large numbers of rows, it is recommended you use ImGuiListClipper to only submit visible rows.
+// ImGuiListClipper is reliant on the fact that rows are of equal height.
+// See 'Demo->Tables->Vertical Scrolling' or 'Demo->Tables->Advanced' for a demo of using the clipper.
+// - Note that auto-resizing columns don't play well with using the clipper.
+// By default a table with _ScrollX but without _Resizable will have column auto-resize.
+// So, if you want to use the clipper, make sure to either enable _Resizable, either setup columns width explicitly with _WidthFixed.
+//-----------------------------------------------------------------------------
+// About clipping/culling of Columns in Tables:
+// - Both TableSetColumnIndex() and TableNextColumn() return true when the column is visible or performing
+// width measurements. Otherwise, you may skip submitting the contents of a cell/column, BUT ONLY if you know
+// it is not going to contribute to row height.
+// In many situations, you may skip submitting contents for every columns but one (e.g. the first one).
+// - Case A: column is not hidden by user, and at least partially in sight (most common case).
+// - Case B: column is clipped / out of sight (because of scrolling or parent ClipRect): TableNextColumn() return false as a hint but we still allow layout output.
+// - Case C: column is hidden explicitly by the user (e.g. via the context menu, or _DefaultHide column flag, etc.).
+//
+// [A] [B] [C]
+// TableNextColumn(): true false false -> [userland] when TableNextColumn() / TableSetColumnIndex() return false, user can skip submitting items but only if the column doesn't contribute to row height.
+// SkipItems: false false true -> [internal] when SkipItems is true, most widgets will early out if submitted, resulting is no layout output.
+// ClipRect: normal zero-width zero-width -> [internal] when ClipRect is zero, ItemAdd() will return false and most widgets will early out mid-way.
+// ImDrawList output: normal dummy dummy -> [internal] when using the dummy channel, ImDrawList submissions (if any) will be wasted (because cliprect is zero-width anyway).
+//
+// - We need distinguish those cases because non-hidden columns that are clipped outside of scrolling bounds should still contribute their height to the row.
+// However, in the majority of cases, the contribution to row height is the same for all columns, or the tallest cells are known by the programmer.
+//-----------------------------------------------------------------------------
+// About clipping/culling of whole Tables:
+// - Scrolling tables with a known outer size can be clipped earlier as BeginTable() will return false.
+//-----------------------------------------------------------------------------
+
+//-----------------------------------------------------------------------------
+// [SECTION] Header mess
+//-----------------------------------------------------------------------------
+
+#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
+#define _CRT_SECURE_NO_WARNINGS
+#endif
+
+#include "imgui.h"
+#ifndef IMGUI_DISABLE
+
+#ifndef IMGUI_DEFINE_MATH_OPERATORS
+#define IMGUI_DEFINE_MATH_OPERATORS
+#endif
+#include "imgui_internal.h"
+
+// System includes
+#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
+#include // intptr_t
+#else
+#include // intptr_t
+#endif
+
+// Visual Studio warnings
+#ifdef _MSC_VER
+#pragma warning (disable: 4127) // condition expression is constant
+#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
+#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later
+#pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types
+#endif
+#endif
+
+// Clang/GCC warnings with -Weverything
+#if defined(__clang__)
+#if __has_warning("-Wunknown-warning-option")
+#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
+#endif
+#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
+#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
+#pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
+#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning: format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
+#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
+#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
+#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
+#pragma clang diagnostic ignored "-Wenum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_')
+#pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion"// warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated
+#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
+#elif defined(__GNUC__)
+#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
+#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
+#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
+#endif
+
+//-----------------------------------------------------------------------------
+// [SECTION] Tables: Main code
+//-----------------------------------------------------------------------------
+
+// Configuration
+static const int TABLE_DRAW_CHANNEL_BG0 = 0;
+static const int TABLE_DRAW_CHANNEL_BG2_FROZEN = 1;
+static const int TABLE_DRAW_CHANNEL_NOCLIP = 2; // When using ImGuiTableFlags_NoClip (this becomes the last visible channel)
+static const float TABLE_BORDER_SIZE = 1.0f; // FIXME-TABLE: Currently hard-coded because of clipping assumptions with outer borders rendering.
+static const float TABLE_RESIZE_SEPARATOR_HALF_THICKNESS = 4.0f; // Extend outside inner borders.
+static const float TABLE_RESIZE_SEPARATOR_FEEDBACK_TIMER = 0.06f; // Delay/timer before making the hover feedback (color+cursor) visible because tables/columns tends to be more cramped.
+
+// Helper
+inline ImGuiTableFlags TableFixFlags(ImGuiTableFlags flags, ImGuiWindow* outer_window)
+{
+ // Adjust flags: set default sizing policy
+ if ((flags & ImGuiTableFlags_SizingMask_) == 0)
+ flags |= ((flags & ImGuiTableFlags_ScrollX) || (outer_window->Flags & ImGuiWindowFlags_AlwaysAutoResize)) ? ImGuiTableFlags_SizingFixedFit : ImGuiTableFlags_SizingStretchSame;
+
+ // Adjust flags: enable NoKeepColumnsVisible when using ImGuiTableFlags_SizingFixedSame
+ if ((flags & ImGuiTableFlags_SizingMask_) == ImGuiTableFlags_SizingFixedSame)
+ flags |= ImGuiTableFlags_NoKeepColumnsVisible;
+
+ // Adjust flags: enforce borders when resizable
+ if (flags & ImGuiTableFlags_Resizable)
+ flags |= ImGuiTableFlags_BordersInnerV;
+
+ // Adjust flags: disable NoHostExtendX/NoHostExtendY if we have any scrolling going on
+ if (flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY))
+ flags &= ~(ImGuiTableFlags_NoHostExtendX | ImGuiTableFlags_NoHostExtendY);
+
+ // Adjust flags: NoBordersInBodyUntilResize takes priority over NoBordersInBody
+ if (flags & ImGuiTableFlags_NoBordersInBodyUntilResize)
+ flags &= ~ImGuiTableFlags_NoBordersInBody;
+
+ // Adjust flags: disable saved settings if there's nothing to save
+ if ((flags & (ImGuiTableFlags_Resizable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Sortable)) == 0)
+ flags |= ImGuiTableFlags_NoSavedSettings;
+
+ // Inherit _NoSavedSettings from top-level window (child windows always have _NoSavedSettings set)
+#ifdef IMGUI_HAS_DOCK
+ ImGuiWindow* window_for_settings = outer_window->RootWindowDockStop;
+#else
+ ImGuiWindow* window_for_settings = outer_window->RootWindow;
+#endif
+ if (window_for_settings->Flags & ImGuiWindowFlags_NoSavedSettings)
+ flags |= ImGuiTableFlags_NoSavedSettings;
+
+ return flags;
+}
+
+ImGuiTable* ImGui::TableFindByID(ImGuiID id)
+{
+ ImGuiContext& g = *GImGui;
+ return g.Tables.GetByKey(id);
+}
+
+// Read about "TABLE SIZING" at the top of this file.
+bool ImGui::BeginTable(const char* str_id, int columns_count, ImGuiTableFlags flags, const ImVec2& outer_size, float inner_width)
+{
+ ImGuiID id = GetID(str_id);
+ return BeginTableEx(str_id, id, columns_count, flags, outer_size, inner_width);
+}
+
+bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImGuiTableFlags flags, const ImVec2& outer_size, float inner_width)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* outer_window = GetCurrentWindow();
+ if (outer_window->SkipItems) // Consistent with other tables + beneficial side effect that assert on miscalling EndTable() will be more visible.
+ return false;
+
+ // Sanity checks
+ IM_ASSERT(columns_count > 0 && columns_count <= IMGUI_TABLE_MAX_COLUMNS && "Only 1..64 columns allowed!");
+ if (flags & ImGuiTableFlags_ScrollX)
+ IM_ASSERT(inner_width >= 0.0f);
+
+ // If an outer size is specified ahead we will be able to early out when not visible. Exact clipping rules may evolve.
+ const bool use_child_window = (flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) != 0;
+ const ImVec2 avail_size = GetContentRegionAvail();
+ ImVec2 actual_outer_size = CalcItemSize(outer_size, ImMax(avail_size.x, 1.0f), use_child_window ? ImMax(avail_size.y, 1.0f) : 0.0f);
+ ImRect outer_rect(outer_window->DC.CursorPos, outer_window->DC.CursorPos + actual_outer_size);
+ if (use_child_window && IsClippedEx(outer_rect, 0, false))
+ {
+ ItemSize(outer_rect);
+ return false;
+ }
+
+ // Acquire storage for the table
+ ImGuiTable* table = g.Tables.GetOrAddByKey(id);
+ const int instance_no = (table->LastFrameActive != g.FrameCount) ? 0 : table->InstanceCurrent + 1;
+ const ImGuiID instance_id = id + instance_no;
+ const ImGuiTableFlags table_last_flags = table->Flags;
+ if (instance_no > 0)
+ IM_ASSERT(table->ColumnsCount == columns_count && "BeginTable(): Cannot change columns count mid-frame while preserving same ID");
+
+ // Fix flags
+ table->IsDefaultSizingPolicy = (flags & ImGuiTableFlags_SizingMask_) == 0;
+ flags = TableFixFlags(flags, outer_window);
+
+ // Initialize
+ table->ID = id;
+ table->Flags = flags;
+ table->InstanceCurrent = (ImS16)instance_no;
+ table->LastFrameActive = g.FrameCount;
+ table->OuterWindow = table->InnerWindow = outer_window;
+ table->ColumnsCount = columns_count;
+ table->IsLayoutLocked = false;
+ table->InnerWidth = inner_width;
+ table->UserOuterSize = outer_size;
+
+ // When not using a child window, WorkRect.Max will grow as we append contents.
+ if (use_child_window)
+ {
+ // Ensure no vertical scrollbar appears if we only want horizontal one, to make flag consistent
+ // (we have no other way to disable vertical scrollbar of a window while keeping the horizontal one showing)
+ ImVec2 override_content_size(FLT_MAX, FLT_MAX);
+ if ((flags & ImGuiTableFlags_ScrollX) && !(flags & ImGuiTableFlags_ScrollY))
+ override_content_size.y = FLT_MIN;
+
+ // Ensure specified width (when not specified, Stretched columns will act as if the width == OuterWidth and
+ // never lead to any scrolling). We don't handle inner_width < 0.0f, we could potentially use it to right-align
+ // based on the right side of the child window work rect, which would require knowing ahead if we are going to
+ // have decoration taking horizontal spaces (typically a vertical scrollbar).
+ if ((flags & ImGuiTableFlags_ScrollX) && inner_width > 0.0f)
+ override_content_size.x = inner_width;
+
+ if (override_content_size.x != FLT_MAX || override_content_size.y != FLT_MAX)
+ SetNextWindowContentSize(ImVec2(override_content_size.x != FLT_MAX ? override_content_size.x : 0.0f, override_content_size.y != FLT_MAX ? override_content_size.y : 0.0f));
+
+ // Reset scroll if we are reactivating it
+ if ((table_last_flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) == 0)
+ SetNextWindowScroll(ImVec2(0.0f, 0.0f));
+
+ // Create scrolling region (without border and zero window padding)
+ ImGuiWindowFlags child_flags = (flags & ImGuiTableFlags_ScrollX) ? ImGuiWindowFlags_HorizontalScrollbar : ImGuiWindowFlags_None;
+ BeginChildEx(name, instance_id, outer_rect.GetSize(), false, child_flags);
+ table->InnerWindow = g.CurrentWindow;
+ table->WorkRect = table->InnerWindow->WorkRect;
+ table->OuterRect = table->InnerWindow->Rect();
+ table->InnerRect = table->InnerWindow->InnerRect;
+ IM_ASSERT(table->InnerWindow->WindowPadding.x == 0.0f && table->InnerWindow->WindowPadding.y == 0.0f && table->InnerWindow->WindowBorderSize == 0.0f);
+ }
+ else
+ {
+ // For non-scrolling tables, WorkRect == OuterRect == InnerRect.
+ // But at this point we do NOT have a correct value for .Max.y (unless a height has been explicitly passed in). It will only be updated in EndTable().
+ table->WorkRect = table->OuterRect = table->InnerRect = outer_rect;
+ }
+
+ // Push a standardized ID for both child-using and not-child-using tables
+ PushOverrideID(instance_id);
+
+ // Backup a copy of host window members we will modify
+ ImGuiWindow* inner_window = table->InnerWindow;
+ table->HostIndentX = inner_window->DC.Indent.x;
+ table->HostClipRect = inner_window->ClipRect;
+ table->HostSkipItems = inner_window->SkipItems;
+ table->HostBackupWorkRect = inner_window->WorkRect;
+ table->HostBackupParentWorkRect = inner_window->ParentWorkRect;
+ table->HostBackupColumnsOffset = outer_window->DC.ColumnsOffset;
+ table->HostBackupPrevLineSize = inner_window->DC.PrevLineSize;
+ table->HostBackupCurrLineSize = inner_window->DC.CurrLineSize;
+ table->HostBackupCursorMaxPos = inner_window->DC.CursorMaxPos;
+ table->HostBackupItemWidth = outer_window->DC.ItemWidth;
+ table->HostBackupItemWidthStackSize = outer_window->DC.ItemWidthStack.Size;
+ inner_window->DC.PrevLineSize = inner_window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
+
+ // Padding and Spacing
+ // - None ........Content..... Pad .....Content........
+ // - PadOuter | Pad ..Content..... Pad .....Content.. Pad |
+ // - PadInner ........Content.. Pad | Pad ..Content........
+ // - PadOuter+PadInner | Pad ..Content.. Pad | Pad ..Content.. Pad |
+ const bool pad_outer_x = (flags & ImGuiTableFlags_NoPadOuterX) ? false : (flags & ImGuiTableFlags_PadOuterX) ? true : (flags & ImGuiTableFlags_BordersOuterV) != 0;
+ const bool pad_inner_x = (flags & ImGuiTableFlags_NoPadInnerX) ? false : true;
+ const float inner_spacing_for_border = (flags & ImGuiTableFlags_BordersInnerV) ? TABLE_BORDER_SIZE : 0.0f;
+ const float inner_spacing_explicit = (pad_inner_x && (flags & ImGuiTableFlags_BordersInnerV) == 0) ? g.Style.CellPadding.x : 0.0f;
+ const float inner_padding_explicit = (pad_inner_x && (flags & ImGuiTableFlags_BordersInnerV) != 0) ? g.Style.CellPadding.x : 0.0f;
+ table->CellSpacingX1 = inner_spacing_explicit + inner_spacing_for_border;
+ table->CellSpacingX2 = inner_spacing_explicit;
+ table->CellPaddingX = inner_padding_explicit;
+ table->CellPaddingY = g.Style.CellPadding.y;
+
+ const float outer_padding_for_border = (flags & ImGuiTableFlags_BordersOuterV) ? TABLE_BORDER_SIZE : 0.0f;
+ const float outer_padding_explicit = pad_outer_x ? g.Style.CellPadding.x : 0.0f;
+ table->OuterPaddingX = (outer_padding_for_border + outer_padding_explicit) - table->CellPaddingX;
+
+ table->CurrentColumn = -1;
+ table->CurrentRow = -1;
+ table->RowBgColorCounter = 0;
+ table->LastRowFlags = ImGuiTableRowFlags_None;
+ table->InnerClipRect = (inner_window == outer_window) ? table->WorkRect : inner_window->ClipRect;
+ table->InnerClipRect.ClipWith(table->WorkRect); // We need this to honor inner_width
+ table->InnerClipRect.ClipWithFull(table->HostClipRect);
+ table->InnerClipRect.Max.y = (flags & ImGuiTableFlags_NoHostExtendY) ? ImMin(table->InnerClipRect.Max.y, inner_window->WorkRect.Max.y) : inner_window->ClipRect.Max.y;
+
+ table->RowPosY1 = table->RowPosY2 = table->WorkRect.Min.y; // This is needed somehow
+ table->RowTextBaseline = 0.0f; // This will be cleared again by TableBeginRow()
+ table->FreezeRowsRequest = table->FreezeRowsCount = 0; // This will be setup by TableSetupScrollFreeze(), if any
+ table->FreezeColumnsRequest = table->FreezeColumnsCount = 0;
+ table->IsUnfrozenRows = true;
+ table->DeclColumnsCount = 0;
+
+ // Using opaque colors facilitate overlapping elements of the grid
+ table->BorderColorStrong = GetColorU32(ImGuiCol_TableBorderStrong);
+ table->BorderColorLight = GetColorU32(ImGuiCol_TableBorderLight);
+
+ // Make table current
+ const int table_idx = g.Tables.GetIndex(table);
+ g.CurrentTableStack.push_back(ImGuiPtrOrIndex(table_idx));
+ g.CurrentTable = table;
+ outer_window->DC.CurrentTableIdx = table_idx;
+ if (inner_window != outer_window) // So EndChild() within the inner window can restore the table properly.
+ inner_window->DC.CurrentTableIdx = table_idx;
+
+ if ((table_last_flags & ImGuiTableFlags_Reorderable) && (flags & ImGuiTableFlags_Reorderable) == 0)
+ table->IsResetDisplayOrderRequest = true;
+
+ // Mark as used
+ if (table_idx >= g.TablesLastTimeActive.Size)
+ g.TablesLastTimeActive.resize(table_idx + 1, -1.0f);
+ g.TablesLastTimeActive[table_idx] = (float)g.Time;
+ table->MemoryCompacted = false;
+
+ // Setup memory buffer (clear data if columns count changed)
+ const int stored_size = table->Columns.size();
+ if (stored_size != 0 && stored_size != columns_count)
+ {
+ IM_FREE(table->RawData);
+ table->RawData = NULL;
+ }
+ if (table->RawData == NULL)
+ {
+ TableBeginInitMemory(table, columns_count);
+ table->IsInitializing = table->IsSettingsRequestLoad = true;
+ }
+ if (table->IsResetAllRequest)
+ TableResetSettings(table);
+ if (table->IsInitializing)
+ {
+ // Initialize
+ table->SettingsOffset = -1;
+ table->IsSortSpecsDirty = true;
+ table->InstanceInteracted = -1;
+ table->ContextPopupColumn = -1;
+ table->ReorderColumn = table->ResizedColumn = table->LastResizedColumn = -1;
+ table->AutoFitSingleColumn = -1;
+ table->HoveredColumnBody = table->HoveredColumnBorder = -1;
+ for (int n = 0; n < columns_count; n++)
+ {
+ ImGuiTableColumn* column = &table->Columns[n];
+ float width_auto = column->WidthAuto;
+ *column = ImGuiTableColumn();
+ column->WidthAuto = width_auto;
+ column->IsPreserveWidthAuto = true; // Preserve WidthAuto when reinitializing a live table: not technically necessary but remove a visible flicker
+ column->DisplayOrder = table->DisplayOrderToIndex[n] = (ImGuiTableColumnIdx)n;
+ column->IsEnabled = column->IsEnabledNextFrame = true;
+ }
+ }
+
+ // Load settings
+ if (table->IsSettingsRequestLoad)
+ TableLoadSettings(table);
+
+ // Handle DPI/font resize
+ // This is designed to facilitate DPI changes with the assumption that e.g. style.CellPadding has been scaled as well.
+ // It will also react to changing fonts with mixed results. It doesn't need to be perfect but merely provide a decent transition.
+ // FIXME-DPI: Provide consistent standards for reference size. Perhaps using g.CurrentDpiScale would be more self explanatory.
+ // This is will lead us to non-rounded WidthRequest in columns, which should work but is a poorly tested path.
+ const float new_ref_scale_unit = g.FontSize; // g.Font->GetCharAdvance('A') ?
+ if (table->RefScale != 0.0f && table->RefScale != new_ref_scale_unit)
+ {
+ const float scale_factor = new_ref_scale_unit / table->RefScale;
+ //IMGUI_DEBUG_LOG("[table] %08X RefScaleUnit %.3f -> %.3f, scaling width by %.3f\n", table->ID, table->RefScaleUnit, new_ref_scale_unit, scale_factor);
+ for (int n = 0; n < columns_count; n++)
+ table->Columns[n].WidthRequest = table->Columns[n].WidthRequest * scale_factor;
+ }
+ table->RefScale = new_ref_scale_unit;
+
+ // Disable output until user calls TableNextRow() or TableNextColumn() leading to the TableUpdateLayout() call..
+ // This is not strictly necessary but will reduce cases were "out of table" output will be misleading to the user.
+ // Because we cannot safely assert in EndTable() when no rows have been created, this seems like our best option.
+ inner_window->SkipItems = true;
+
+ // Clear names
+ // At this point the ->NameOffset field of each column will be invalid until TableUpdateLayout() or the first call to TableSetupColumn()
+ if (table->ColumnsNames.Buf.Size > 0)
+ table->ColumnsNames.Buf.resize(0);
+
+ // Apply queued resizing/reordering/hiding requests
+ TableBeginApplyRequests(table);
+
+ return true;
+}
+
+// For reference, the average total _allocation count_ for a table is:
+// + 0 (for ImGuiTable instance, we are pooling allocations in g.Tables)
+// + 1 (for table->RawData allocated below)
+// + 1 (for table->ColumnsNames, if names are used)
+// + 1 (for table->Splitter._Channels)
+// + 2 * active_channels_count (for ImDrawCmd and ImDrawIdx buffers inside channels)
+// Where active_channels_count is variable but often == columns_count or columns_count + 1, see TableSetupDrawChannels() for details.
+// Unused channels don't perform their +2 allocations.
+void ImGui::TableBeginInitMemory(ImGuiTable* table, int columns_count)
+{
+ // Allocate single buffer for our arrays
+ ImSpanAllocator<3> span_allocator;
+ span_allocator.ReserveBytes(0, columns_count * sizeof(ImGuiTableColumn));
+ span_allocator.ReserveBytes(1, columns_count * sizeof(ImGuiTableColumnIdx));
+ span_allocator.ReserveBytes(2, columns_count * sizeof(ImGuiTableCellData));
+ table->RawData = IM_ALLOC(span_allocator.GetArenaSizeInBytes());
+ memset(table->RawData, 0, span_allocator.GetArenaSizeInBytes());
+ span_allocator.SetArenaBasePtr(table->RawData);
+ span_allocator.GetSpan(0, &table->Columns);
+ span_allocator.GetSpan(1, &table->DisplayOrderToIndex);
+ span_allocator.GetSpan(2, &table->RowCellData);
+}
+
+// Apply queued resizing/reordering/hiding requests
+void ImGui::TableBeginApplyRequests(ImGuiTable* table)
+{
+ // Handle resizing request
+ // (We process this at the first TableBegin of the frame)
+ // FIXME-TABLE: Contains columns if our work area doesn't allow for scrolling?
+ if (table->InstanceCurrent == 0)
+ {
+ if (table->ResizedColumn != -1 && table->ResizedColumnNextWidth != FLT_MAX)
+ TableSetColumnWidth(table->ResizedColumn, table->ResizedColumnNextWidth);
+ table->LastResizedColumn = table->ResizedColumn;
+ table->ResizedColumnNextWidth = FLT_MAX;
+ table->ResizedColumn = -1;
+
+ // Process auto-fit for single column, which is a special case for stretch columns and fixed columns with FixedSame policy.
+ // FIXME-TABLE: Would be nice to redistribute available stretch space accordingly to other weights, instead of giving it all to siblings.
+ if (table->AutoFitSingleColumn != -1)
+ {
+ TableSetColumnWidth(table->AutoFitSingleColumn, table->Columns[table->AutoFitSingleColumn].WidthAuto);
+ table->AutoFitSingleColumn = -1;
+ }
+ }
+
+ // Handle reordering request
+ // Note: we don't clear ReorderColumn after handling the request.
+ if (table->InstanceCurrent == 0)
+ {
+ if (table->HeldHeaderColumn == -1 && table->ReorderColumn != -1)
+ table->ReorderColumn = -1;
+ table->HeldHeaderColumn = -1;
+ if (table->ReorderColumn != -1 && table->ReorderColumnDir != 0)
+ {
+ // We need to handle reordering across hidden columns.
+ // In the configuration below, moving C to the right of E will lead to:
+ // ... C [D] E ---> ... [D] E C (Column name/index)
+ // ... 2 3 4 ... 2 3 4 (Display order)
+ const int reorder_dir = table->ReorderColumnDir;
+ IM_ASSERT(reorder_dir == -1 || reorder_dir == +1);
+ IM_ASSERT(table->Flags & ImGuiTableFlags_Reorderable);
+ ImGuiTableColumn* src_column = &table->Columns[table->ReorderColumn];
+ ImGuiTableColumn* dst_column = &table->Columns[(reorder_dir == -1) ? src_column->PrevEnabledColumn : src_column->NextEnabledColumn];
+ IM_UNUSED(dst_column);
+ const int src_order = src_column->DisplayOrder;
+ const int dst_order = dst_column->DisplayOrder;
+ src_column->DisplayOrder = (ImGuiTableColumnIdx)dst_order;
+ for (int order_n = src_order + reorder_dir; order_n != dst_order + reorder_dir; order_n += reorder_dir)
+ table->Columns[table->DisplayOrderToIndex[order_n]].DisplayOrder -= (ImGuiTableColumnIdx)reorder_dir;
+ IM_ASSERT(dst_column->DisplayOrder == dst_order - reorder_dir);
+
+ // Display order is stored in both columns->IndexDisplayOrder and table->DisplayOrder[],
+ // rebuild the later from the former.
+ for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
+ table->DisplayOrderToIndex[table->Columns[column_n].DisplayOrder] = (ImGuiTableColumnIdx)column_n;
+ table->ReorderColumnDir = 0;
+ table->IsSettingsDirty = true;
+ }
+ }
+
+ // Handle display order reset request
+ if (table->IsResetDisplayOrderRequest)
+ {
+ for (int n = 0; n < table->ColumnsCount; n++)
+ table->DisplayOrderToIndex[n] = table->Columns[n].DisplayOrder = (ImGuiTableColumnIdx)n;
+ table->IsResetDisplayOrderRequest = false;
+ table->IsSettingsDirty = true;
+ }
+}
+
+// Adjust flags: default width mode + stretch columns are not allowed when auto extending
+static void TableSetupColumnFlags(ImGuiTable* table, ImGuiTableColumn* column, ImGuiTableColumnFlags flags_in)
+{
+ ImGuiTableColumnFlags flags = flags_in;
+
+ // Sizing Policy
+ if ((flags & ImGuiTableColumnFlags_WidthMask_) == 0)
+ {
+ const ImGuiTableFlags table_sizing_policy = (table->Flags & ImGuiTableFlags_SizingMask_);
+ if (table_sizing_policy == ImGuiTableFlags_SizingFixedFit || table_sizing_policy == ImGuiTableFlags_SizingFixedSame)
+ flags |= ImGuiTableColumnFlags_WidthFixed;
+ else
+ flags |= ImGuiTableColumnFlags_WidthStretch;
+ }
+ else
+ {
+ IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiTableColumnFlags_WidthMask_)); // Check that only 1 of each set is used.
+ }
+
+ // Resize
+ if ((table->Flags & ImGuiTableFlags_Resizable) == 0)
+ flags |= ImGuiTableColumnFlags_NoResize;
+
+ // Sorting
+ if ((flags & ImGuiTableColumnFlags_NoSortAscending) && (flags & ImGuiTableColumnFlags_NoSortDescending))
+ flags |= ImGuiTableColumnFlags_NoSort;
+
+ // Indentation
+ if ((flags & ImGuiTableColumnFlags_IndentMask_) == 0)
+ flags |= (table->Columns.index_from_ptr(column) == 0) ? ImGuiTableColumnFlags_IndentEnable : ImGuiTableColumnFlags_IndentDisable;
+
+ // Alignment
+ //if ((flags & ImGuiTableColumnFlags_AlignMask_) == 0)
+ // flags |= ImGuiTableColumnFlags_AlignCenter;
+ //IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiTableColumnFlags_AlignMask_)); // Check that only 1 of each set is used.
+
+ // Preserve status flags
+ column->Flags = flags | (column->Flags & ImGuiTableColumnFlags_StatusMask_);
+
+ // Build an ordered list of available sort directions
+ column->SortDirectionsAvailCount = column->SortDirectionsAvailMask = column->SortDirectionsAvailList = 0;
+ if (table->Flags & ImGuiTableFlags_Sortable)
+ {
+ int count = 0, mask = 0, list = 0;
+ if ((flags & ImGuiTableColumnFlags_PreferSortAscending) != 0 && (flags & ImGuiTableColumnFlags_NoSortAscending) == 0) { mask |= 1 << ImGuiSortDirection_Ascending; list |= ImGuiSortDirection_Ascending << (count << 1); count++; }
+ if ((flags & ImGuiTableColumnFlags_PreferSortDescending) != 0 && (flags & ImGuiTableColumnFlags_NoSortDescending) == 0) { mask |= 1 << ImGuiSortDirection_Descending; list |= ImGuiSortDirection_Descending << (count << 1); count++; }
+ if ((flags & ImGuiTableColumnFlags_PreferSortAscending) == 0 && (flags & ImGuiTableColumnFlags_NoSortAscending) == 0) { mask |= 1 << ImGuiSortDirection_Ascending; list |= ImGuiSortDirection_Ascending << (count << 1); count++; }
+ if ((flags & ImGuiTableColumnFlags_PreferSortDescending) == 0 && (flags & ImGuiTableColumnFlags_NoSortDescending) == 0) { mask |= 1 << ImGuiSortDirection_Descending; list |= ImGuiSortDirection_Descending << (count << 1); count++; }
+ if ((table->Flags & ImGuiTableFlags_SortTristate) || count == 0) { mask |= 1 << ImGuiSortDirection_None; count++; }
+ column->SortDirectionsAvailList = (ImU8)list;
+ column->SortDirectionsAvailMask = (ImU8)mask;
+ column->SortDirectionsAvailCount = (ImU8)count;
+ ImGui::TableFixColumnSortDirection(table, column);
+ }
+}
+
+// Layout columns for the frame. This is in essence the followup to BeginTable().
+// Runs on the first call to TableNextRow(), to give a chance for TableSetupColumn() to be called first.
+// FIXME-TABLE: Our width (and therefore our WorkRect) will be minimal in the first frame for _WidthAuto columns.
+// Increase feedback side-effect with widgets relying on WorkRect.Max.x... Maybe provide a default distribution for _WidthAuto columns?
+void ImGui::TableUpdateLayout(ImGuiTable* table)
+{
+ ImGuiContext& g = *GImGui;
+ IM_ASSERT(table->IsLayoutLocked == false);
+
+ const ImGuiTableFlags table_sizing_policy = (table->Flags & ImGuiTableFlags_SizingMask_);
+ table->IsDefaultDisplayOrder = true;
+ table->ColumnsEnabledCount = 0;
+ table->EnabledMaskByIndex = 0x00;
+ table->EnabledMaskByDisplayOrder = 0x00;
+ table->MinColumnWidth = ImMax(1.0f, g.Style.FramePadding.x * 1.0f); // g.Style.ColumnsMinSpacing; // FIXME-TABLE
+
+ // [Part 1] Apply/lock Enabled and Order states. Calculate auto/ideal width for columns. Count fixed/stretch columns.
+ // Process columns in their visible orders as we are building the Prev/Next indices.
+ int count_fixed = 0; // Number of columns that have fixed sizing policies
+ int count_stretch = 0; // Number of columns that have stretch sizing policies
+ int last_visible_column_idx = -1;
+ bool has_auto_fit_request = false;
+ bool has_resizable = false;
+ float stretch_sum_width_auto = 0.0f;
+ float fixed_max_width_auto = 0.0f;
+ for (int order_n = 0; order_n < table->ColumnsCount; order_n++)
+ {
+ const int column_n = table->DisplayOrderToIndex[order_n];
+ if (column_n != order_n)
+ table->IsDefaultDisplayOrder = false;
+ ImGuiTableColumn* column = &table->Columns[column_n];
+
+ // Clear column setup if not submitted by user. Currently we make it mandatory to call TableSetupColumn() every frame.
+ // It would easily work without but we're not ready to guarantee it since e.g. names need resubmission anyway.
+ // We take a slight shortcut but in theory we could be calling TableSetupColumn() here with dummy values, it should yield the same effect.
+ if (table->DeclColumnsCount <= column_n)
+ {
+ TableSetupColumnFlags(table, column, ImGuiTableColumnFlags_None);
+ column->NameOffset = -1;
+ column->UserID = 0;
+ column->InitStretchWeightOrWidth = -1.0f;
+ }
+
+ // Update Enabled state, mark settings/sortspecs dirty
+ if (!(table->Flags & ImGuiTableFlags_Hideable) || (column->Flags & ImGuiTableColumnFlags_NoHide))
+ column->IsEnabledNextFrame = true;
+ if (column->IsEnabled != column->IsEnabledNextFrame)
+ {
+ column->IsEnabled = column->IsEnabledNextFrame;
+ table->IsSettingsDirty = true;
+ if (!column->IsEnabled && column->SortOrder != -1)
+ table->IsSortSpecsDirty = true;
+ }
+ if (column->SortOrder > 0 && !(table->Flags & ImGuiTableFlags_SortMulti))
+ table->IsSortSpecsDirty = true;
+
+ // Auto-fit unsized columns
+ const bool start_auto_fit = (column->Flags & ImGuiTableColumnFlags_WidthFixed) ? (column->WidthRequest < 0.0f) : (column->StretchWeight < 0.0f);
+ if (start_auto_fit)
+ column->AutoFitQueue = column->CannotSkipItemsQueue = (1 << 3) - 1; // Fit for three frames
+
+ if (!column->IsEnabled)
+ {
+ column->IndexWithinEnabledSet = -1;
+ continue;
+ }
+
+ // Mark as enabled and link to previous/next enabled column
+ column->PrevEnabledColumn = (ImGuiTableColumnIdx)last_visible_column_idx;
+ column->NextEnabledColumn = -1;
+ if (last_visible_column_idx != -1)
+ table->Columns[last_visible_column_idx].NextEnabledColumn = (ImGuiTableColumnIdx)column_n;
+ column->IndexWithinEnabledSet = table->ColumnsEnabledCount++;
+ table->EnabledMaskByIndex |= (ImU64)1 << column_n;
+ table->EnabledMaskByDisplayOrder |= (ImU64)1 << column->DisplayOrder;
+ last_visible_column_idx = column_n;
+ IM_ASSERT(column->IndexWithinEnabledSet <= column->DisplayOrder);
+
+ // Calculate ideal/auto column width (that's the width required for all contents to be visible without clipping)
+ // Combine width from regular rows + width from headers unless requested not to.
+ if (!column->IsPreserveWidthAuto)
+ column->WidthAuto = TableGetColumnWidthAuto(table, column);
+
+ // Non-resizable columns keep their requested width (apply user value regardless of IsPreserveWidthAuto)
+ const bool column_is_resizable = (column->Flags & ImGuiTableColumnFlags_NoResize) == 0;
+ if (column_is_resizable)
+ has_resizable = true;
+ if ((column->Flags & ImGuiTableColumnFlags_WidthFixed) && column->InitStretchWeightOrWidth > 0.0f && !column_is_resizable)
+ column->WidthAuto = column->InitStretchWeightOrWidth;
+
+ if (column->AutoFitQueue != 0x00)
+ has_auto_fit_request = true;
+ if (column->Flags & ImGuiTableColumnFlags_WidthStretch)
+ {
+ stretch_sum_width_auto += column->WidthAuto;
+ count_stretch++;
+ }
+ else
+ {
+ fixed_max_width_auto = ImMax(fixed_max_width_auto, column->WidthAuto);
+ count_fixed++;
+ }
+ }
+ if ((table->Flags & ImGuiTableFlags_Sortable) && table->SortSpecsCount == 0 && !(table->Flags & ImGuiTableFlags_SortTristate))
+ table->IsSortSpecsDirty = true;
+ table->RightMostEnabledColumn = (ImGuiTableColumnIdx)last_visible_column_idx;
+ IM_ASSERT(table->RightMostEnabledColumn >= 0);
+
+ // [Part 2] Disable child window clipping while fitting columns. This is not strictly necessary but makes it possible
+ // to avoid the column fitting having to wait until the first visible frame of the child container (may or not be a good thing).
+ // FIXME-TABLE: for always auto-resizing columns may not want to do that all the time.
+ if (has_auto_fit_request && table->OuterWindow != table->InnerWindow)
+ table->InnerWindow->SkipItems = false;
+ if (has_auto_fit_request)
+ table->IsSettingsDirty = true;
+
+ // [Part 3] Fix column flags and record a few extra information.
+ float sum_width_requests = 0.0f; // Sum of all width for fixed and auto-resize columns, excluding width contributed by Stretch columns but including spacing/padding.
+ float stretch_sum_weights = 0.0f; // Sum of all weights for stretch columns.
+ table->LeftMostStretchedColumn = table->RightMostStretchedColumn = -1;
+ for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
+ {
+ if (!(table->EnabledMaskByIndex & ((ImU64)1 << column_n)))
+ continue;
+ ImGuiTableColumn* column = &table->Columns[column_n];
+
+ const bool column_is_resizable = (column->Flags & ImGuiTableColumnFlags_NoResize) == 0;
+ if (column->Flags & ImGuiTableColumnFlags_WidthFixed)
+ {
+ // Apply same widths policy
+ float width_auto = column->WidthAuto;
+ if (table_sizing_policy == ImGuiTableFlags_SizingFixedSame && (column->AutoFitQueue != 0x00 || !column_is_resizable))
+ width_auto = fixed_max_width_auto;
+
+ // Apply automatic width
+ // Latch initial size for fixed columns and update it constantly for auto-resizing column (unless clipped!)
+ if (column->AutoFitQueue != 0x00)
+ column->WidthRequest = width_auto;
+ else if ((column->Flags & ImGuiTableColumnFlags_WidthFixed) && !column_is_resizable && (table->RequestOutputMaskByIndex & ((ImU64)1 << column_n)))
+ column->WidthRequest = width_auto;
+
+ // FIXME-TABLE: Increase minimum size during init frame to avoid biasing auto-fitting widgets
+ // (e.g. TextWrapped) too much. Otherwise what tends to happen is that TextWrapped would output a very
+ // large height (= first frame scrollbar display very off + clipper would skip lots of items).
+ // This is merely making the side-effect less extreme, but doesn't properly fixes it.
+ // FIXME: Move this to ->WidthGiven to avoid temporary lossyless?
+ // FIXME: This break IsPreserveWidthAuto from not flickering if the stored WidthAuto was smaller.
+ if (column->AutoFitQueue > 0x01 && table->IsInitializing && !column->IsPreserveWidthAuto)
+ column->WidthRequest = ImMax(column->WidthRequest, table->MinColumnWidth * 4.0f); // FIXME-TABLE: Another constant/scale?
+ sum_width_requests += column->WidthRequest;
+ }
+ else
+ {
+ // Initialize stretch weight
+ if (column->AutoFitQueue != 0x00 || column->StretchWeight < 0.0f || !column_is_resizable)
+ {
+ if (column->InitStretchWeightOrWidth > 0.0f)
+ column->StretchWeight = column->InitStretchWeightOrWidth;
+ else if (table_sizing_policy == ImGuiTableFlags_SizingStretchProp)
+ column->StretchWeight = (column->WidthAuto / stretch_sum_width_auto) * count_stretch;
+ else
+ column->StretchWeight = 1.0f;
+ }
+
+ stretch_sum_weights += column->StretchWeight;
+ if (table->LeftMostStretchedColumn == -1 || table->Columns[table->LeftMostStretchedColumn].DisplayOrder > column->DisplayOrder)
+ table->LeftMostStretchedColumn = (ImGuiTableColumnIdx)column_n;
+ if (table->RightMostStretchedColumn == -1 || table->Columns[table->RightMostStretchedColumn].DisplayOrder < column->DisplayOrder)
+ table->RightMostStretchedColumn = (ImGuiTableColumnIdx)column_n;
+ }
+ column->IsPreserveWidthAuto = false;
+ sum_width_requests += table->CellPaddingX * 2.0f;
+ }
+ table->ColumnsEnabledFixedCount = (ImGuiTableColumnIdx)count_fixed;
+
+ // [Part 4] Apply final widths based on requested widths
+ const ImRect work_rect = table->WorkRect;
+ const float width_spacings = (table->OuterPaddingX * 2.0f) + (table->CellSpacingX1 + table->CellSpacingX2) * (table->ColumnsEnabledCount - 1);
+ const float width_avail = ((table->Flags & ImGuiTableFlags_ScrollX) && table->InnerWidth == 0.0f) ? table->InnerClipRect.GetWidth() : work_rect.GetWidth();
+ const float width_avail_for_stretched_columns = width_avail - width_spacings - sum_width_requests;
+ float width_remaining_for_stretched_columns = width_avail_for_stretched_columns;
+ table->ColumnsGivenWidth = width_spacings + (table->CellPaddingX * 2.0f) * table->ColumnsEnabledCount;
+ for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
+ {
+ if (!(table->EnabledMaskByIndex & ((ImU64)1 << column_n)))
+ continue;
+ ImGuiTableColumn* column = &table->Columns[column_n];
+
+ // Allocate width for stretched/weighted columns (StretchWeight gets converted into WidthRequest)
+ if (column->Flags & ImGuiTableColumnFlags_WidthStretch)
+ {
+ float weight_ratio = column->StretchWeight / stretch_sum_weights;
+ column->WidthRequest = IM_FLOOR(ImMax(width_avail_for_stretched_columns * weight_ratio, table->MinColumnWidth) + 0.01f);
+ width_remaining_for_stretched_columns -= column->WidthRequest;
+ }
+
+ // [Resize Rule 1] The right-most Visible column is not resizable if there is at least one Stretch column
+ // See additional comments in TableSetColumnWidth().
+ if (column->NextEnabledColumn == -1 && table->LeftMostStretchedColumn != -1)
+ column->Flags |= ImGuiTableColumnFlags_NoDirectResize_;
+
+ // Assign final width, record width in case we will need to shrink
+ column->WidthGiven = ImFloor(ImMax(column->WidthRequest, table->MinColumnWidth));
+ table->ColumnsGivenWidth += column->WidthGiven;
+ }
+
+ // [Part 5] Redistribute stretch remainder width due to rounding (remainder width is < 1.0f * number of Stretch column).
+ // Using right-to-left distribution (more likely to match resizing cursor).
+ if (width_remaining_for_stretched_columns >= 1.0f && !(table->Flags & ImGuiTableFlags_PreciseWidths))
+ for (int order_n = table->ColumnsCount - 1; stretch_sum_weights > 0.0f && width_remaining_for_stretched_columns >= 1.0f && order_n >= 0; order_n--)
+ {
+ if (!(table->EnabledMaskByDisplayOrder & ((ImU64)1 << order_n)))
+ continue;
+ ImGuiTableColumn* column = &table->Columns[table->DisplayOrderToIndex[order_n]];
+ if (!(column->Flags & ImGuiTableColumnFlags_WidthStretch))
+ continue;
+ column->WidthRequest += 1.0f;
+ column->WidthGiven += 1.0f;
+ width_remaining_for_stretched_columns -= 1.0f;
+ }
+
+ table->HoveredColumnBody = -1;
+ table->HoveredColumnBorder = -1;
+ const ImRect mouse_hit_rect(table->OuterRect.Min.x, table->OuterRect.Min.y, table->OuterRect.Max.x, ImMax(table->OuterRect.Max.y, table->OuterRect.Min.y + table->LastOuterHeight));
+ const bool is_hovering_table = ItemHoverable(mouse_hit_rect, 0);
+
+ // [Part 6] Setup final position, offset, skip/clip states and clipping rectangles, detect hovered column
+ // Process columns in their visible orders as we are comparing the visible order and adjusting host_clip_rect while looping.
+ int visible_n = 0;
+ bool offset_x_frozen = (table->FreezeColumnsCount > 0);
+ float offset_x = ((table->FreezeColumnsCount > 0) ? table->OuterRect.Min.x : work_rect.Min.x) + table->OuterPaddingX - table->CellSpacingX1;
+ ImRect host_clip_rect = table->InnerClipRect;
+ //host_clip_rect.Max.x += table->CellPaddingX + table->CellSpacingX2;
+ table->VisibleMaskByIndex = 0x00;
+ table->RequestOutputMaskByIndex = 0x00;
+ for (int order_n = 0; order_n < table->ColumnsCount; order_n++)
+ {
+ const int column_n = table->DisplayOrderToIndex[order_n];
+ ImGuiTableColumn* column = &table->Columns[column_n];
+
+ column->NavLayerCurrent = (ImS8)((table->FreezeRowsCount > 0 || column_n < table->FreezeColumnsCount) ? ImGuiNavLayer_Menu : ImGuiNavLayer_Main);
+
+ if (offset_x_frozen && table->FreezeColumnsCount == visible_n)
+ {
+ offset_x += work_rect.Min.x - table->OuterRect.Min.x;
+ offset_x_frozen = false;
+ }
+
+ // Clear status flags
+ column->Flags &= ~ImGuiTableColumnFlags_StatusMask_;
+
+ if ((table->EnabledMaskByDisplayOrder & ((ImU64)1 << order_n)) == 0)
+ {
+ // Hidden column: clear a few fields and we are done with it for the remainder of the function.
+ // We set a zero-width clip rect but set Min.y/Max.y properly to not interfere with the clipper.
+ column->MinX = column->MaxX = column->WorkMinX = column->ClipRect.Min.x = column->ClipRect.Max.x = offset_x;
+ column->WidthGiven = 0.0f;
+ column->ClipRect.Min.y = work_rect.Min.y;
+ column->ClipRect.Max.y = FLT_MAX;
+ column->ClipRect.ClipWithFull(host_clip_rect);
+ column->IsVisibleX = column->IsVisibleY = column->IsRequestOutput = false;
+ column->IsSkipItems = true;
+ column->ItemWidth = 1.0f;
+ continue;
+ }
+
+ // Detect hovered column
+ if (is_hovering_table && g.IO.MousePos.x >= column->ClipRect.Min.x && g.IO.MousePos.x < column->ClipRect.Max.x)
+ table->HoveredColumnBody = (ImGuiTableColumnIdx)column_n;
+
+ // Lock start position
+ column->MinX = offset_x;
+
+ // Lock width based on start position and minimum/maximum width for this position
+ float max_width = TableGetMaxColumnWidth(table, column_n);
+ column->WidthGiven = ImMin(column->WidthGiven, max_width);
+ column->WidthGiven = ImMax(column->WidthGiven, ImMin(column->WidthRequest, table->MinColumnWidth));
+ column->MaxX = offset_x + column->WidthGiven + table->CellSpacingX1 + table->CellSpacingX2 + table->CellPaddingX * 2.0f;
+
+ // Lock other positions
+ // - ClipRect.Min.x: Because merging draw commands doesn't compare min boundaries, we make ClipRect.Min.x match left bounds to be consistent regardless of merging.
+ // - ClipRect.Max.x: using WorkMaxX instead of MaxX (aka including padding) makes things more consistent when resizing down, tho slightly detrimental to visibility in very-small column.
+ // - ClipRect.Max.x: using MaxX makes it easier for header to receive hover highlight with no discontinuity and display sorting arrow.
+ // - FIXME-TABLE: We want equal width columns to have equal (ClipRect.Max.x - WorkMinX) width, which means ClipRect.max.x cannot stray off host_clip_rect.Max.x else right-most column may appear shorter.
+ column->WorkMinX = column->MinX + table->CellPaddingX + table->CellSpacingX1;
+ column->WorkMaxX = column->MaxX - table->CellPaddingX - table->CellSpacingX2; // Expected max
+ column->ItemWidth = ImFloor(column->WidthGiven * 0.65f);
+ column->ClipRect.Min.x = column->MinX;
+ column->ClipRect.Min.y = work_rect.Min.y;
+ column->ClipRect.Max.x = column->MaxX; //column->WorkMaxX;
+ column->ClipRect.Max.y = FLT_MAX;
+ column->ClipRect.ClipWithFull(host_clip_rect);
+
+ // Mark column as Clipped (not in sight)
+ // Note that scrolling tables (where inner_window != outer_window) handle Y clipped earlier in BeginTable() so IsVisibleY really only applies to non-scrolling tables.
+ // FIXME-TABLE: Because InnerClipRect.Max.y is conservatively ==outer_window->ClipRect.Max.y, we never can mark columns _Above_ the scroll line as not IsVisibleY.
+ // Taking advantage of LastOuterHeight would yield good results there...
+ // FIXME-TABLE: Y clipping is disabled because it effectively means not submitting will reduce contents width which is fed to outer_window->DC.CursorMaxPos.x,
+ // and this may be used (e.g. typically by outer_window using AlwaysAutoResize or outer_window's horizontal scrollbar, but could be something else).
+ // Possible solution to preserve last known content width for clipped column. Test 'table_reported_size' fails when enabling Y clipping and window is resized small.
+ column->IsVisibleX = (column->ClipRect.Max.x > column->ClipRect.Min.x);
+ column->IsVisibleY = true; // (column->ClipRect.Max.y > column->ClipRect.Min.y);
+ const bool is_visible = column->IsVisibleX; //&& column->IsVisibleY;
+ if (is_visible)
+ table->VisibleMaskByIndex |= ((ImU64)1 << column_n);
+
+ // Mark column as requesting output from user. Note that fixed + non-resizable sets are auto-fitting at all times and therefore always request output.
+ column->IsRequestOutput = is_visible || column->AutoFitQueue != 0 || column->CannotSkipItemsQueue != 0;
+ if (column->IsRequestOutput)
+ table->RequestOutputMaskByIndex |= ((ImU64)1 << column_n);
+
+ // Mark column as SkipItems (ignoring all items/layout)
+ column->IsSkipItems = !column->IsEnabled || table->HostSkipItems;
+ if (column->IsSkipItems)
+ IM_ASSERT(!is_visible);
+
+ // Update status flags
+ column->Flags |= ImGuiTableColumnFlags_IsEnabled;
+ if (is_visible)
+ column->Flags |= ImGuiTableColumnFlags_IsVisible;
+ if (column->SortOrder != -1)
+ column->Flags |= ImGuiTableColumnFlags_IsSorted;
+ if (table->HoveredColumnBody == column_n)
+ column->Flags |= ImGuiTableColumnFlags_IsHovered;
+
+ // Alignment
+ // FIXME-TABLE: This align based on the whole column width, not per-cell, and therefore isn't useful in
+ // many cases (to be able to honor this we might be able to store a log of cells width, per row, for
+ // visible rows, but nav/programmatic scroll would have visible artifacts.)
+ //if (column->Flags & ImGuiTableColumnFlags_AlignRight)
+ // column->WorkMinX = ImMax(column->WorkMinX, column->MaxX - column->ContentWidthRowsUnfrozen);
+ //else if (column->Flags & ImGuiTableColumnFlags_AlignCenter)
+ // column->WorkMinX = ImLerp(column->WorkMinX, ImMax(column->StartX, column->MaxX - column->ContentWidthRowsUnfrozen), 0.5f);
+
+ // Reset content width variables
+ column->ContentMaxXFrozen = column->ContentMaxXUnfrozen = column->WorkMinX;
+ column->ContentMaxXHeadersUsed = column->ContentMaxXHeadersIdeal = column->WorkMinX;
+
+ // Don't decrement auto-fit counters until container window got a chance to submit its items
+ if (table->HostSkipItems == false)
+ {
+ column->AutoFitQueue >>= 1;
+ column->CannotSkipItemsQueue >>= 1;
+ }
+
+ if (visible_n < table->FreezeColumnsCount)
+ host_clip_rect.Min.x = ImClamp(column->MaxX + TABLE_BORDER_SIZE, host_clip_rect.Min.x, host_clip_rect.Max.x);
+
+ offset_x += column->WidthGiven + table->CellSpacingX1 + table->CellSpacingX2 + table->CellPaddingX * 2.0f;
+ visible_n++;
+ }
+
+ // [Part 7] Detect/store when we are hovering the unused space after the right-most column (so e.g. context menus can react on it)
+ // Clear Resizable flag if none of our column are actually resizable (either via an explicit _NoResize flag, either
+ // because of using _WidthAuto/_WidthStretch). This will hide the resizing option from the context menu.
+ const float unused_x1 = ImMax(table->WorkRect.Min.x, table->Columns[table->RightMostEnabledColumn].ClipRect.Max.x);
+ if (is_hovering_table && table->HoveredColumnBody == -1)
+ {
+ if (g.IO.MousePos.x >= unused_x1)
+ table->HoveredColumnBody = (ImGuiTableColumnIdx)table->ColumnsCount;
+ }
+ if (has_resizable == false && (table->Flags & ImGuiTableFlags_Resizable))
+ table->Flags &= ~ImGuiTableFlags_Resizable;
+
+ // [Part 8] Lock actual OuterRect/WorkRect right-most position.
+ // This is done late to handle the case of fixed-columns tables not claiming more widths that they need.
+ // Because of this we are careful with uses of WorkRect and InnerClipRect before this point.
+ if (table->RightMostStretchedColumn != -1)
+ table->Flags &= ~ImGuiTableFlags_NoHostExtendX;
+ if (table->Flags & ImGuiTableFlags_NoHostExtendX)
+ {
+ table->OuterRect.Max.x = table->WorkRect.Max.x = unused_x1;
+ table->InnerClipRect.Max.x = ImMin(table->InnerClipRect.Max.x, unused_x1);
+ }
+ table->InnerWindow->ParentWorkRect = table->WorkRect;
+ table->BorderX1 = table->InnerClipRect.Min.x;// +((table->Flags & ImGuiTableFlags_BordersOuter) ? 0.0f : -1.0f);
+ table->BorderX2 = table->InnerClipRect.Max.x;// +((table->Flags & ImGuiTableFlags_BordersOuter) ? 0.0f : +1.0f);
+
+ // [Part 9] Allocate draw channels and setup background cliprect
+ TableSetupDrawChannels(table);
+
+ // [Part 10] Hit testing on borders
+ if (table->Flags & ImGuiTableFlags_Resizable)
+ TableUpdateBorders(table);
+ table->LastFirstRowHeight = 0.0f;
+ table->IsLayoutLocked = true;
+ table->IsUsingHeaders = false;
+
+ // [Part 11] Context menu
+ if (table->IsContextPopupOpen && table->InstanceCurrent == table->InstanceInteracted)
+ {
+ const ImGuiID context_menu_id = ImHashStr("##ContextMenu", 0, table->ID);
+ if (BeginPopupEx(context_menu_id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings))
+ {
+ TableDrawContextMenu(table);
+ EndPopup();
+ }
+ else
+ {
+ table->IsContextPopupOpen = false;
+ }
+ }
+
+ // [Part 13] Sanitize and build sort specs before we have a change to use them for display.
+ // This path will only be exercised when sort specs are modified before header rows (e.g. init or visibility change)
+ if (table->IsSortSpecsDirty && (table->Flags & ImGuiTableFlags_Sortable))
+ TableSortSpecsBuild(table);
+
+ // Initial state
+ ImGuiWindow* inner_window = table->InnerWindow;
+ if (table->Flags & ImGuiTableFlags_NoClip)
+ table->DrawSplitter.SetCurrentChannel(inner_window->DrawList, TABLE_DRAW_CHANNEL_NOCLIP);
+ else
+ inner_window->DrawList->PushClipRect(inner_window->ClipRect.Min, inner_window->ClipRect.Max, false);
+}
+
+// Process hit-testing on resizing borders. Actual size change will be applied in EndTable()
+// - Set table->HoveredColumnBorder with a short delay/timer to reduce feedback noise
+// - Submit ahead of table contents and header, use ImGuiButtonFlags_AllowItemOverlap to prioritize widgets
+// overlapping the same area.
+void ImGui::TableUpdateBorders(ImGuiTable* table)
+{
+ ImGuiContext& g = *GImGui;
+ IM_ASSERT(table->Flags & ImGuiTableFlags_Resizable);
+
+ // At this point OuterRect height may be zero or under actual final height, so we rely on temporal coherency and
+ // use the final height from last frame. Because this is only affecting _interaction_ with columns, it is not
+ // really problematic (whereas the actual visual will be displayed in EndTable() and using the current frame height).
+ // Actual columns highlight/render will be performed in EndTable() and not be affected.
+ const float hit_half_width = TABLE_RESIZE_SEPARATOR_HALF_THICKNESS;
+ const float hit_y1 = table->OuterRect.Min.y;
+ const float hit_y2_body = ImMax(table->OuterRect.Max.y, hit_y1 + table->LastOuterHeight);
+ const float hit_y2_head = hit_y1 + table->LastFirstRowHeight;
+
+ for (int order_n = 0; order_n < table->ColumnsCount; order_n++)
+ {
+ if (!(table->EnabledMaskByDisplayOrder & ((ImU64)1 << order_n)))
+ continue;
+
+ const int column_n = table->DisplayOrderToIndex[order_n];
+ ImGuiTableColumn* column = &table->Columns[column_n];
+ if (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_))
+ continue;
+
+ // ImGuiTableFlags_NoBordersInBodyUntilResize will be honored in TableDrawBorders()
+ const float border_y2_hit = (table->Flags & ImGuiTableFlags_NoBordersInBody) ? hit_y2_head : hit_y2_body;
+ if ((table->Flags & ImGuiTableFlags_NoBordersInBody) && table->IsUsingHeaders == false)
+ continue;
+
+ if (table->FreezeColumnsCount > 0)
+ if (column->MaxX < table->Columns[table->DisplayOrderToIndex[table->FreezeColumnsCount - 1]].MaxX)
+ continue;
+
+ ImGuiID column_id = TableGetColumnResizeID(table, column_n, table->InstanceCurrent);
+ ImRect hit_rect(column->MaxX - hit_half_width, hit_y1, column->MaxX + hit_half_width, border_y2_hit);
+ //GetForegroundDrawList()->AddRect(hit_rect.Min, hit_rect.Max, IM_COL32(255, 0, 0, 100));
+ KeepAliveID(column_id);
+
+ bool hovered = false, held = false;
+ bool pressed = ButtonBehavior(hit_rect, column_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_AllowItemOverlap | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnDoubleClick);
+ if (pressed && IsMouseDoubleClicked(0))
+ {
+ TableSetColumnWidthAutoSingle(table, column_n);
+ ClearActiveID();
+ held = hovered = false;
+ }
+ if (held)
+ {
+ if (table->LastResizedColumn == -1)
+ table->ResizeLockMinContentsX2 = table->RightMostEnabledColumn != -1 ? table->Columns[table->RightMostEnabledColumn].MaxX : -FLT_MAX;
+ table->ResizedColumn = (ImGuiTableColumnIdx)column_n;
+ table->InstanceInteracted = table->InstanceCurrent;
+ }
+ if ((hovered && g.HoveredIdTimer > TABLE_RESIZE_SEPARATOR_FEEDBACK_TIMER) || held)
+ {
+ table->HoveredColumnBorder = (ImGuiTableColumnIdx)column_n;
+ SetMouseCursor(ImGuiMouseCursor_ResizeEW);
+ }
+ }
+}
+
+void ImGui::EndTable()
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiTable* table = g.CurrentTable;
+ IM_ASSERT(table != NULL && "Only call EndTable() if BeginTable() returns true!");
+
+ // This assert would be very useful to catch a common error... unfortunately it would probably trigger in some
+ // cases, and for consistency user may sometimes output empty tables (and still benefit from e.g. outer border)
+ //IM_ASSERT(table->IsLayoutLocked && "Table unused: never called TableNextRow(), is that the intent?");
+
+ // If the user never got to call TableNextRow() or TableNextColumn(), we call layout ourselves to ensure all our
+ // code paths are consistent (instead of just hoping that TableBegin/TableEnd will work), get borders drawn, etc.
+ if (!table->IsLayoutLocked)
+ TableUpdateLayout(table);
+
+ const ImGuiTableFlags flags = table->Flags;
+ ImGuiWindow* inner_window = table->InnerWindow;
+ ImGuiWindow* outer_window = table->OuterWindow;
+ IM_ASSERT(inner_window == g.CurrentWindow);
+ IM_ASSERT(outer_window == inner_window || outer_window == inner_window->ParentWindow);
+
+ if (table->IsInsideRow)
+ TableEndRow(table);
+
+ // Context menu in columns body
+ if (flags & ImGuiTableFlags_ContextMenuInBody)
+ if (table->HoveredColumnBody != -1 && !IsAnyItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
+ TableOpenContextMenu((int)table->HoveredColumnBody);
+
+ // Finalize table height
+ inner_window->DC.PrevLineSize = table->HostBackupPrevLineSize;
+ inner_window->DC.CurrLineSize = table->HostBackupCurrLineSize;
+ inner_window->DC.CursorMaxPos = table->HostBackupCursorMaxPos;
+ const float inner_content_max_y = table->RowPosY2;
+ IM_ASSERT(table->RowPosY2 == inner_window->DC.CursorPos.y);
+ if (inner_window != outer_window)
+ inner_window->DC.CursorMaxPos.y = inner_content_max_y;
+ else if (!(flags & ImGuiTableFlags_NoHostExtendY))
+ table->OuterRect.Max.y = table->InnerRect.Max.y = ImMax(table->OuterRect.Max.y, inner_content_max_y); // Patch OuterRect/InnerRect height
+ table->WorkRect.Max.y = ImMax(table->WorkRect.Max.y, table->OuterRect.Max.y);
+ table->LastOuterHeight = table->OuterRect.GetHeight();
+
+ // Setup inner scrolling range
+ // FIXME: This ideally should be done earlier, in BeginTable() SetNextWindowContentSize call, just like writing to inner_window->DC.CursorMaxPos.y,
+ // but since the later is likely to be impossible to do we'd rather update both axises together.
+ if (table->Flags & ImGuiTableFlags_ScrollX)
+ {
+ const float outer_padding_for_border = (table->Flags & ImGuiTableFlags_BordersOuterV) ? TABLE_BORDER_SIZE : 0.0f;
+ float max_pos_x = table->InnerWindow->DC.CursorMaxPos.x;
+ if (table->RightMostEnabledColumn != -1)
+ max_pos_x = ImMax(max_pos_x, table->Columns[table->RightMostEnabledColumn].WorkMaxX + table->CellPaddingX + table->OuterPaddingX - outer_padding_for_border);
+ if (table->ResizedColumn != -1)
+ max_pos_x = ImMax(max_pos_x, table->ResizeLockMinContentsX2);
+ table->InnerWindow->DC.CursorMaxPos.x = max_pos_x;
+ }
+
+ // Pop clipping rect
+ if (!(flags & ImGuiTableFlags_NoClip))
+ inner_window->DrawList->PopClipRect();
+ inner_window->ClipRect = inner_window->DrawList->_ClipRectStack.back();
+
+ // Draw borders
+ if ((flags & ImGuiTableFlags_Borders) != 0)
+ TableDrawBorders(table);
+
+#if 0
+ // Strip out dummy channel draw calls
+ // We have no way to prevent user submitting direct ImDrawList calls into a hidden column (but ImGui:: calls will be clipped out)
+ // Pros: remove draw calls which will have no effect. since they'll have zero-size cliprect they may be early out anyway.
+ // Cons: making it harder for users watching metrics/debugger to spot the wasted vertices.
+ if (table->DummyDrawChannel != (ImGuiTableColumnIdx)-1)
+ {
+ ImDrawChannel* dummy_channel = &table->DrawSplitter._Channels[table->DummyDrawChannel];
+ dummy_channel->_CmdBuffer.resize(0);
+ dummy_channel->_IdxBuffer.resize(0);
+ }
+#endif
+
+ // Flatten channels and merge draw calls
+ table->DrawSplitter.SetCurrentChannel(inner_window->DrawList, 0);
+ if ((table->Flags & ImGuiTableFlags_NoClip) == 0)
+ TableMergeDrawChannels(table);
+ table->DrawSplitter.Merge(inner_window->DrawList);
+
+ // Update ColumnsAutoFitWidth to get us ahead for host using our size to auto-resize without waiting for next BeginTable()
+ const float width_spacings = (table->OuterPaddingX * 2.0f) + (table->CellSpacingX1 + table->CellSpacingX2) * (table->ColumnsEnabledCount - 1);
+ table->ColumnsAutoFitWidth = width_spacings + (table->CellPaddingX * 2.0f) * table->ColumnsEnabledCount;
+ for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
+ if (table->EnabledMaskByIndex & ((ImU64)1 << column_n))
+ {
+ ImGuiTableColumn* column = &table->Columns[column_n];
+ if ((column->Flags & ImGuiTableColumnFlags_WidthFixed) && !(column->Flags & ImGuiTableColumnFlags_NoResize))
+ table->ColumnsAutoFitWidth += column->WidthRequest;
+ else
+ table->ColumnsAutoFitWidth += TableGetColumnWidthAuto(table, column);
+ }
+
+ // Update scroll
+ if ((table->Flags & ImGuiTableFlags_ScrollX) == 0 && inner_window != outer_window)
+ {
+ inner_window->Scroll.x = 0.0f;
+ }
+ else if (table->LastResizedColumn != -1 && table->ResizedColumn == -1 && inner_window->ScrollbarX && table->InstanceInteracted == table->InstanceCurrent)
+ {
+ // When releasing a column being resized, scroll to keep the resulting column in sight
+ const float neighbor_width_to_keep_visible = table->MinColumnWidth + table->CellPaddingX * 2.0f;
+ ImGuiTableColumn* column = &table->Columns[table->LastResizedColumn];
+ if (column->MaxX < table->InnerClipRect.Min.x)
+ SetScrollFromPosX(inner_window, column->MaxX - inner_window->Pos.x - neighbor_width_to_keep_visible, 1.0f);
+ else if (column->MaxX > table->InnerClipRect.Max.x)
+ SetScrollFromPosX(inner_window, column->MaxX - inner_window->Pos.x + neighbor_width_to_keep_visible, 1.0f);
+ }
+
+ // Apply resizing/dragging at the end of the frame
+ if (table->ResizedColumn != -1 && table->InstanceCurrent == table->InstanceInteracted)
+ {
+ ImGuiTableColumn* column = &table->Columns[table->ResizedColumn];
+ const float new_x2 = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + TABLE_RESIZE_SEPARATOR_HALF_THICKNESS);
+ const float new_width = ImFloor(new_x2 - column->MinX - table->CellSpacingX1 - table->CellPaddingX * 2.0f);
+ table->ResizedColumnNextWidth = new_width;
+ }
+
+ // Pop from id stack
+ IM_ASSERT_USER_ERROR(inner_window->IDStack.back() == table->ID + table->InstanceCurrent, "Mismatching PushID/PopID!");
+ IM_ASSERT_USER_ERROR(outer_window->DC.ItemWidthStack.Size >= table->HostBackupItemWidthStackSize, "Too many PopItemWidth!");
+ PopID();
+
+ // Restore window data that we modified
+ const ImVec2 backup_outer_max_pos = outer_window->DC.CursorMaxPos;
+ inner_window->WorkRect = table->HostBackupWorkRect;
+ inner_window->ParentWorkRect = table->HostBackupParentWorkRect;
+ inner_window->SkipItems = table->HostSkipItems;
+ outer_window->DC.CursorPos = table->OuterRect.Min;
+ outer_window->DC.ItemWidth = table->HostBackupItemWidth;
+ outer_window->DC.ItemWidthStack.Size = table->HostBackupItemWidthStackSize;
+ outer_window->DC.ColumnsOffset = table->HostBackupColumnsOffset;
+
+ // Layout in outer window
+ // (FIXME: To allow auto-fit and allow desirable effect of SameLine() we dissociate 'used' vs 'ideal' size by overriding
+ // CursorPosPrevLine and CursorMaxPos manually. That should be a more general layout feature, see same problem e.g. #3414)
+ if (inner_window != outer_window)
+ {
+ EndChild();
+ }
+ else
+ {
+ ItemSize(table->OuterRect.GetSize());
+ ItemAdd(table->OuterRect, 0);
+ }
+
+ // Override declared contents width/height to enable auto-resize while not needlessly adding a scrollbar
+ if (table->Flags & ImGuiTableFlags_NoHostExtendX)
+ {
+ // FIXME-TABLE: Could we remove this section?
+ // ColumnsAutoFitWidth may be one frame ahead here since for Fixed+NoResize is calculated from latest contents
+ IM_ASSERT((table->Flags & ImGuiTableFlags_ScrollX) == 0);
+ outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth);
+ }
+ else if (table->UserOuterSize.x <= 0.0f)
+ {
+ const float decoration_size = (table->Flags & ImGuiTableFlags_ScrollX) ? inner_window->ScrollbarSizes.x : 0.0f;
+ outer_window->DC.IdealMaxPos.x = ImMax(outer_window->DC.IdealMaxPos.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth + decoration_size - table->UserOuterSize.x);
+ outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, ImMin(table->OuterRect.Max.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth));
+ }
+ else
+ {
+ outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table->OuterRect.Max.x);
+ }
+ if (table->UserOuterSize.y <= 0.0f)
+ {
+ const float decoration_size = (table->Flags & ImGuiTableFlags_ScrollY) ? inner_window->ScrollbarSizes.y : 0.0f;
+ outer_window->DC.IdealMaxPos.y = ImMax(outer_window->DC.IdealMaxPos.y, inner_content_max_y + decoration_size - table->UserOuterSize.y);
+ outer_window->DC.CursorMaxPos.y = ImMax(backup_outer_max_pos.y, ImMin(table->OuterRect.Max.y, inner_content_max_y));
+ }
+ else
+ {
+ // OuterRect.Max.y may already have been pushed downward from the initial value (unless ImGuiTableFlags_NoHostExtendY is set)
+ outer_window->DC.CursorMaxPos.y = ImMax(backup_outer_max_pos.y, table->OuterRect.Max.y);
+ }
+
+ // Save settings
+ if (table->IsSettingsDirty)
+ TableSaveSettings(table);
+ table->IsInitializing = false;
+
+ // Clear or restore current table, if any
+ IM_ASSERT(g.CurrentWindow == outer_window && g.CurrentTable == table);
+ g.CurrentTableStack.pop_back();
+ g.CurrentTable = g.CurrentTableStack.Size ? g.Tables.GetByIndex(g.CurrentTableStack.back().Index) : NULL;
+ outer_window->DC.CurrentTableIdx = g.CurrentTable ? g.Tables.GetIndex(g.CurrentTable) : -1;
+}
+
+// See "COLUMN SIZING POLICIES" comments at the top of this file
+// If (init_width_or_weight <= 0.0f) it is ignored
+void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, float init_width_or_weight, ImGuiID user_id)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiTable* table = g.CurrentTable;
+ IM_ASSERT(table != NULL && "Need to call TableSetupColumn() after BeginTable()!");
+ IM_ASSERT(table->IsLayoutLocked == false && "Need to call call TableSetupColumn() before first row!");
+ IM_ASSERT((flags & ImGuiTableColumnFlags_StatusMask_) == 0 && "Illegal to pass StatusMask values to TableSetupColumn()");
+ if (table->DeclColumnsCount >= table->ColumnsCount)
+ {
+ IM_ASSERT_USER_ERROR(table->DeclColumnsCount < table->ColumnsCount, "Called TableSetupColumn() too many times!");
+ return;
+ }
+
+ ImGuiTableColumn* column = &table->Columns[table->DeclColumnsCount];
+ table->DeclColumnsCount++;
+
+ // Assert when passing a width or weight if policy is entirely left to default, to avoid storing width into weight and vice-versa.
+ // Give a grace to users of ImGuiTableFlags_ScrollX.
+ if (table->IsDefaultSizingPolicy && (flags & ImGuiTableColumnFlags_WidthMask_) == 0 && (flags & ImGuiTableFlags_ScrollX) == 0)
+ IM_ASSERT(init_width_or_weight <= 0.0f && "Can only specify width/weight if sizing policy is set explicitely in either Table or Column.");
+
+ // When passing a width automatically enforce WidthFixed policy
+ // (whereas TableSetupColumnFlags would default to WidthAuto if table is not Resizable)
+ if ((flags & ImGuiTableColumnFlags_WidthMask_) == 0 && init_width_or_weight > 0.0f)
+ if ((table->Flags & ImGuiTableFlags_SizingMask_) == ImGuiTableFlags_SizingFixedFit || (table->Flags & ImGuiTableFlags_SizingMask_) == ImGuiTableFlags_SizingFixedSame)
+ flags |= ImGuiTableColumnFlags_WidthFixed;
+
+ TableSetupColumnFlags(table, column, flags);
+ column->UserID = user_id;
+ flags = column->Flags;
+
+ // Initialize defaults
+ column->InitStretchWeightOrWidth = init_width_or_weight;
+ if (table->IsInitializing)
+ {
+ // Init width or weight
+ if (column->WidthRequest < 0.0f && column->StretchWeight < 0.0f)
+ {
+ if ((flags & ImGuiTableColumnFlags_WidthFixed) && init_width_or_weight > 0.0f)
+ column->WidthRequest = init_width_or_weight;
+ if (flags & ImGuiTableColumnFlags_WidthStretch)
+ column->StretchWeight = (init_width_or_weight > 0.0f) ? init_width_or_weight : -1.0f;
+
+ // Disable auto-fit if an explicit width/weight has been specified
+ if (init_width_or_weight > 0.0f)
+ column->AutoFitQueue = 0x00;
+ }
+
+ // Init default visibility/sort state
+ if ((flags & ImGuiTableColumnFlags_DefaultHide) && (table->SettingsLoadedFlags & ImGuiTableFlags_Hideable) == 0)
+ column->IsEnabled = column->IsEnabledNextFrame = false;
+ if (flags & ImGuiTableColumnFlags_DefaultSort && (table->SettingsLoadedFlags & ImGuiTableFlags_Sortable) == 0)
+ {
+ column->SortOrder = 0; // Multiple columns using _DefaultSort will be reassigned unique SortOrder values when building the sort specs.
+ column->SortDirection = (column->Flags & ImGuiTableColumnFlags_PreferSortDescending) ? (ImS8)ImGuiSortDirection_Descending : (ImU8)(ImGuiSortDirection_Ascending);
+ }
+ }
+
+ // Store name (append with zero-terminator in contiguous buffer)
+ column->NameOffset = -1;
+ if (label != NULL && label[0] != 0)
+ {
+ column->NameOffset = (ImS16)table->ColumnsNames.size();
+ table->ColumnsNames.append(label, label + strlen(label) + 1);
+ }
+}
+
+// [Public]
+void ImGui::TableSetupScrollFreeze(int columns, int rows)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiTable* table = g.CurrentTable;
+ IM_ASSERT(table != NULL && "Need to call TableSetupColumn() after BeginTable()!");
+ IM_ASSERT(table->IsLayoutLocked == false && "Need to call TableSetupColumn() before first row!");
+ IM_ASSERT(columns >= 0 && columns < IMGUI_TABLE_MAX_COLUMNS);
+ IM_ASSERT(rows >= 0 && rows < 128); // Arbitrary limit
+
+ table->FreezeColumnsRequest = (table->Flags & ImGuiTableFlags_ScrollX) ? (ImGuiTableColumnIdx)columns : 0;
+ table->FreezeColumnsCount = (table->InnerWindow->Scroll.x != 0.0f) ? table->FreezeColumnsRequest : 0;
+ table->FreezeRowsRequest = (table->Flags & ImGuiTableFlags_ScrollY) ? (ImGuiTableColumnIdx)rows : 0;
+ table->FreezeRowsCount = (table->InnerWindow->Scroll.y != 0.0f) ? table->FreezeRowsRequest : 0;
+ table->IsUnfrozenRows = (table->FreezeRowsCount == 0); // Make sure this is set before TableUpdateLayout() so ImGuiListClipper can benefit from it.b
+}
+
+int ImGui::TableGetColumnCount()
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiTable* table = g.CurrentTable;
+ return table ? table->ColumnsCount : 0;
+}
+
+const char* ImGui::TableGetColumnName(int column_n)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiTable* table = g.CurrentTable;
+ if (!table)
+ return NULL;
+ if (column_n < 0)
+ column_n = table->CurrentColumn;
+ return TableGetColumnName(table, column_n);
+}
+
+const char* ImGui::TableGetColumnName(const ImGuiTable* table, int column_n)
+{
+ if (table->IsLayoutLocked == false && column_n >= table->DeclColumnsCount)
+ return ""; // NameOffset is invalid at this point
+ const ImGuiTableColumn* column = &table->Columns[column_n];
+ if (column->NameOffset == -1)
+ return "";
+ return &table->ColumnsNames.Buf[column->NameOffset];
+}
+
+// We allow querying for an extra column in order to poll the IsHovered state of the right-most section
+ImGuiTableColumnFlags ImGui::TableGetColumnFlags(int column_n)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiTable* table = g.CurrentTable;
+ if (!table)
+ return ImGuiTableColumnFlags_None;
+ if (column_n < 0)
+ column_n = table->CurrentColumn;
+ if (column_n == table->ColumnsCount)
+ return (table->HoveredColumnBody == column_n) ? ImGuiTableColumnFlags_IsHovered : ImGuiTableColumnFlags_None;
+ return table->Columns[column_n].Flags;
+}
+
+// Return the cell rectangle based on currently known height.
+// - Important: we generally don't know our row height until the end of the row, so Max.y will be incorrect in many situations.
+// The only case where this is correct is if we provided a min_row_height to TableNextRow() and don't go below it.
+// - Important: if ImGuiTableFlags_PadOuterX is set but ImGuiTableFlags_PadInnerX is not set, the outer-most left and right
+// columns report a small offset so their CellBgRect can extend up to the outer border.
+ImRect ImGui::TableGetCellBgRect(const ImGuiTable* table, int column_n)
+{
+ const ImGuiTableColumn* column = &table->Columns[column_n];
+ float x1 = column->MinX;
+ float x2 = column->MaxX;
+ if (column->PrevEnabledColumn == -1)
+ x1 -= table->CellSpacingX1;
+ if (column->NextEnabledColumn == -1)
+ x2 += table->CellSpacingX2;
+ return ImRect(x1, table->RowPosY1, x2, table->RowPosY2);
+}
+
+// Return the resizing ID for the right-side of the given column.
+ImGuiID ImGui::TableGetColumnResizeID(const ImGuiTable* table, int column_n, int instance_no)
+{
+ IM_ASSERT(column_n >= 0 && column_n < table->ColumnsCount);
+ ImGuiID id = table->ID + 1 + (instance_no * table->ColumnsCount) + column_n;
+ return id;
+}
+
+// Return -1 when table is not hovered. return columns_count if the unused space at the right of visible columns is hovered.
+int ImGui::TableGetHoveredColumn()
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiTable* table = g.CurrentTable;
+ if (!table)
+ return -1;
+ return (int)table->HoveredColumnBody;
+}
+
+void ImGui::TableSetBgColor(ImGuiTableBgTarget target, ImU32 color, int column_n)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiTable* table = g.CurrentTable;
+ IM_ASSERT(target != ImGuiTableBgTarget_None);
+
+ if (color == IM_COL32_DISABLE)
+ color = 0;
+
+ // We cannot draw neither the cell or row background immediately as we don't know the row height at this point in time.
+ switch (target)
+ {
+ case ImGuiTableBgTarget_CellBg:
+ {
+ if (table->RowPosY1 > table->InnerClipRect.Max.y) // Discard
+ return;
+ if (column_n == -1)
+ column_n = table->CurrentColumn;
+ if ((table->VisibleMaskByIndex & ((ImU64)1 << column_n)) == 0)
+ return;
+ if (table->RowCellDataCurrent < 0 || table->RowCellData[table->RowCellDataCurrent].Column != column_n)
+ table->RowCellDataCurrent++;
+ ImGuiTableCellData* cell_data = &table->RowCellData[table->RowCellDataCurrent];
+ cell_data->BgColor = color;
+ cell_data->Column = (ImGuiTableColumnIdx)column_n;
+ break;
+ }
+ case ImGuiTableBgTarget_RowBg0:
+ case ImGuiTableBgTarget_RowBg1:
+ {
+ if (table->RowPosY1 > table->InnerClipRect.Max.y) // Discard
+ return;
+ IM_ASSERT(column_n == -1);
+ int bg_idx = (target == ImGuiTableBgTarget_RowBg1) ? 1 : 0;
+ table->RowBgColor[bg_idx] = color;
+ break;
+ }
+ default:
+ IM_ASSERT(0);
+ }
+}
+
+//-------------------------------------------------------------------------
+// [SECTION] Tables: Row changes
+//-------------------------------------------------------------------------
+// - TableGetRowIndex()
+// - TableNextRow()
+// - TableBeginRow() [Internal]
+// - TableEndRow() [Internal]
+//-------------------------------------------------------------------------
+
+// [Public] Note: for row coloring we use ->RowBgColorCounter which is the same value without counting header rows
+int ImGui::TableGetRowIndex()
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiTable* table = g.CurrentTable;
+ if (!table)
+ return 0;
+ return table->CurrentRow;
+}
+
+// [Public] Starts into the first cell of a new row
+void ImGui::TableNextRow(ImGuiTableRowFlags row_flags, float row_min_height)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiTable* table = g.CurrentTable;
+
+ if (!table->IsLayoutLocked)
+ TableUpdateLayout(table);
+ if (table->IsInsideRow)
+ TableEndRow(table);
+
+ table->LastRowFlags = table->RowFlags;
+ table->RowFlags = row_flags;
+ table->RowMinHeight = row_min_height;
+ TableBeginRow(table);
+
+ // We honor min_row_height requested by user, but cannot guarantee per-row maximum height,
+ // because that would essentially require a unique clipping rectangle per-cell.
+ table->RowPosY2 += table->CellPaddingY * 2.0f;
+ table->RowPosY2 = ImMax(table->RowPosY2, table->RowPosY1 + row_min_height);
+
+ // Disable output until user calls TableNextColumn()
+ table->InnerWindow->SkipItems = true;
+}
+
+// [Internal] Called by TableNextRow()
+void ImGui::TableBeginRow(ImGuiTable* table)
+{
+ ImGuiWindow* window = table->InnerWindow;
+ IM_ASSERT(!table->IsInsideRow);
+
+ // New row
+ table->CurrentRow++;
+ table->CurrentColumn = -1;
+ table->RowBgColor[0] = table->RowBgColor[1] = IM_COL32_DISABLE;
+ table->RowCellDataCurrent = -1;
+ table->IsInsideRow = true;
+
+ // Begin frozen rows
+ float next_y1 = table->RowPosY2;
+ if (table->CurrentRow == 0 && table->FreezeRowsCount > 0)
+ next_y1 = window->DC.CursorPos.y = table->OuterRect.Min.y;
+
+ table->RowPosY1 = table->RowPosY2 = next_y1;
+ table->RowTextBaseline = 0.0f;
+ table->RowIndentOffsetX = window->DC.Indent.x - table->HostIndentX; // Lock indent
+ window->DC.PrevLineTextBaseOffset = 0.0f;
+ window->DC.CursorMaxPos.y = next_y1;
+
+ // Making the header BG color non-transparent will allow us to overlay it multiple times when handling smooth dragging.
+ if (table->RowFlags & ImGuiTableRowFlags_Headers)
+ {
+ TableSetBgColor(ImGuiTableBgTarget_RowBg0, GetColorU32(ImGuiCol_TableHeaderBg));
+ if (table->CurrentRow == 0)
+ table->IsUsingHeaders = true;
+ }
+}
+
+// [Internal] Called by TableNextRow()
+void ImGui::TableEndRow(ImGuiTable* table)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ IM_ASSERT(window == table->InnerWindow);
+ IM_ASSERT(table->IsInsideRow);
+
+ if (table->CurrentColumn != -1)
+ TableEndCell(table);
+
+ // Position cursor at the bottom of our row so it can be used for e.g. clipping calculation. However it is
+ // likely that the next call to TableBeginCell() will reposition the cursor to take account of vertical padding.
+ window->DC.CursorPos.y = table->RowPosY2;
+
+ // Row background fill
+ const float bg_y1 = table->RowPosY1;
+ const float bg_y2 = table->RowPosY2;
+ const bool unfreeze_rows_actual = (table->CurrentRow + 1 == table->FreezeRowsCount);
+ const bool unfreeze_rows_request = (table->CurrentRow + 1 == table->FreezeRowsRequest);
+ if (table->CurrentRow == 0)
+ table->LastFirstRowHeight = bg_y2 - bg_y1;
+
+ const bool is_visible = (bg_y2 >= table->InnerClipRect.Min.y && bg_y1 <= table->InnerClipRect.Max.y);
+ if (is_visible)
+ {
+ // Decide of background color for the row
+ ImU32 bg_col0 = 0;
+ ImU32 bg_col1 = 0;
+ if (table->RowBgColor[0] != IM_COL32_DISABLE)
+ bg_col0 = table->RowBgColor[0];
+ else if (table->Flags & ImGuiTableFlags_RowBg)
+ bg_col0 = GetColorU32((table->RowBgColorCounter & 1) ? ImGuiCol_TableRowBgAlt : ImGuiCol_TableRowBg);
+ if (table->RowBgColor[1] != IM_COL32_DISABLE)
+ bg_col1 = table->RowBgColor[1];
+
+ // Decide of top border color
+ ImU32 border_col = 0;
+ const float border_size = TABLE_BORDER_SIZE;
+ if (table->CurrentRow > 0 || table->InnerWindow == table->OuterWindow)
+ if (table->Flags & ImGuiTableFlags_BordersInnerH)
+ border_col = (table->LastRowFlags & ImGuiTableRowFlags_Headers) ? table->BorderColorStrong : table->BorderColorLight;
+
+ const bool draw_cell_bg_color = table->RowCellDataCurrent >= 0;
+ const bool draw_strong_bottom_border = unfreeze_rows_actual;
+ if ((bg_col0 | bg_col1 | border_col) != 0 || draw_strong_bottom_border || draw_cell_bg_color)
+ {
+ // In theory we could call SetWindowClipRectBeforeSetChannel() but since we know TableEndRow() is
+ // always followed by a change of clipping rectangle we perform the smallest overwrite possible here.
+ if ((table->Flags & ImGuiTableFlags_NoClip) == 0)
+ window->DrawList->_CmdHeader.ClipRect = table->Bg0ClipRectForDrawCmd.ToVec4();
+ table->DrawSplitter.SetCurrentChannel(window->DrawList, TABLE_DRAW_CHANNEL_BG0);
+ }
+
+ // Draw row background
+ // We soft/cpu clip this so all backgrounds and borders can share the same clipping rectangle
+ if (bg_col0 || bg_col1)
+ {
+ ImRect row_rect(table->WorkRect.Min.x, bg_y1, table->WorkRect.Max.x, bg_y2);
+ row_rect.ClipWith(table->BgClipRect);
+ if (bg_col0 != 0 && row_rect.Min.y < row_rect.Max.y)
+ window->DrawList->AddRectFilled(row_rect.Min, row_rect.Max, bg_col0);
+ if (bg_col1 != 0 && row_rect.Min.y < row_rect.Max.y)
+ window->DrawList->AddRectFilled(row_rect.Min, row_rect.Max, bg_col1);
+ }
+
+ // Draw cell background color
+ if (draw_cell_bg_color)
+ {
+ ImGuiTableCellData* cell_data_end = &table->RowCellData[table->RowCellDataCurrent];
+ for (ImGuiTableCellData* cell_data = &table->RowCellData[0]; cell_data <= cell_data_end; cell_data++)
+ {
+ const ImGuiTableColumn* column = &table->Columns[cell_data->Column];
+ ImRect cell_bg_rect = TableGetCellBgRect(table, cell_data->Column);
+ cell_bg_rect.ClipWith(table->BgClipRect);
+ cell_bg_rect.Min.x = ImMax(cell_bg_rect.Min.x, column->ClipRect.Min.x); // So that first column after frozen one gets clipped
+ cell_bg_rect.Max.x = ImMin(cell_bg_rect.Max.x, column->MaxX);
+ window->DrawList->AddRectFilled(cell_bg_rect.Min, cell_bg_rect.Max, cell_data->BgColor);
+ }
+ }
+
+ // Draw top border
+ if (border_col && bg_y1 >= table->BgClipRect.Min.y && bg_y1 < table->BgClipRect.Max.y)
+ window->DrawList->AddLine(ImVec2(table->BorderX1, bg_y1), ImVec2(table->BorderX2, bg_y1), border_col, border_size);
+
+ // Draw bottom border at the row unfreezing mark (always strong)
+ if (draw_strong_bottom_border && bg_y2 >= table->BgClipRect.Min.y && bg_y2 < table->BgClipRect.Max.y)
+ window->DrawList->AddLine(ImVec2(table->BorderX1, bg_y2), ImVec2(table->BorderX2, bg_y2), table->BorderColorStrong, border_size);
+ }
+
+ // End frozen rows (when we are past the last frozen row line, teleport cursor and alter clipping rectangle)
+ // We need to do that in TableEndRow() instead of TableBeginRow() so the list clipper can mark end of row and
+ // get the new cursor position.
+ if (unfreeze_rows_request)
+ for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
+ {
+ ImGuiTableColumn* column = &table->Columns[column_n];
+ column->NavLayerCurrent = (ImS8)((column_n < table->FreezeColumnsCount) ? ImGuiNavLayer_Menu : ImGuiNavLayer_Main);
+ }
+ if (unfreeze_rows_actual)
+ {
+ IM_ASSERT(table->IsUnfrozenRows == false);
+ table->IsUnfrozenRows = true;
+
+ // BgClipRect starts as table->InnerClipRect, reduce it now and make BgClipRectForDrawCmd == BgClipRect
+ float y0 = ImMax(table->RowPosY2 + 1, window->InnerClipRect.Min.y);
+ table->BgClipRect.Min.y = table->Bg2ClipRectForDrawCmd.Min.y = ImMin(y0, window->InnerClipRect.Max.y);
+ table->BgClipRect.Max.y = table->Bg2ClipRectForDrawCmd.Max.y = window->InnerClipRect.Max.y;
+ table->Bg2DrawChannelCurrent = table->Bg2DrawChannelUnfrozen;
+ IM_ASSERT(table->Bg2ClipRectForDrawCmd.Min.y <= table->Bg2ClipRectForDrawCmd.Max.y);
+
+ float row_height = table->RowPosY2 - table->RowPosY1;
+ table->RowPosY2 = window->DC.CursorPos.y = table->WorkRect.Min.y + table->RowPosY2 - table->OuterRect.Min.y;
+ table->RowPosY1 = table->RowPosY2 - row_height;
+ for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
+ {
+ ImGuiTableColumn* column = &table->Columns[column_n];
+ column->DrawChannelCurrent = column->DrawChannelUnfrozen;
+ column->ClipRect.Min.y = table->Bg2ClipRectForDrawCmd.Min.y;
+ }
+
+ // Update cliprect ahead of TableBeginCell() so clipper can access to new ClipRect->Min.y
+ SetWindowClipRectBeforeSetChannel(window, table->Columns[0].ClipRect);
+ table->DrawSplitter.SetCurrentChannel(window->DrawList, table->Columns[0].DrawChannelCurrent);
+ }
+
+ if (!(table->RowFlags & ImGuiTableRowFlags_Headers))
+ table->RowBgColorCounter++;
+ table->IsInsideRow = false;
+}
+
+//-------------------------------------------------------------------------
+// [SECTION] Tables: Columns changes
+//-------------------------------------------------------------------------
+// - TableGetColumnIndex()
+// - TableSetColumnIndex()
+// - TableNextColumn()
+// - TableBeginCell() [Internal]
+// - TableEndCell() [Internal]
+//-------------------------------------------------------------------------
+
+int ImGui::TableGetColumnIndex()
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiTable* table = g.CurrentTable;
+ if (!table)
+ return 0;
+ return table->CurrentColumn;
+}
+
+// [Public] Append into a specific column
+bool ImGui::TableSetColumnIndex(int column_n)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiTable* table = g.CurrentTable;
+ if (!table)
+ return false;
+
+ if (table->CurrentColumn != column_n)
+ {
+ if (table->CurrentColumn != -1)
+ TableEndCell(table);
+ IM_ASSERT(column_n >= 0 && table->ColumnsCount);
+ TableBeginCell(table, column_n);
+ }
+
+ // Return whether the column is visible. User may choose to skip submitting items based on this return value,
+ // however they shouldn't skip submitting for columns that may have the tallest contribution to row height.
+ return (table->RequestOutputMaskByIndex & ((ImU64)1 << column_n)) != 0;
+}
+
+// [Public] Append into the next column, wrap and create a new row when already on last column
+bool ImGui::TableNextColumn()
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiTable* table = g.CurrentTable;
+ if (!table)
+ return false;
+
+ if (table->IsInsideRow && table->CurrentColumn + 1 < table->ColumnsCount)
+ {
+ if (table->CurrentColumn != -1)
+ TableEndCell(table);
+ TableBeginCell(table, table->CurrentColumn + 1);
+ }
+ else
+ {
+ TableNextRow();
+ TableBeginCell(table, 0);
+ }
+
+ // Return whether the column is visible. User may choose to skip submitting items based on this return value,
+ // however they shouldn't skip submitting for columns that may have the tallest contribution to row height.
+ int column_n = table->CurrentColumn;
+ return (table->RequestOutputMaskByIndex & ((ImU64)1 << column_n)) != 0;
+}
+
+
+// [Internal] Called by TableSetColumnIndex()/TableNextColumn()
+// This is called very frequently, so we need to be mindful of unnecessary overhead.
+// FIXME-TABLE FIXME-OPT: Could probably shortcut some things for non-active or clipped columns.
+void ImGui::TableBeginCell(ImGuiTable* table, int column_n)
+{
+ ImGuiTableColumn* column = &table->Columns[column_n];
+ ImGuiWindow* window = table->InnerWindow;
+ table->CurrentColumn = column_n;
+
+ // Start position is roughly ~~ CellRect.Min + CellPadding + Indent
+ float start_x = column->WorkMinX;
+ if (column->Flags & ImGuiTableColumnFlags_IndentEnable)
+ start_x += table->RowIndentOffsetX; // ~~ += window.DC.Indent.x - table->HostIndentX, except we locked it for the row.
+
+ window->DC.CursorPos.x = start_x;
+ window->DC.CursorPos.y = table->RowPosY1 + table->CellPaddingY;
+ window->DC.CursorMaxPos.x = window->DC.CursorPos.x;
+ window->DC.ColumnsOffset.x = start_x - window->Pos.x - window->DC.Indent.x; // FIXME-WORKRECT
+ window->DC.CurrLineTextBaseOffset = table->RowTextBaseline;
+ window->DC.NavLayerCurrent = (ImGuiNavLayer)column->NavLayerCurrent;
+
+ window->WorkRect.Min.y = window->DC.CursorPos.y;
+ window->WorkRect.Min.x = column->WorkMinX;
+ window->WorkRect.Max.x = column->WorkMaxX;
+ window->DC.ItemWidth = column->ItemWidth;
+
+ // To allow ImGuiListClipper to function we propagate our row height
+ if (!column->IsEnabled)
+ window->DC.CursorPos.y = ImMax(window->DC.CursorPos.y, table->RowPosY2);
+
+ window->SkipItems = column->IsSkipItems;
+ if (column->IsSkipItems)
+ {
+ window->DC.LastItemId = 0;
+ window->DC.LastItemStatusFlags = 0;
+ }
+
+ if (table->Flags & ImGuiTableFlags_NoClip)
+ {
+ // FIXME: if we end up drawing all borders/bg in EndTable, could remove this and just assert that channel hasn't changed.
+ table->DrawSplitter.SetCurrentChannel(window->DrawList, TABLE_DRAW_CHANNEL_NOCLIP);
+ //IM_ASSERT(table->DrawSplitter._Current == TABLE_DRAW_CHANNEL_NOCLIP);
+ }
+ else
+ {
+ // FIXME-TABLE: Could avoid this if draw channel is dummy channel?
+ SetWindowClipRectBeforeSetChannel(window, column->ClipRect);
+ table->DrawSplitter.SetCurrentChannel(window->DrawList, column->DrawChannelCurrent);
+ }
+}
+
+// [Internal] Called by TableNextRow()/TableSetColumnIndex()/TableNextColumn()
+void ImGui::TableEndCell(ImGuiTable* table)
+{
+ ImGuiTableColumn* column = &table->Columns[table->CurrentColumn];
+ ImGuiWindow* window = table->InnerWindow;
+
+ // Report maximum position so we can infer content size per column.
+ float* p_max_pos_x;
+ if (table->RowFlags & ImGuiTableRowFlags_Headers)
+ p_max_pos_x = &column->ContentMaxXHeadersUsed; // Useful in case user submit contents in header row that is not a TableHeader() call
+ else
+ p_max_pos_x = table->IsUnfrozenRows ? &column->ContentMaxXUnfrozen : &column->ContentMaxXFrozen;
+ *p_max_pos_x = ImMax(*p_max_pos_x, window->DC.CursorMaxPos.x);
+ table->RowPosY2 = ImMax(table->RowPosY2, window->DC.CursorMaxPos.y + table->CellPaddingY);
+ column->ItemWidth = window->DC.ItemWidth;
+
+ // Propagate text baseline for the entire row
+ // FIXME-TABLE: Here we propagate text baseline from the last line of the cell.. instead of the first one.
+ table->RowTextBaseline = ImMax(table->RowTextBaseline, window->DC.PrevLineTextBaseOffset);
+}
+
+//-------------------------------------------------------------------------
+// [SECTION] Tables: Columns width management
+//-------------------------------------------------------------------------
+// - TableGetMaxColumnWidth() [Internal]
+// - TableGetColumnWidthAuto() [Internal]
+// - TableSetColumnWidth()
+// - TableSetColumnWidthAutoSingle() [Internal]
+// - TableSetColumnWidthAutoAll() [Internal]
+// - TableUpdateColumnsWeightFromWidth() [Internal]
+//-------------------------------------------------------------------------
+
+// Maximum column content width given current layout. Use column->MinX so this value on a per-column basis.
+float ImGui::TableGetMaxColumnWidth(const ImGuiTable* table, int column_n)
+{
+ const ImGuiTableColumn* column = &table->Columns[column_n];
+ float max_width = FLT_MAX;
+ const float min_column_distance = table->MinColumnWidth + table->CellPaddingX * 2.0f + table->CellSpacingX1 + table->CellSpacingX2;
+ if (table->Flags & ImGuiTableFlags_ScrollX)
+ {
+ // Frozen columns can't reach beyond visible width else scrolling will naturally break.
+ if (column->DisplayOrder < table->FreezeColumnsRequest)
+ {
+ max_width = (table->InnerClipRect.Max.x - (table->FreezeColumnsRequest - column->DisplayOrder) * min_column_distance) - column->MinX;
+ max_width = max_width - table->OuterPaddingX - table->CellPaddingX - table->CellSpacingX2;
+ }
+ }
+ else if ((table->Flags & ImGuiTableFlags_NoKeepColumnsVisible) == 0)
+ {
+ // If horizontal scrolling if disabled, we apply a final lossless shrinking of columns in order to make
+ // sure they are all visible. Because of this we also know that all of the columns will always fit in
+ // table->WorkRect and therefore in table->InnerRect (because ScrollX is off)
+ // FIXME-TABLE: This is solved incorrectly but also quite a difficult problem to fix as we also want ClipRect width to match.
+ // See "table_width_distrib" and "table_width_keep_visible" tests
+ max_width = table->WorkRect.Max.x - (table->ColumnsEnabledCount - column->IndexWithinEnabledSet - 1) * min_column_distance - column->MinX;
+ //max_width -= table->CellSpacingX1;
+ max_width -= table->CellSpacingX2;
+ max_width -= table->CellPaddingX * 2.0f;
+ max_width -= table->OuterPaddingX;
+ }
+ return max_width;
+}
+
+// Note this is meant to be stored in column->WidthAuto, please generally use the WidthAuto field
+float ImGui::TableGetColumnWidthAuto(ImGuiTable* table, ImGuiTableColumn* column)
+{
+ const float content_width_body = ImMax(column->ContentMaxXFrozen, column->ContentMaxXUnfrozen) - column->WorkMinX;
+ const float content_width_headers = column->ContentMaxXHeadersIdeal - column->WorkMinX;
+ float width_auto = content_width_body;
+ if (!(column->Flags & ImGuiTableColumnFlags_NoHeaderWidth))
+ width_auto = ImMax(width_auto, content_width_headers);
+
+ // Non-resizable fixed columns preserve their requested width
+ if ((column->Flags & ImGuiTableColumnFlags_WidthFixed) && column->InitStretchWeightOrWidth > 0.0f)
+ if (!(table->Flags & ImGuiTableFlags_Resizable) || (column->Flags & ImGuiTableColumnFlags_NoResize))
+ width_auto = column->InitStretchWeightOrWidth;
+
+ return ImMax(width_auto, table->MinColumnWidth);
+}
+
+// 'width' = inner column width, without padding
+void ImGui::TableSetColumnWidth(int column_n, float width)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiTable* table = g.CurrentTable;
+ IM_ASSERT(table != NULL && table->IsLayoutLocked == false);
+ IM_ASSERT(column_n >= 0 && column_n < table->ColumnsCount);
+ ImGuiTableColumn* column_0 = &table->Columns[column_n];
+ float column_0_width = width;
+
+ // Apply constraints early
+ // Compare both requested and actual given width to avoid overwriting requested width when column is stuck (minimum size, bounded)
+ IM_ASSERT(table->MinColumnWidth > 0.0f);
+ const float min_width = table->MinColumnWidth;
+ const float max_width = ImMax(min_width, TableGetMaxColumnWidth(table, column_n));
+ column_0_width = ImClamp(column_0_width, min_width, max_width);
+ if (column_0->WidthGiven == column_0_width || column_0->WidthRequest == column_0_width)
+ return;
+
+ //IMGUI_DEBUG_LOG("TableSetColumnWidth(%d, %.1f->%.1f)\n", column_0_idx, column_0->WidthGiven, column_0_width);
+ ImGuiTableColumn* column_1 = (column_0->NextEnabledColumn != -1) ? &table->Columns[column_0->NextEnabledColumn] : NULL;
+
+ // In this surprisingly not simple because of how we support mixing Fixed and multiple Stretch columns.
+ // - All fixed: easy.
+ // - All stretch: easy.
+ // - One or more fixed + one stretch: easy.
+ // - One or more fixed + more than one stretch: tricky.
+ // Qt when manual resize is enabled only support a single _trailing_ stretch column.
+
+ // When forwarding resize from Wn| to Fn+1| we need to be considerate of the _NoResize flag on Fn+1.
+ // FIXME-TABLE: Find a way to rewrite all of this so interactions feel more consistent for the user.
+ // Scenarios:
+ // - F1 F2 F3 resize from F1| or F2| --> ok: alter ->WidthRequested of Fixed column. Subsequent columns will be offset.
+ // - F1 F2 F3 resize from F3| --> ok: alter ->WidthRequested of Fixed column. If active, ScrollX extent can be altered.
+ // - F1 F2 W3 resize from F1| or F2| --> ok: alter ->WidthRequested of Fixed column. If active, ScrollX extent can be altered, but it doesn't make much sense as the Stretch column will always be minimal size.
+ // - F1 F2 W3 resize from W3| --> ok: no-op (disabled by Resize Rule 1)
+ // - W1 W2 W3 resize from W1| or W2| --> ok
+ // - W1 W2 W3 resize from W3| --> ok: no-op (disabled by Resize Rule 1)
+ // - W1 F2 F3 resize from F3| --> ok: no-op (disabled by Resize Rule 1)
+ // - W1 F2 resize from F2| --> ok: no-op (disabled by Resize Rule 1)
+ // - W1 W2 F3 resize from W1| or W2| --> ok
+ // - W1 F2 W3 resize from W1| or F2| --> ok
+ // - F1 W2 F3 resize from W2| --> ok
+ // - F1 W3 F2 resize from W3| --> ok
+ // - W1 F2 F3 resize from W1| --> ok: equivalent to resizing |F2. F3 will not move.
+ // - W1 F2 F3 resize from F2| --> ok
+ // All resizes from a Wx columns are locking other columns.
+
+ // Possible improvements:
+ // - W1 W2 W3 resize W1| --> to not be stuck, both W2 and W3 would stretch down. Seems possible to fix. Would be most beneficial to simplify resize of all-weighted columns.
+ // - W3 F1 F2 resize W3| --> to not be stuck past F1|, both F1 and F2 would need to stretch down, which would be lossy or ambiguous. Seems hard to fix.
+
+ // [Resize Rule 1] Can't resize from right of right-most visible column if there is any Stretch column. Implemented in TableUpdateLayout().
+
+ // If we have all Fixed columns OR resizing a Fixed column that doesn't come after a Stretch one, we can do an offsetting resize.
+ // This is the preferred resize path
+ if (column_0->Flags & ImGuiTableColumnFlags_WidthFixed)
+ if (!column_1 || table->LeftMostStretchedColumn == -1 || table->Columns[table->LeftMostStretchedColumn].DisplayOrder >= column_0->DisplayOrder)
+ {
+ column_0->WidthRequest = column_0_width;
+ table->IsSettingsDirty = true;
+ return;
+ }
+
+ // We can also use previous column if there's no next one (this is used when doing an auto-fit on the right-most stretch column)
+ if (column_1 == NULL)
+ column_1 = (column_0->PrevEnabledColumn != -1) ? &table->Columns[column_0->PrevEnabledColumn] : NULL;
+ if (column_1 == NULL)
+ return;
+
+ // Resizing from right-side of a Stretch column before a Fixed column forward sizing to left-side of fixed column.
+ // (old_a + old_b == new_a + new_b) --> (new_a == old_a + old_b - new_b)
+ float column_1_width = ImMax(column_1->WidthRequest - (column_0_width - column_0->WidthRequest), min_width);
+ column_0_width = column_0->WidthRequest + column_1->WidthRequest - column_1_width;
+ IM_ASSERT(column_0_width > 0.0f && column_1_width > 0.0f);
+ column_0->WidthRequest = column_0_width;
+ column_1->WidthRequest = column_1_width;
+ if ((column_0->Flags | column_1->Flags) & ImGuiTableColumnFlags_WidthStretch)
+ TableUpdateColumnsWeightFromWidth(table);
+ table->IsSettingsDirty = true;
+}
+
+// Disable clipping then auto-fit, will take 2 frames
+// (we don't take a shortcut for unclipped columns to reduce inconsistencies when e.g. resizing multiple columns)
+void ImGui::TableSetColumnWidthAutoSingle(ImGuiTable* table, int column_n)
+{
+ // Single auto width uses auto-fit
+ ImGuiTableColumn* column = &table->Columns[column_n];
+ if (!column->IsEnabled)
+ return;
+ column->CannotSkipItemsQueue = (1 << 0);
+ table->AutoFitSingleColumn = (ImGuiTableColumnIdx)column_n;
+}
+
+void ImGui::TableSetColumnWidthAutoAll(ImGuiTable* table)
+{
+ for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
+ {
+ ImGuiTableColumn* column = &table->Columns[column_n];
+ if (!column->IsEnabled && !(column->Flags & ImGuiTableColumnFlags_WidthStretch)) // Cannot reset weight of hidden stretch column
+ continue;
+ column->CannotSkipItemsQueue = (1 << 0);
+ column->AutoFitQueue = (1 << 1);
+ }
+}
+
+void ImGui::TableUpdateColumnsWeightFromWidth(ImGuiTable* table)
+{
+ IM_ASSERT(table->LeftMostStretchedColumn != -1 && table->RightMostStretchedColumn != -1);
+
+ // Measure existing quantity
+ float visible_weight = 0.0f;
+ float visible_width = 0.0f;
+ for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
+ {
+ ImGuiTableColumn* column = &table->Columns[column_n];
+ if (!column->IsEnabled || !(column->Flags & ImGuiTableColumnFlags_WidthStretch))
+ continue;
+ IM_ASSERT(column->StretchWeight > 0.0f);
+ visible_weight += column->StretchWeight;
+ visible_width += column->WidthRequest;
+ }
+ IM_ASSERT(visible_weight > 0.0f && visible_width > 0.0f);
+
+ // Apply new weights
+ for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
+ {
+ ImGuiTableColumn* column = &table->Columns[column_n];
+ if (!column->IsEnabled || !(column->Flags & ImGuiTableColumnFlags_WidthStretch))
+ continue;
+ column->StretchWeight = (column->WidthRequest / visible_width) * visible_weight;
+ IM_ASSERT(column->StretchWeight > 0.0f);
+ }
+}
+
+//-------------------------------------------------------------------------
+// [SECTION] Tables: Drawing
+//-------------------------------------------------------------------------
+// - TablePushBackgroundChannel() [Internal]
+// - TablePopBackgroundChannel() [Internal]
+// - TableSetupDrawChannels() [Internal]
+// - TableMergeDrawChannels() [Internal]
+// - TableDrawBorders() [Internal]
+//-------------------------------------------------------------------------
+
+// Bg2 is used by Selectable (and possibly other widgets) to render to the background.
+// Unlike our Bg0/1 channel which we uses for RowBg/CellBg/Borders and where we guarantee all shapes to be CPU-clipped, the Bg2 channel being widgets-facing will rely on regular ClipRect.
+void ImGui::TablePushBackgroundChannel()
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ ImGuiTable* table = g.CurrentTable;
+
+ // Optimization: avoid SetCurrentChannel() + PushClipRect()
+ table->HostBackupInnerClipRect = window->ClipRect;
+ SetWindowClipRectBeforeSetChannel(window, table->Bg2ClipRectForDrawCmd);
+ table->DrawSplitter.SetCurrentChannel(window->DrawList, table->Bg2DrawChannelCurrent);
+}
+
+void ImGui::TablePopBackgroundChannel()
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ ImGuiTable* table = g.CurrentTable;
+ ImGuiTableColumn* column = &table->Columns[table->CurrentColumn];
+
+ // Optimization: avoid PopClipRect() + SetCurrentChannel()
+ SetWindowClipRectBeforeSetChannel(window, table->HostBackupInnerClipRect);
+ table->DrawSplitter.SetCurrentChannel(window->DrawList, column->DrawChannelCurrent);
+}
+
+// Allocate draw channels. Called by TableUpdateLayout()
+// - We allocate them following storage order instead of display order so reordering columns won't needlessly
+// increase overall dormant memory cost.
+// - We isolate headers draw commands in their own channels instead of just altering clip rects.
+// This is in order to facilitate merging of draw commands.
+// - After crossing FreezeRowsCount, all columns see their current draw channel changed to a second set of channels.
+// - We only use the dummy draw channel so we can push a null clipping rectangle into it without affecting other
+// channels, while simplifying per-row/per-cell overhead. It will be empty and discarded when merged.
+// - We allocate 1 or 2 background draw channels. This is because we know TablePushBackgroundChannel() is only used for
+// horizontal spanning. If we allowed vertical spanning we'd need one background draw channel per merge group (1-4).
+// Draw channel allocation (before merging):
+// - NoClip --> 2+D+1 channels: bg0/1 + bg2 + foreground (same clip rect == always 1 draw call)
+// - Clip --> 2+D+N channels
+// - FreezeRows --> 2+D+N*2 (unless scrolling value is zero)
+// - FreezeRows || FreezeColunns --> 3+D+N*2 (unless scrolling value is zero)
+// Where D is 1 if any column is clipped or hidden (dummy channel) otherwise 0.
+void ImGui::TableSetupDrawChannels(ImGuiTable* table)
+{
+ const int freeze_row_multiplier = (table->FreezeRowsCount > 0) ? 2 : 1;
+ const int channels_for_row = (table->Flags & ImGuiTableFlags_NoClip) ? 1 : table->ColumnsEnabledCount;
+ const int channels_for_bg = 1 + 1 * freeze_row_multiplier;
+ const int channels_for_dummy = (table->ColumnsEnabledCount < table->ColumnsCount || table->VisibleMaskByIndex != table->EnabledMaskByIndex) ? +1 : 0;
+ const int channels_total = channels_for_bg + (channels_for_row * freeze_row_multiplier) + channels_for_dummy;
+ table->DrawSplitter.Split(table->InnerWindow->DrawList, channels_total);
+ table->DummyDrawChannel = (ImGuiTableDrawChannelIdx)((channels_for_dummy > 0) ? channels_total - 1 : -1);
+ table->Bg2DrawChannelCurrent = TABLE_DRAW_CHANNEL_BG2_FROZEN;
+ table->Bg2DrawChannelUnfrozen = (ImGuiTableDrawChannelIdx)((table->FreezeRowsCount > 0) ? 2 + channels_for_row : TABLE_DRAW_CHANNEL_BG2_FROZEN);
+
+ int draw_channel_current = 2;
+ for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
+ {
+ ImGuiTableColumn* column = &table->Columns[column_n];
+ if (column->IsVisibleX && column->IsVisibleY)
+ {
+ column->DrawChannelFrozen = (ImGuiTableDrawChannelIdx)(draw_channel_current);
+ column->DrawChannelUnfrozen = (ImGuiTableDrawChannelIdx)(draw_channel_current + (table->FreezeRowsCount > 0 ? channels_for_row + 1 : 0));
+ if (!(table->Flags & ImGuiTableFlags_NoClip))
+ draw_channel_current++;
+ }
+ else
+ {
+ column->DrawChannelFrozen = column->DrawChannelUnfrozen = table->DummyDrawChannel;
+ }
+ column->DrawChannelCurrent = column->DrawChannelFrozen;
+ }
+
+ // Initial draw cmd starts with a BgClipRect that matches the one of its host, to facilitate merge draw commands by default.
+ // All our cell highlight are manually clipped with BgClipRect. When unfreezing it will be made smaller to fit scrolling rect.
+ // (This technically isn't part of setting up draw channels, but is reasonably related to be done here)
+ table->BgClipRect = table->InnerClipRect;
+ table->Bg0ClipRectForDrawCmd = table->OuterWindow->ClipRect;
+ table->Bg2ClipRectForDrawCmd = table->HostClipRect;
+ IM_ASSERT(table->BgClipRect.Min.y <= table->BgClipRect.Max.y);
+}
+
+// This function reorder draw channels based on matching clip rectangle, to facilitate merging them. Called by EndTable().
+// For simplicity we call it TableMergeDrawChannels() but in fact it only reorder channels + overwrite ClipRect,
+// actual merging is done by table->DrawSplitter.Merge() which is called right after TableMergeDrawChannels().
+//
+// Columns where the contents didn't stray off their local clip rectangle can be merged. To achieve
+// this we merge their clip rect and make them contiguous in the channel list, so they can be merged
+// by the call to DrawSplitter.Merge() following to the call to this function.
+// We reorder draw commands by arranging them into a maximum of 4 distinct groups:
+//
+// 1 group: 2 groups: 2 groups: 4 groups:
+// [ 0. ] no freeze [ 0. ] row freeze [ 01 ] col freeze [ 01 ] row+col freeze
+// [ .. ] or no scroll [ 2. ] and v-scroll [ .. ] and h-scroll [ 23 ] and v+h-scroll
+//
+// Each column itself can use 1 channel (row freeze disabled) or 2 channels (row freeze enabled).
+// When the contents of a column didn't stray off its limit, we move its channels into the corresponding group
+// based on its position (within frozen rows/columns groups or not).
+// At the end of the operation our 1-4 groups will each have a ImDrawCmd using the same ClipRect.
+// This function assume that each column are pointing to a distinct draw channel,
+// otherwise merge_group->ChannelsCount will not match set bit count of merge_group->ChannelsMask.
+//
+// Column channels will not be merged into one of the 1-4 groups in the following cases:
+// - The contents stray off its clipping rectangle (we only compare the MaxX value, not the MinX value).
+// Direct ImDrawList calls won't be taken into account by default, if you use them make sure the ImGui:: bounds
+// matches, by e.g. calling SetCursorScreenPos().
+// - The channel uses more than one draw command itself. We drop all our attempt at merging stuff here..
+// we could do better but it's going to be rare and probably not worth the hassle.
+// Columns for which the draw channel(s) haven't been merged with other will use their own ImDrawCmd.
+//
+// This function is particularly tricky to understand.. take a breath.
+void ImGui::TableMergeDrawChannels(ImGuiTable* table)
+{
+ ImGuiContext& g = *GImGui;
+ ImDrawListSplitter* splitter = &table->DrawSplitter;
+ const bool has_freeze_v = (table->FreezeRowsCount > 0);
+ const bool has_freeze_h = (table->FreezeColumnsCount > 0);
+ IM_ASSERT(splitter->_Current == 0);
+
+ // Track which groups we are going to attempt to merge, and which channels goes into each group.
+ struct MergeGroup
+ {
+ ImRect ClipRect;
+ int ChannelsCount;
+ ImBitArray ChannelsMask;
+ };
+ int merge_group_mask = 0x00;
+ MergeGroup merge_groups[4];
+ memset(merge_groups, 0, sizeof(merge_groups));
+
+ // 1. Scan channels and take note of those which can be merged
+ for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
+ {
+ if ((table->VisibleMaskByIndex & ((ImU64)1 << column_n)) == 0)
+ continue;
+ ImGuiTableColumn* column = &table->Columns[column_n];
+
+ const int merge_group_sub_count = has_freeze_v ? 2 : 1;
+ for (int merge_group_sub_n = 0; merge_group_sub_n < merge_group_sub_count; merge_group_sub_n++)
+ {
+ const int channel_no = (merge_group_sub_n == 0) ? column->DrawChannelFrozen : column->DrawChannelUnfrozen;
+
+ // Don't attempt to merge if there are multiple draw calls within the column
+ ImDrawChannel* src_channel = &splitter->_Channels[channel_no];
+ if (src_channel->_CmdBuffer.Size > 0 && src_channel->_CmdBuffer.back().ElemCount == 0)
+ src_channel->_CmdBuffer.pop_back();
+ if (src_channel->_CmdBuffer.Size != 1)
+ continue;
+
+ // Find out the width of this merge group and check if it will fit in our column
+ // (note that we assume that rendering didn't stray on the left direction. we should need a CursorMinPos to detect it)
+ if (!(column->Flags & ImGuiTableColumnFlags_NoClip))
+ {
+ float content_max_x;
+ if (!has_freeze_v)
+ content_max_x = ImMax(column->ContentMaxXUnfrozen, column->ContentMaxXHeadersUsed); // No row freeze
+ else if (merge_group_sub_n == 0)
+ content_max_x = ImMax(column->ContentMaxXFrozen, column->ContentMaxXHeadersUsed); // Row freeze: use width before freeze
+ else
+ content_max_x = column->ContentMaxXUnfrozen; // Row freeze: use width after freeze
+ if (content_max_x > column->ClipRect.Max.x)
+ continue;
+ }
+
+ const int merge_group_n = (has_freeze_h && column_n < table->FreezeColumnsCount ? 0 : 1) + (has_freeze_v && merge_group_sub_n == 0 ? 0 : 2);
+ IM_ASSERT(channel_no < IMGUI_TABLE_MAX_DRAW_CHANNELS);
+ MergeGroup* merge_group = &merge_groups[merge_group_n];
+ if (merge_group->ChannelsCount == 0)
+ merge_group->ClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
+ merge_group->ChannelsMask.SetBit(channel_no);
+ merge_group->ChannelsCount++;
+ merge_group->ClipRect.Add(src_channel->_CmdBuffer[0].ClipRect);
+ merge_group_mask |= (1 << merge_group_n);
+ }
+
+ // Invalidate current draw channel
+ // (we don't clear DrawChannelFrozen/DrawChannelUnfrozen solely to facilitate debugging/later inspection of data)
+ column->DrawChannelCurrent = (ImGuiTableDrawChannelIdx)-1;
+ }
+
+ // [DEBUG] Display merge groups
+#if 0
+ if (g.IO.KeyShift)
+ for (int merge_group_n = 0; merge_group_n < IM_ARRAYSIZE(merge_groups); merge_group_n++)
+ {
+ MergeGroup* merge_group = &merge_groups[merge_group_n];
+ if (merge_group->ChannelsCount == 0)
+ continue;
+ char buf[32];
+ ImFormatString(buf, 32, "MG%d:%d", merge_group_n, merge_group->ChannelsCount);
+ ImVec2 text_pos = merge_group->ClipRect.Min + ImVec2(4, 4);
+ ImVec2 text_size = CalcTextSize(buf, NULL);
+ GetForegroundDrawList()->AddRectFilled(text_pos, text_pos + text_size, IM_COL32(0, 0, 0, 255));
+ GetForegroundDrawList()->AddText(text_pos, IM_COL32(255, 255, 0, 255), buf, NULL);
+ GetForegroundDrawList()->AddRect(merge_group->ClipRect.Min, merge_group->ClipRect.Max, IM_COL32(255, 255, 0, 255));
+ }
+#endif
+
+ // 2. Rewrite channel list in our preferred order
+ if (merge_group_mask != 0)
+ {
+ // We skip channel 0 (Bg0/Bg1) and 1 (Bg2 frozen) from the shuffling since they won't move - see channels allocation in TableSetupDrawChannels().
+ const int LEADING_DRAW_CHANNELS = 2;
+ g.DrawChannelsTempMergeBuffer.resize(splitter->_Count - LEADING_DRAW_CHANNELS); // Use shared temporary storage so the allocation gets amortized
+ ImDrawChannel* dst_tmp = g.DrawChannelsTempMergeBuffer.Data;
+ ImBitArray remaining_mask; // We need 132-bit of storage
+ remaining_mask.ClearAllBits();
+ remaining_mask.SetBitRange(LEADING_DRAW_CHANNELS, splitter->_Count);
+ remaining_mask.ClearBit(table->Bg2DrawChannelUnfrozen);
+ IM_ASSERT(has_freeze_v == false || table->Bg2DrawChannelUnfrozen != TABLE_DRAW_CHANNEL_BG2_FROZEN);
+ int remaining_count = splitter->_Count - (has_freeze_v ? LEADING_DRAW_CHANNELS + 1 : LEADING_DRAW_CHANNELS);
+ //ImRect host_rect = (table->InnerWindow == table->OuterWindow) ? table->InnerClipRect : table->HostClipRect;
+ ImRect host_rect = table->HostClipRect;
+ for (int merge_group_n = 0; merge_group_n < IM_ARRAYSIZE(merge_groups); merge_group_n++)
+ {
+ if (int merge_channels_count = merge_groups[merge_group_n].ChannelsCount)
+ {
+ MergeGroup* merge_group = &merge_groups[merge_group_n];
+ ImRect merge_clip_rect = merge_group->ClipRect;
+
+ // Extend outer-most clip limits to match those of host, so draw calls can be merged even if
+ // outer-most columns have some outer padding offsetting them from their parent ClipRect.
+ // The principal cases this is dealing with are:
+ // - On a same-window table (not scrolling = single group), all fitting columns ClipRect -> will extend and match host ClipRect -> will merge
+ // - Columns can use padding and have left-most ClipRect.Min.x and right-most ClipRect.Max.x != from host ClipRect -> will extend and match host ClipRect -> will merge
+ // FIXME-TABLE FIXME-WORKRECT: We are wasting a merge opportunity on tables without scrolling if column doesn't fit
+ // within host clip rect, solely because of the half-padding difference between window->WorkRect and window->InnerClipRect.
+ if ((merge_group_n & 1) == 0 || !has_freeze_h)
+ merge_clip_rect.Min.x = ImMin(merge_clip_rect.Min.x, host_rect.Min.x);
+ if ((merge_group_n & 2) == 0 || !has_freeze_v)
+ merge_clip_rect.Min.y = ImMin(merge_clip_rect.Min.y, host_rect.Min.y);
+ if ((merge_group_n & 1) != 0)
+ merge_clip_rect.Max.x = ImMax(merge_clip_rect.Max.x, host_rect.Max.x);
+ if ((merge_group_n & 2) != 0 && (table->Flags & ImGuiTableFlags_NoHostExtendY) == 0)
+ merge_clip_rect.Max.y = ImMax(merge_clip_rect.Max.y, host_rect.Max.y);
+#if 0
+ GetOverlayDrawList()->AddRect(merge_group->ClipRect.Min, merge_group->ClipRect.Max, IM_COL32(255, 0, 0, 200), 0.0f, ~0, 1.0f);
+ GetOverlayDrawList()->AddLine(merge_group->ClipRect.Min, merge_clip_rect.Min, IM_COL32(255, 100, 0, 200));
+ GetOverlayDrawList()->AddLine(merge_group->ClipRect.Max, merge_clip_rect.Max, IM_COL32(255, 100, 0, 200));
+#endif
+ remaining_count -= merge_group->ChannelsCount;
+ for (int n = 0; n < IM_ARRAYSIZE(remaining_mask.Storage); n++)
+ remaining_mask.Storage[n] &= ~merge_group->ChannelsMask.Storage[n];
+ for (int n = 0; n < splitter->_Count && merge_channels_count != 0; n++)
+ {
+ // Copy + overwrite new clip rect
+ if (!merge_group->ChannelsMask.TestBit(n))
+ continue;
+ merge_group->ChannelsMask.ClearBit(n);
+ merge_channels_count--;
+
+ ImDrawChannel* channel = &splitter->_Channels[n];
+ IM_ASSERT(channel->_CmdBuffer.Size == 1 && merge_clip_rect.Contains(ImRect(channel->_CmdBuffer[0].ClipRect)));
+ channel->_CmdBuffer[0].ClipRect = merge_clip_rect.ToVec4();
+ memcpy(dst_tmp++, channel, sizeof(ImDrawChannel));
+ }
+ }
+
+ // Make sure Bg2DrawChannelUnfrozen appears in the middle of our groups (whereas Bg0/Bg1 and Bg2 frozen are fixed to 0 and 1)
+ if (merge_group_n == 1 && has_freeze_v)
+ memcpy(dst_tmp++, &splitter->_Channels[table->Bg2DrawChannelUnfrozen], sizeof(ImDrawChannel));
+ }
+
+ // Append unmergeable channels that we didn't reorder at the end of the list
+ for (int n = 0; n < splitter->_Count && remaining_count != 0; n++)
+ {
+ if (!remaining_mask.TestBit(n))
+ continue;
+ ImDrawChannel* channel = &splitter->_Channels[n];
+ memcpy(dst_tmp++, channel, sizeof(ImDrawChannel));
+ remaining_count--;
+ }
+ IM_ASSERT(dst_tmp == g.DrawChannelsTempMergeBuffer.Data + g.DrawChannelsTempMergeBuffer.Size);
+ memcpy(splitter->_Channels.Data + LEADING_DRAW_CHANNELS, g.DrawChannelsTempMergeBuffer.Data, (splitter->_Count - LEADING_DRAW_CHANNELS) * sizeof(ImDrawChannel));
+ }
+}
+
+// FIXME-TABLE: This is a mess, need to redesign how we render borders (as some are also done in TableEndRow)
+void ImGui::TableDrawBorders(ImGuiTable* table)
+{
+ ImGuiWindow* inner_window = table->InnerWindow;
+ if (!table->OuterWindow->ClipRect.Overlaps(table->OuterRect))
+ return;
+
+ ImDrawList* inner_drawlist = inner_window->DrawList;
+ table->DrawSplitter.SetCurrentChannel(inner_drawlist, TABLE_DRAW_CHANNEL_BG0);
+ inner_drawlist->PushClipRect(table->Bg0ClipRectForDrawCmd.Min, table->Bg0ClipRectForDrawCmd.Max, false);
+
+ // Draw inner border and resizing feedback
+ const float border_size = TABLE_BORDER_SIZE;
+ const float draw_y1 = table->InnerRect.Min.y;
+ const float draw_y2_body = table->InnerRect.Max.y;
+ const float draw_y2_head = table->IsUsingHeaders ? ImMin(table->InnerRect.Max.y, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table->LastFirstRowHeight) : draw_y1;
+ if (table->Flags & ImGuiTableFlags_BordersInnerV)
+ {
+ for (int order_n = 0; order_n < table->ColumnsCount; order_n++)
+ {
+ if (!(table->EnabledMaskByDisplayOrder & ((ImU64)1 << order_n)))
+ continue;
+
+ const int column_n = table->DisplayOrderToIndex[order_n];
+ ImGuiTableColumn* column = &table->Columns[column_n];
+ const bool is_hovered = (table->HoveredColumnBorder == column_n);
+ const bool is_resized = (table->ResizedColumn == column_n) && (table->InstanceInteracted == table->InstanceCurrent);
+ const bool is_resizable = (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_)) == 0;
+ const bool is_frozen_separator = (table->FreezeColumnsCount != -1 && table->FreezeColumnsCount == order_n + 1);
+ if (column->MaxX > table->InnerClipRect.Max.x && !is_resized)
+ continue;
+
+ // Decide whether right-most column is visible
+ if (column->NextEnabledColumn == -1 && !is_resizable)
+ if ((table->Flags & ImGuiTableFlags_SizingMask_) != ImGuiTableFlags_SizingFixedSame || (table->Flags & ImGuiTableFlags_NoHostExtendX))
+ continue;
+ if (column->MaxX <= column->ClipRect.Min.x) // FIXME-TABLE FIXME-STYLE: Assume BorderSize==1, this is problematic if we want to increase the border size..
+ continue;
+
+ // Draw in outer window so right-most column won't be clipped
+ // Always draw full height border when being resized/hovered, or on the delimitation of frozen column scrolling.
+ ImU32 col;
+ float draw_y2;
+ if (is_hovered || is_resized || is_frozen_separator)
+ {
+ draw_y2 = draw_y2_body;
+ col = is_resized ? GetColorU32(ImGuiCol_SeparatorActive) : is_hovered ? GetColorU32(ImGuiCol_SeparatorHovered) : table->BorderColorStrong;
+ }
+ else
+ {
+ draw_y2 = (table->Flags & (ImGuiTableFlags_NoBordersInBody | ImGuiTableFlags_NoBordersInBodyUntilResize)) ? draw_y2_head : draw_y2_body;
+ col = (table->Flags & (ImGuiTableFlags_NoBordersInBody | ImGuiTableFlags_NoBordersInBodyUntilResize)) ? table->BorderColorStrong : table->BorderColorLight;
+ }
+
+ if (draw_y2 > draw_y1)
+ inner_drawlist->AddLine(ImVec2(column->MaxX, draw_y1), ImVec2(column->MaxX, draw_y2), col, border_size);
+ }
+ }
+
+ // Draw outer border
+ // FIXME: could use AddRect or explicit VLine/HLine helper?
+ if (table->Flags & ImGuiTableFlags_BordersOuter)
+ {
+ // Display outer border offset by 1 which is a simple way to display it without adding an extra draw call
+ // (Without the offset, in outer_window it would be rendered behind cells, because child windows are above their
+ // parent. In inner_window, it won't reach out over scrollbars. Another weird solution would be to display part
+ // of it in inner window, and the part that's over scrollbars in the outer window..)
+ // Either solution currently won't allow us to use a larger border size: the border would clipped.
+ const ImRect outer_border = table->OuterRect;
+ const ImU32 outer_col = table->BorderColorStrong;
+ if ((table->Flags & ImGuiTableFlags_BordersOuter) == ImGuiTableFlags_BordersOuter)
+ {
+ inner_drawlist->AddRect(outer_border.Min, outer_border.Max, outer_col, 0.0f, ~0, border_size);
+ }
+ else if (table->Flags & ImGuiTableFlags_BordersOuterV)
+ {
+ inner_drawlist->AddLine(outer_border.Min, ImVec2(outer_border.Min.x, outer_border.Max.y), outer_col, border_size);
+ inner_drawlist->AddLine(ImVec2(outer_border.Max.x, outer_border.Min.y), outer_border.Max, outer_col, border_size);
+ }
+ else if (table->Flags & ImGuiTableFlags_BordersOuterH)
+ {
+ inner_drawlist->AddLine(outer_border.Min, ImVec2(outer_border.Max.x, outer_border.Min.y), outer_col, border_size);
+ inner_drawlist->AddLine(ImVec2(outer_border.Min.x, outer_border.Max.y), outer_border.Max, outer_col, border_size);
+ }
+ }
+ if ((table->Flags & ImGuiTableFlags_BordersInnerH) && table->RowPosY2 < table->OuterRect.Max.y)
+ {
+ // Draw bottom-most row border
+ const float border_y = table->RowPosY2;
+ if (border_y >= table->BgClipRect.Min.y && border_y < table->BgClipRect.Max.y)
+ inner_drawlist->AddLine(ImVec2(table->BorderX1, border_y), ImVec2(table->BorderX2, border_y), table->BorderColorLight, border_size);
+ }
+
+ inner_drawlist->PopClipRect();
+}
+
+//-------------------------------------------------------------------------
+// [SECTION] Tables: Sorting
+//-------------------------------------------------------------------------
+// - TableGetSortSpecs()
+// - TableFixColumnSortDirection() [Internal]
+// - TableGetColumnNextSortDirection() [Internal]
+// - TableSetColumnSortDirection() [Internal]
+// - TableSortSpecsSanitize() [Internal]
+// - TableSortSpecsBuild() [Internal]
+//-------------------------------------------------------------------------
+
+// Return NULL if no sort specs (most often when ImGuiTableFlags_Sortable is not set)
+// You can sort your data again when 'SpecsChanged == true'. It will be true with sorting specs have changed since
+// last call, or the first time.
+// Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable()!
+ImGuiTableSortSpecs* ImGui::TableGetSortSpecs()
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiTable* table = g.CurrentTable;
+ IM_ASSERT(table != NULL);
+
+ if (!(table->Flags & ImGuiTableFlags_Sortable))
+ return NULL;
+
+ // Require layout (in case TableHeadersRow() hasn't been called) as it may alter IsSortSpecsDirty in some paths.
+ if (!table->IsLayoutLocked)
+ TableUpdateLayout(table);
+
+ if (table->IsSortSpecsDirty)
+ TableSortSpecsBuild(table);
+
+ return &table->SortSpecs;
+}
+
+static inline ImGuiSortDirection TableGetColumnAvailSortDirection(ImGuiTableColumn* column, int n)
+{
+ IM_ASSERT(n < column->SortDirectionsAvailCount);
+ return (column->SortDirectionsAvailList >> (n << 1)) & 0x03;
+}
+
+// Fix sort direction if currently set on a value which is unavailable (e.g. activating NoSortAscending/NoSortDescending)
+void ImGui::TableFixColumnSortDirection(ImGuiTable* table, ImGuiTableColumn* column)
+{
+ if (column->SortOrder == -1 || (column->SortDirectionsAvailMask & (1 << column->SortDirection)) != 0)
+ return;
+ column->SortDirection = (ImU8)TableGetColumnAvailSortDirection(column, 0);
+ table->IsSortSpecsDirty = true;
+}
+
+// Calculate next sort direction that would be set after clicking the column
+// - If the PreferSortDescending flag is set, we will default to a Descending direction on the first click.
+// - Note that the PreferSortAscending flag is never checked, it is essentially the default and therefore a no-op.
+IM_STATIC_ASSERT(ImGuiSortDirection_None == 0 && ImGuiSortDirection_Ascending == 1 && ImGuiSortDirection_Descending == 2);
+ImGuiSortDirection ImGui::TableGetColumnNextSortDirection(ImGuiTableColumn* column)
+{
+ IM_ASSERT(column->SortDirectionsAvailCount > 0);
+ if (column->SortOrder == -1)
+ return TableGetColumnAvailSortDirection(column, 0);
+ for (int n = 0; n < 3; n++)
+ if (column->SortDirection == TableGetColumnAvailSortDirection(column, n))
+ return TableGetColumnAvailSortDirection(column, (n + 1) % column->SortDirectionsAvailCount);
+ IM_ASSERT(0);
+ return ImGuiSortDirection_None;
+}
+
+// Note that the NoSortAscending/NoSortDescending flags are processed in TableSortSpecsSanitize(), and they may change/revert
+// the value of SortDirection. We could technically also do it here but it would be unnecessary and duplicate code.
+void ImGui::TableSetColumnSortDirection(int column_n, ImGuiSortDirection sort_direction, bool append_to_sort_specs)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiTable* table = g.CurrentTable;
+
+ if (!(table->Flags & ImGuiTableFlags_SortMulti))
+ append_to_sort_specs = false;
+ if (!(table->Flags & ImGuiTableFlags_SortTristate))
+ IM_ASSERT(sort_direction != ImGuiSortDirection_None);
+
+ ImGuiTableColumnIdx sort_order_max = 0;
+ if (append_to_sort_specs)
+ for (int other_column_n = 0; other_column_n < table->ColumnsCount; other_column_n++)
+ sort_order_max = ImMax(sort_order_max, table->Columns[other_column_n].SortOrder);
+
+ ImGuiTableColumn* column = &table->Columns[column_n];
+ column->SortDirection = (ImU8)sort_direction;
+ if (column->SortDirection == ImGuiSortDirection_None)
+ column->SortOrder = -1;
+ else if (column->SortOrder == -1 || !append_to_sort_specs)
+ column->SortOrder = append_to_sort_specs ? sort_order_max + 1 : 0;
+
+ for (int other_column_n = 0; other_column_n < table->ColumnsCount; other_column_n++)
+ {
+ ImGuiTableColumn* other_column = &table->Columns[other_column_n];
+ if (other_column != column && !append_to_sort_specs)
+ other_column->SortOrder = -1;
+ TableFixColumnSortDirection(table, other_column);
+ }
+ table->IsSettingsDirty = true;
+ table->IsSortSpecsDirty = true;
+}
+
+void ImGui::TableSortSpecsSanitize(ImGuiTable* table)
+{
+ IM_ASSERT(table->Flags & ImGuiTableFlags_Sortable);
+
+ // Clear SortOrder from hidden column and verify that there's no gap or duplicate.
+ int sort_order_count = 0;
+ ImU64 sort_order_mask = 0x00;
+ for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
+ {
+ ImGuiTableColumn* column = &table->Columns[column_n];
+ if (column->SortOrder != -1 && !column->IsEnabled)
+ column->SortOrder = -1;
+ if (column->SortOrder == -1)
+ continue;
+ sort_order_count++;
+ sort_order_mask |= ((ImU64)1 << column->SortOrder);
+ IM_ASSERT(sort_order_count < (int)sizeof(sort_order_mask) * 8);
+ }
+
+ const bool need_fix_linearize = ((ImU64)1 << sort_order_count) != (sort_order_mask + 1);
+ const bool need_fix_single_sort_order = (sort_order_count > 1) && !(table->Flags & ImGuiTableFlags_SortMulti);
+ if (need_fix_linearize || need_fix_single_sort_order)
+ {
+ ImU64 fixed_mask = 0x00;
+ for (int sort_n = 0; sort_n < sort_order_count; sort_n++)
+ {
+ // Fix: Rewrite sort order fields if needed so they have no gap or duplicate.
+ // (e.g. SortOrder 0 disappeared, SortOrder 1..2 exists --> rewrite then as SortOrder 0..1)
+ int column_with_smallest_sort_order = -1;
+ for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
+ if ((fixed_mask & ((ImU64)1 << (ImU64)column_n)) == 0 && table->Columns[column_n].SortOrder != -1)
+ if (column_with_smallest_sort_order == -1 || table->Columns[column_n].SortOrder < table->Columns[column_with_smallest_sort_order].SortOrder)
+ column_with_smallest_sort_order = column_n;
+ IM_ASSERT(column_with_smallest_sort_order != -1);
+ fixed_mask |= ((ImU64)1 << column_with_smallest_sort_order);
+ table->Columns[column_with_smallest_sort_order].SortOrder = (ImGuiTableColumnIdx)sort_n;
+
+ // Fix: Make sure only one column has a SortOrder if ImGuiTableFlags_MultiSortable is not set.
+ if (need_fix_single_sort_order)
+ {
+ sort_order_count = 1;
+ for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
+ if (column_n != column_with_smallest_sort_order)
+ table->Columns[column_n].SortOrder = -1;
+ break;
+ }
+ }
+ }
+
+ // Fallback default sort order (if no column had the ImGuiTableColumnFlags_DefaultSort flag)
+ if (sort_order_count == 0 && !(table->Flags & ImGuiTableFlags_SortTristate))
+ for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
+ {
+ ImGuiTableColumn* column = &table->Columns[column_n];
+ if (column->IsEnabled && !(column->Flags & ImGuiTableColumnFlags_NoSort))
+ {
+ sort_order_count = 1;
+ column->SortOrder = 0;
+ column->SortDirection = (ImU8)TableGetColumnAvailSortDirection(column, 0);
+ break;
+ }
+ }
+
+ table->SortSpecsCount = (ImGuiTableColumnIdx)sort_order_count;
+}
+
+void ImGui::TableSortSpecsBuild(ImGuiTable* table)
+{
+ IM_ASSERT(table->IsSortSpecsDirty);
+ TableSortSpecsSanitize(table);
+
+ // Write output
+ table->SortSpecsMulti.resize(table->SortSpecsCount <= 1 ? 0 : table->SortSpecsCount);
+ ImGuiTableColumnSortSpecs* sort_specs = (table->SortSpecsCount == 0) ? NULL : (table->SortSpecsCount == 1) ? &table->SortSpecsSingle : table->SortSpecsMulti.Data;
+ for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
+ {
+ ImGuiTableColumn* column = &table->Columns[column_n];
+ if (column->SortOrder == -1)
+ continue;
+ IM_ASSERT(column->SortOrder < table->SortSpecsCount);
+ ImGuiTableColumnSortSpecs* sort_spec = &sort_specs[column->SortOrder];
+ sort_spec->ColumnUserID = column->UserID;
+ sort_spec->ColumnIndex = (ImGuiTableColumnIdx)column_n;
+ sort_spec->SortOrder = (ImGuiTableColumnIdx)column->SortOrder;
+ sort_spec->SortDirection = column->SortDirection;
+ }
+ table->SortSpecs.Specs = sort_specs;
+ table->SortSpecs.SpecsCount = table->SortSpecsCount;
+ table->SortSpecs.SpecsDirty = true; // Mark as dirty for user
+ table->IsSortSpecsDirty = false; // Mark as not dirty for us
+}
+
+//-------------------------------------------------------------------------
+// [SECTION] Tables: Headers
+//-------------------------------------------------------------------------
+// - TableGetHeaderRowHeight() [Internal]
+// - TableHeadersRow()
+// - TableHeader()
+//-------------------------------------------------------------------------
+
+float ImGui::TableGetHeaderRowHeight()
+{
+ // Caring for a minor edge case:
+ // Calculate row height, for the unlikely case that some labels may be taller than others.
+ // If we didn't do that, uneven header height would highlight but smaller one before the tallest wouldn't catch input for all height.
+ // In your custom header row you may omit this all together and just call TableNextRow() without a height...
+ float row_height = GetTextLineHeight();
+ int columns_count = TableGetColumnCount();
+ for (int column_n = 0; column_n < columns_count; column_n++)
+ if (TableGetColumnFlags(column_n) & ImGuiTableColumnFlags_IsEnabled)
+ row_height = ImMax(row_height, CalcTextSize(TableGetColumnName(column_n)).y);
+ row_height += GetStyle().CellPadding.y * 2.0f;
+ return row_height;
+}
+
+// [Public] This is a helper to output TableHeader() calls based on the column names declared in TableSetupColumn().
+// The intent is that advanced users willing to create customized headers would not need to use this helper
+// and can create their own! For example: TableHeader() may be preceeded by Checkbox() or other custom widgets.
+// See 'Demo->Tables->Custom headers' for a demonstration of implementing a custom version of this.
+// This code is constructed to not make much use of internal functions, as it is intended to be a template to copy.
+// FIXME-TABLE: TableOpenContextMenu() and TableGetHeaderRowHeight() are not public.
+void ImGui::TableHeadersRow()
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiTable* table = g.CurrentTable;
+ IM_ASSERT(table != NULL && "Need to call TableHeadersRow() after BeginTable()!");
+
+ // Layout if not already done (this is automatically done by TableNextRow, we do it here solely to facilitate stepping in debugger as it is frequent to step in TableUpdateLayout)
+ if (!table->IsLayoutLocked)
+ TableUpdateLayout(table);
+
+ // Open row
+ const float row_y1 = GetCursorScreenPos().y;
+ const float row_height = TableGetHeaderRowHeight();
+ TableNextRow(ImGuiTableRowFlags_Headers, row_height);
+ if (table->HostSkipItems) // Merely an optimization, you may skip in your own code.
+ return;
+
+ const int columns_count = TableGetColumnCount();
+ for (int column_n = 0; column_n < columns_count; column_n++)
+ {
+ if (!TableSetColumnIndex(column_n))
+ continue;
+
+ // Push an id to allow unnamed labels (generally accidental, but let's behave nicely with them)
+ // - in your own code you may omit the PushID/PopID all-together, provided you know they won't collide
+ // - table->InstanceCurrent is only >0 when we use multiple BeginTable/EndTable calls with same identifier.
+ const char* name = TableGetColumnName(column_n);
+ PushID(table->InstanceCurrent * table->ColumnsCount + column_n);
+ TableHeader(name);
+ PopID();
+ }
+
+ // Allow opening popup from the right-most section after the last column.
+ ImVec2 mouse_pos = ImGui::GetMousePos();
+ if (IsMouseReleased(1) && TableGetHoveredColumn() == columns_count)
+ if (mouse_pos.y >= row_y1 && mouse_pos.y < row_y1 + row_height)
+ TableOpenContextMenu(-1); // Will open a non-column-specific popup.
+}
+
+// Emit a column header (text + optional sort order)
+// We cpu-clip text here so that all columns headers can be merged into a same draw call.
+// Note that because of how we cpu-clip and display sorting indicators, you _cannot_ use SameLine() after a TableHeader()
+void ImGui::TableHeader(const char* label)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ if (window->SkipItems)
+ return;
+
+ ImGuiTable* table = g.CurrentTable;
+ IM_ASSERT(table != NULL && "Need to call TableHeader() after BeginTable()!");
+ IM_ASSERT(table->CurrentColumn != -1);
+ const int column_n = table->CurrentColumn;
+ ImGuiTableColumn* column = &table->Columns[column_n];
+
+ // Label
+ if (label == NULL)
+ label = "";
+ const char* label_end = FindRenderedTextEnd(label);
+ ImVec2 label_size = CalcTextSize(label, label_end, true);
+ ImVec2 label_pos = window->DC.CursorPos;
+
+ // If we already got a row height, there's use that.
+ // FIXME-TABLE: Padding problem if the correct outer-padding CellBgRect strays off our ClipRect?
+ ImRect cell_r = TableGetCellBgRect(table, column_n);
+ float label_height = ImMax(label_size.y, table->RowMinHeight - table->CellPaddingY * 2.0f);
+
+ // Calculate ideal size for sort order arrow
+ float w_arrow = 0.0f;
+ float w_sort_text = 0.0f;
+ char sort_order_suf[4] = "";
+ const float ARROW_SCALE = 0.65f;
+ if ((table->Flags & ImGuiTableFlags_Sortable) && !(column->Flags & ImGuiTableColumnFlags_NoSort))
+ {
+ w_arrow = ImFloor(g.FontSize * ARROW_SCALE + g.Style.FramePadding.x);
+ if (column->SortOrder > 0)
+ {
+ ImFormatString(sort_order_suf, IM_ARRAYSIZE(sort_order_suf), "%d", column->SortOrder + 1);
+ w_sort_text = g.Style.ItemInnerSpacing.x + CalcTextSize(sort_order_suf).x;
+ }
+ }
+
+ // We feed our unclipped width to the column without writing on CursorMaxPos, so that column is still considering for merging.
+ float max_pos_x = label_pos.x + label_size.x + w_sort_text + w_arrow;
+ column->ContentMaxXHeadersUsed = ImMax(column->ContentMaxXHeadersUsed, column->WorkMaxX);
+ column->ContentMaxXHeadersIdeal = ImMax(column->ContentMaxXHeadersIdeal, max_pos_x);
+
+ // Keep header highlighted when context menu is open.
+ const bool selected = (table->IsContextPopupOpen && table->ContextPopupColumn == column_n && table->InstanceInteracted == table->InstanceCurrent);
+ ImGuiID id = window->GetID(label);
+ ImRect bb(cell_r.Min.x, cell_r.Min.y, cell_r.Max.x, ImMax(cell_r.Max.y, cell_r.Min.y + label_height + g.Style.CellPadding.y * 2.0f));
+ ItemSize(ImVec2(0.0f, label_height)); // Don't declare unclipped width, it'll be fed ContentMaxPosHeadersIdeal
+ if (!ItemAdd(bb, id))
+ return;
+
+ //GetForegroundDrawList()->AddRect(cell_r.Min, cell_r.Max, IM_COL32(255, 0, 0, 255)); // [DEBUG]
+ //GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 0, 0, 255)); // [DEBUG]
+
+ // Using AllowItemOverlap mode because we cover the whole cell, and we want user to be able to submit subsequent items.
+ bool hovered, held;
+ bool pressed = ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_AllowItemOverlap);
+ if (g.ActiveId != id)
+ SetItemAllowOverlap();
+ if (held || hovered || selected)
+ {
+ const ImU32 col = GetColorU32(held ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
+ //RenderFrame(bb.Min, bb.Max, col, false, 0.0f);
+ TableSetBgColor(ImGuiTableBgTarget_CellBg, col, table->CurrentColumn);
+ RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_TypeThin | ImGuiNavHighlightFlags_NoRounding);
+ }
+ else
+ {
+ // Submit single cell bg color in the case we didn't submit a full header row
+ if ((table->RowFlags & ImGuiTableRowFlags_Headers) == 0)
+ TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_TableHeaderBg), table->CurrentColumn);
+ }
+ if (held)
+ table->HeldHeaderColumn = (ImGuiTableColumnIdx)column_n;
+ window->DC.CursorPos.y -= g.Style.ItemSpacing.y * 0.5f;
+
+ // Drag and drop to re-order columns.
+ // FIXME-TABLE: Scroll request while reordering a column and it lands out of the scrolling zone.
+ if (held && (table->Flags & ImGuiTableFlags_Reorderable) && IsMouseDragging(0) && !g.DragDropActive)
+ {
+ // While moving a column it will jump on the other side of the mouse, so we also test for MouseDelta.x
+ table->ReorderColumn = (ImGuiTableColumnIdx)column_n;
+ table->InstanceInteracted = table->InstanceCurrent;
+
+ // We don't reorder: through the frozen<>unfrozen line, or through a column that is marked with ImGuiTableColumnFlags_NoReorder.
+ if (g.IO.MouseDelta.x < 0.0f && g.IO.MousePos.x < cell_r.Min.x)
+ if (ImGuiTableColumn* prev_column = (column->PrevEnabledColumn != -1) ? &table->Columns[column->PrevEnabledColumn] : NULL)
+ if (!((column->Flags | prev_column->Flags) & ImGuiTableColumnFlags_NoReorder))
+ if ((column->IndexWithinEnabledSet < table->FreezeColumnsRequest) == (prev_column->IndexWithinEnabledSet < table->FreezeColumnsRequest))
+ table->ReorderColumnDir = -1;
+ if (g.IO.MouseDelta.x > 0.0f && g.IO.MousePos.x > cell_r.Max.x)
+ if (ImGuiTableColumn* next_column = (column->NextEnabledColumn != -1) ? &table->Columns[column->NextEnabledColumn] : NULL)
+ if (!((column->Flags | next_column->Flags) & ImGuiTableColumnFlags_NoReorder))
+ if ((column->IndexWithinEnabledSet < table->FreezeColumnsRequest) == (next_column->IndexWithinEnabledSet < table->FreezeColumnsRequest))
+ table->ReorderColumnDir = +1;
+ }
+
+ // Sort order arrow
+ const float ellipsis_max = cell_r.Max.x - w_arrow - w_sort_text;
+ if ((table->Flags & ImGuiTableFlags_Sortable) && !(column->Flags & ImGuiTableColumnFlags_NoSort))
+ {
+ if (column->SortOrder != -1)
+ {
+ float x = ImMax(cell_r.Min.x, cell_r.Max.x - w_arrow - w_sort_text);
+ float y = label_pos.y;
+ if (column->SortOrder > 0)
+ {
+ PushStyleColor(ImGuiCol_Text, GetColorU32(ImGuiCol_Text, 0.70f));
+ RenderText(ImVec2(x + g.Style.ItemInnerSpacing.x, y), sort_order_suf);
+ PopStyleColor();
+ x += w_sort_text;
+ }
+ RenderArrow(window->DrawList, ImVec2(x, y), GetColorU32(ImGuiCol_Text), column->SortDirection == ImGuiSortDirection_Ascending ? ImGuiDir_Up : ImGuiDir_Down, ARROW_SCALE);
+ }
+
+ // Handle clicking on column header to adjust Sort Order
+ if (pressed && table->ReorderColumn != column_n)
+ {
+ ImGuiSortDirection sort_direction = TableGetColumnNextSortDirection(column);
+ TableSetColumnSortDirection(column_n, sort_direction, g.IO.KeyShift);
+ }
+ }
+
+ // Render clipped label. Clipping here ensure that in the majority of situations, all our header cells will
+ // be merged into a single draw call.
+ //window->DrawList->AddCircleFilled(ImVec2(ellipsis_max, label_pos.y), 40, IM_COL32_WHITE);
+ RenderTextEllipsis(window->DrawList, label_pos, ImVec2(ellipsis_max, label_pos.y + label_height + g.Style.FramePadding.y), ellipsis_max, ellipsis_max, label, label_end, &label_size);
+
+ const bool text_clipped = label_size.x > (ellipsis_max - label_pos.x);
+ if (text_clipped && hovered && g.HoveredIdNotActiveTimer > g.TooltipSlowDelay)
+ SetTooltip("%.*s", (int)(label_end - label), label);
+
+ // We don't use BeginPopupContextItem() because we want the popup to stay up even after the column is hidden
+ if (IsMouseReleased(1) && IsItemHovered())
+ TableOpenContextMenu(column_n);
+}
+
+//-------------------------------------------------------------------------
+// [SECTION] Tables: Context Menu
+//-------------------------------------------------------------------------
+// - TableOpenContextMenu() [Internal]
+// - TableDrawContextMenu() [Internal]
+//-------------------------------------------------------------------------
+
+// Use -1 to open menu not specific to a given column.
+void ImGui::TableOpenContextMenu(int column_n)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiTable* table = g.CurrentTable;
+ if (column_n == -1 && table->CurrentColumn != -1) // When called within a column automatically use this one (for consistency)
+ column_n = table->CurrentColumn;
+ if (column_n == table->ColumnsCount) // To facilitate using with TableGetHoveredColumn()
+ column_n = -1;
+ IM_ASSERT(column_n >= -1 && column_n < table->ColumnsCount);
+ if (table->Flags & (ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable))
+ {
+ table->IsContextPopupOpen = true;
+ table->ContextPopupColumn = (ImGuiTableColumnIdx)column_n;
+ table->InstanceInteracted = table->InstanceCurrent;
+ const ImGuiID context_menu_id = ImHashStr("##ContextMenu", 0, table->ID);
+ OpenPopupEx(context_menu_id, ImGuiPopupFlags_None);
+ }
+}
+
+// Output context menu into current window (generally a popup)
+// FIXME-TABLE: Ideally this should be writable by the user. Full programmatic access to that data?
+void ImGui::TableDrawContextMenu(ImGuiTable* table)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ if (window->SkipItems)
+ return;
+
+ bool want_separator = false;
+ const int column_n = (table->ContextPopupColumn >= 0 && table->ContextPopupColumn < table->ColumnsCount) ? table->ContextPopupColumn : -1;
+ ImGuiTableColumn* column = (column_n != -1) ? &table->Columns[column_n] : NULL;
+
+ // Sizing
+ if (table->Flags & ImGuiTableFlags_Resizable)
+ {
+ if (column != NULL)
+ {
+ const bool can_resize = !(column->Flags & ImGuiTableColumnFlags_NoResize) && column->IsEnabled;
+ if (MenuItem("Size column to fit###SizeOne", NULL, false, can_resize))
+ TableSetColumnWidthAutoSingle(table, column_n);
+ }
+
+ const char* size_all_desc;
+ if (table->ColumnsEnabledFixedCount == table->ColumnsEnabledCount && (table->Flags & ImGuiTableFlags_SizingMask_) != ImGuiTableFlags_SizingFixedSame)
+ size_all_desc = "Size all columns to fit###SizeAll"; // All fixed
+ else
+ size_all_desc = "Size all columns to default###SizeAll"; // All stretch or mixed
+ if (MenuItem(size_all_desc, NULL))
+ TableSetColumnWidthAutoAll(table);
+ want_separator = true;
+ }
+
+ // Ordering
+ if (table->Flags & ImGuiTableFlags_Reorderable)
+ {
+ if (MenuItem("Reset order", NULL, false, !table->IsDefaultDisplayOrder))
+ table->IsResetDisplayOrderRequest = true;
+ want_separator = true;
+ }
+
+ // Reset all (should work but seems unnecessary/noisy to expose?)
+ //if (MenuItem("Reset all"))
+ // table->IsResetAllRequest = true;
+
+ // Sorting
+ // (modify TableOpenContextMenu() to add _Sortable flag if enabling this)
+#if 0
+ if ((table->Flags & ImGuiTableFlags_Sortable) && column != NULL && (column->Flags & ImGuiTableColumnFlags_NoSort) == 0)
+ {
+ if (want_separator)
+ Separator();
+ want_separator = true;
+
+ bool append_to_sort_specs = g.IO.KeyShift;
+ if (MenuItem("Sort in Ascending Order", NULL, column->SortOrder != -1 && column->SortDirection == ImGuiSortDirection_Ascending, (column->Flags & ImGuiTableColumnFlags_NoSortAscending) == 0))
+ TableSetColumnSortDirection(table, column_n, ImGuiSortDirection_Ascending, append_to_sort_specs);
+ if (MenuItem("Sort in Descending Order", NULL, column->SortOrder != -1 && column->SortDirection == ImGuiSortDirection_Descending, (column->Flags & ImGuiTableColumnFlags_NoSortDescending) == 0))
+ TableSetColumnSortDirection(table, column_n, ImGuiSortDirection_Descending, append_to_sort_specs);
+ }
+#endif
+
+ // Hiding / Visibility
+ if (table->Flags & ImGuiTableFlags_Hideable)
+ {
+ if (want_separator)
+ Separator();
+ want_separator = true;
+
+ PushItemFlag(ImGuiItemFlags_SelectableDontClosePopup, true);
+ for (int other_column_n = 0; other_column_n < table->ColumnsCount; other_column_n++)
+ {
+ ImGuiTableColumn* other_column = &table->Columns[other_column_n];
+ const char* name = TableGetColumnName(table, other_column_n);
+ if (name == NULL || name[0] == 0)
+ name = "";
+
+ // Make sure we can't hide the last active column
+ bool menu_item_active = (other_column->Flags & ImGuiTableColumnFlags_NoHide) ? false : true;
+ if (other_column->IsEnabled && table->ColumnsEnabledCount <= 1)
+ menu_item_active = false;
+ if (MenuItem(name, NULL, other_column->IsEnabled, menu_item_active))
+ other_column->IsEnabledNextFrame = !other_column->IsEnabled;
+ }
+ PopItemFlag();
+ }
+}
+
+//-------------------------------------------------------------------------
+// [SECTION] Tables: Settings (.ini data)
+//-------------------------------------------------------------------------
+// FIXME: The binding/finding/creating flow are too confusing.
+//-------------------------------------------------------------------------
+// - TableSettingsInit() [Internal]
+// - TableSettingsCalcChunkSize() [Internal]
+// - TableSettingsCreate() [Internal]
+// - TableSettingsFindByID() [Internal]
+// - TableGetBoundSettings() [Internal]
+// - TableResetSettings()
+// - TableSaveSettings() [Internal]
+// - TableLoadSettings() [Internal]
+// - TableSettingsHandler_ClearAll() [Internal]
+// - TableSettingsHandler_ApplyAll() [Internal]
+// - TableSettingsHandler_ReadOpen() [Internal]
+// - TableSettingsHandler_ReadLine() [Internal]
+// - TableSettingsHandler_WriteAll() [Internal]
+// - TableSettingsInstallHandler() [Internal]
+//-------------------------------------------------------------------------
+// [Init] 1: TableSettingsHandler_ReadXXXX() Load and parse .ini file into TableSettings.
+// [Main] 2: TableLoadSettings() When table is created, bind Table to TableSettings, serialize TableSettings data into Table.
+// [Main] 3: TableSaveSettings() When table properties are modified, serialize Table data into bound or new TableSettings, mark .ini as dirty.
+// [Main] 4: TableSettingsHandler_WriteAll() When .ini file is dirty (which can come from other source), save TableSettings into .ini file.
+//-------------------------------------------------------------------------
+
+// Clear and initialize empty settings instance
+static void TableSettingsInit(ImGuiTableSettings* settings, ImGuiID id, int columns_count, int columns_count_max)
+{
+ IM_PLACEMENT_NEW(settings) ImGuiTableSettings();
+ ImGuiTableColumnSettings* settings_column = settings->GetColumnSettings();
+ for (int n = 0; n < columns_count_max; n++, settings_column++)
+ IM_PLACEMENT_NEW(settings_column) ImGuiTableColumnSettings();
+ settings->ID = id;
+ settings->ColumnsCount = (ImGuiTableColumnIdx)columns_count;
+ settings->ColumnsCountMax = (ImGuiTableColumnIdx)columns_count_max;
+ settings->WantApply = true;
+}
+
+static size_t TableSettingsCalcChunkSize(int columns_count)
+{
+ return sizeof(ImGuiTableSettings) + (size_t)columns_count * sizeof(ImGuiTableColumnSettings);
+}
+
+ImGuiTableSettings* ImGui::TableSettingsCreate(ImGuiID id, int columns_count)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiTableSettings* settings = g.SettingsTables.alloc_chunk(TableSettingsCalcChunkSize(columns_count));
+ TableSettingsInit(settings, id, columns_count, columns_count);
+ return settings;
+}
+
+// Find existing settings
+ImGuiTableSettings* ImGui::TableSettingsFindByID(ImGuiID id)
+{
+ // FIXME-OPT: Might want to store a lookup map for this?
+ ImGuiContext& g = *GImGui;
+ for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
+ if (settings->ID == id)
+ return settings;
+ return NULL;
+}
+
+// Get settings for a given table, NULL if none
+ImGuiTableSettings* ImGui::TableGetBoundSettings(ImGuiTable* table)
+{
+ if (table->SettingsOffset != -1)
+ {
+ ImGuiContext& g = *GImGui;
+ ImGuiTableSettings* settings = g.SettingsTables.ptr_from_offset(table->SettingsOffset);
+ IM_ASSERT(settings->ID == table->ID);
+ if (settings->ColumnsCountMax >= table->ColumnsCount)
+ return settings; // OK
+ settings->ID = 0; // Invalidate storage, we won't fit because of a count change
+ }
+ return NULL;
+}
+
+// Restore initial state of table (with or without saved settings)
+void ImGui::TableResetSettings(ImGuiTable* table)
+{
+ table->IsInitializing = table->IsSettingsDirty = true;
+ table->IsResetAllRequest = false;
+ table->IsSettingsRequestLoad = false; // Don't reload from ini
+ table->SettingsLoadedFlags = ImGuiTableFlags_None; // Mark as nothing loaded so our initialized data becomes authoritative
+}
+
+void ImGui::TableSaveSettings(ImGuiTable* table)
+{
+ table->IsSettingsDirty = false;
+ if (table->Flags & ImGuiTableFlags_NoSavedSettings)
+ return;
+
+ // Bind or create settings data
+ ImGuiContext& g = *GImGui;
+ ImGuiTableSettings* settings = TableGetBoundSettings(table);
+ if (settings == NULL)
+ {
+ settings = TableSettingsCreate(table->ID, table->ColumnsCount);
+ table->SettingsOffset = g.SettingsTables.offset_from_ptr(settings);
+ }
+ settings->ColumnsCount = (ImGuiTableColumnIdx)table->ColumnsCount;
+
+ // Serialize ImGuiTable/ImGuiTableColumn into ImGuiTableSettings/ImGuiTableColumnSettings
+ IM_ASSERT(settings->ID == table->ID);
+ IM_ASSERT(settings->ColumnsCount == table->ColumnsCount && settings->ColumnsCountMax >= settings->ColumnsCount);
+ ImGuiTableColumn* column = table->Columns.Data;
+ ImGuiTableColumnSettings* column_settings = settings->GetColumnSettings();
+
+ bool save_ref_scale = false;
+ settings->SaveFlags = ImGuiTableFlags_None;
+ for (int n = 0; n < table->ColumnsCount; n++, column++, column_settings++)
+ {
+ const float width_or_weight = (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? column->StretchWeight : column->WidthRequest;
+ column_settings->WidthOrWeight = width_or_weight;
+ column_settings->Index = (ImGuiTableColumnIdx)n;
+ column_settings->DisplayOrder = column->DisplayOrder;
+ column_settings->SortOrder = column->SortOrder;
+ column_settings->SortDirection = column->SortDirection;
+ column_settings->IsEnabled = column->IsEnabled;
+ column_settings->IsStretch = (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? 1 : 0;
+ if ((column->Flags & ImGuiTableColumnFlags_WidthStretch) == 0)
+ save_ref_scale = true;
+
+ // We skip saving some data in the .ini file when they are unnecessary to restore our state.
+ // Note that fixed width where initial width was derived from auto-fit will always be saved as InitStretchWeightOrWidth will be 0.0f.
+ // FIXME-TABLE: We don't have logic to easily compare SortOrder to DefaultSortOrder yet so it's always saved when present.
+ if (width_or_weight != column->InitStretchWeightOrWidth)
+ settings->SaveFlags |= ImGuiTableFlags_Resizable;
+ if (column->DisplayOrder != n)
+ settings->SaveFlags |= ImGuiTableFlags_Reorderable;
+ if (column->SortOrder != -1)
+ settings->SaveFlags |= ImGuiTableFlags_Sortable;
+ if (column->IsEnabled != ((column->Flags & ImGuiTableColumnFlags_DefaultHide) == 0))
+ settings->SaveFlags |= ImGuiTableFlags_Hideable;
+ }
+ settings->SaveFlags &= table->Flags;
+ settings->RefScale = save_ref_scale ? table->RefScale : 0.0f;
+
+ MarkIniSettingsDirty();
+}
+
+void ImGui::TableLoadSettings(ImGuiTable* table)
+{
+ ImGuiContext& g = *GImGui;
+ table->IsSettingsRequestLoad = false;
+ if (table->Flags & ImGuiTableFlags_NoSavedSettings)
+ return;
+
+ // Bind settings
+ ImGuiTableSettings* settings;
+ if (table->SettingsOffset == -1)
+ {
+ settings = TableSettingsFindByID(table->ID);
+ if (settings == NULL)
+ return;
+ if (settings->ColumnsCount != table->ColumnsCount) // Allow settings if columns count changed. We could otherwise decide to return...
+ table->IsSettingsDirty = true;
+ table->SettingsOffset = g.SettingsTables.offset_from_ptr(settings);
+ }
+ else
+ {
+ settings = TableGetBoundSettings(table);
+ }
+
+ table->SettingsLoadedFlags = settings->SaveFlags;
+ table->RefScale = settings->RefScale;
+
+ // Serialize ImGuiTableSettings/ImGuiTableColumnSettings into ImGuiTable/ImGuiTableColumn
+ ImGuiTableColumnSettings* column_settings = settings->GetColumnSettings();
+ ImU64 display_order_mask = 0;
+ for (int data_n = 0; data_n < settings->ColumnsCount; data_n++, column_settings++)
+ {
+ int column_n = column_settings->Index;
+ if (column_n < 0 || column_n >= table->ColumnsCount)
+ continue;
+
+ ImGuiTableColumn* column = &table->Columns[column_n];
+ if (settings->SaveFlags & ImGuiTableFlags_Resizable)
+ {
+ if (column_settings->IsStretch)
+ column->StretchWeight = column_settings->WidthOrWeight;
+ else
+ column->WidthRequest = column_settings->WidthOrWeight;
+ column->AutoFitQueue = 0x00;
+ }
+ if (settings->SaveFlags & ImGuiTableFlags_Reorderable)
+ column->DisplayOrder = column_settings->DisplayOrder;
+ else
+ column->DisplayOrder = (ImGuiTableColumnIdx)column_n;
+ display_order_mask |= (ImU64)1 << column->DisplayOrder;
+ column->IsEnabled = column->IsEnabledNextFrame = column_settings->IsEnabled;
+ column->SortOrder = column_settings->SortOrder;
+ column->SortDirection = column_settings->SortDirection;
+ }
+
+ // Validate and fix invalid display order data
+ const ImU64 expected_display_order_mask = (settings->ColumnsCount == 64) ? ~0 : ((ImU64)1 << settings->ColumnsCount) - 1;
+ if (display_order_mask != expected_display_order_mask)
+ for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
+ table->Columns[column_n].DisplayOrder = (ImGuiTableColumnIdx)column_n;
+
+ // Rebuild index
+ for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
+ table->DisplayOrderToIndex[table->Columns[column_n].DisplayOrder] = (ImGuiTableColumnIdx)column_n;
+}
+
+static void TableSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
+{
+ ImGuiContext& g = *ctx;
+ for (int i = 0; i != g.Tables.GetSize(); i++)
+ g.Tables.GetByIndex(i)->SettingsOffset = -1;
+ g.SettingsTables.clear();
+}
+
+// Apply to existing windows (if any)
+static void TableSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
+{
+ ImGuiContext& g = *ctx;
+ for (int i = 0; i != g.Tables.GetSize(); i++)
+ {
+ ImGuiTable* table = g.Tables.GetByIndex(i);
+ table->IsSettingsRequestLoad = true;
+ table->SettingsOffset = -1;
+ }
+}
+
+static void* TableSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
+{
+ ImGuiID id = 0;
+ int columns_count = 0;
+ if (sscanf(name, "0x%08X,%d", &id, &columns_count) < 2)
+ return NULL;
+
+ if (ImGuiTableSettings* settings = ImGui::TableSettingsFindByID(id))
+ {
+ if (settings->ColumnsCountMax >= columns_count)
+ {
+ TableSettingsInit(settings, id, columns_count, settings->ColumnsCountMax); // Recycle
+ return settings;
+ }
+ settings->ID = 0; // Invalidate storage, we won't fit because of a count change
+ }
+ return ImGui::TableSettingsCreate(id, columns_count);
+}
+
+static void TableSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
+{
+ // "Column 0 UserID=0x42AD2D21 Width=100 Visible=1 Order=0 Sort=0v"
+ ImGuiTableSettings* settings = (ImGuiTableSettings*)entry;
+ float f = 0.0f;
+ int column_n = 0, r = 0, n = 0;
+
+ if (sscanf(line, "RefScale=%f", &f) == 1) { settings->RefScale = f; return; }
+
+ if (sscanf(line, "Column %d%n", &column_n, &r) == 1)
+ {
+ if (column_n < 0 || column_n >= settings->ColumnsCount)
+ return;
+ line = ImStrSkipBlank(line + r);
+ char c = 0;
+ ImGuiTableColumnSettings* column = settings->GetColumnSettings() + column_n;
+ column->Index = (ImGuiTableColumnIdx)column_n;
+ if (sscanf(line, "UserID=0x%08X%n", (ImU32*)&n, &r)==1) { line = ImStrSkipBlank(line + r); column->UserID = (ImGuiID)n; }
+ if (sscanf(line, "Width=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->WidthOrWeight = (float)n; column->IsStretch = 0; settings->SaveFlags |= ImGuiTableFlags_Resizable; }
+ if (sscanf(line, "Weight=%f%n", &f, &r) == 1) { line = ImStrSkipBlank(line + r); column->WidthOrWeight = f; column->IsStretch = 1; settings->SaveFlags |= ImGuiTableFlags_Resizable; }
+ if (sscanf(line, "Visible=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->IsEnabled = (ImU8)n; settings->SaveFlags |= ImGuiTableFlags_Hideable; }
+ if (sscanf(line, "Order=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->DisplayOrder = (ImGuiTableColumnIdx)n; settings->SaveFlags |= ImGuiTableFlags_Reorderable; }
+ if (sscanf(line, "Sort=%d%c%n", &n, &c, &r) == 2) { line = ImStrSkipBlank(line + r); column->SortOrder = (ImGuiTableColumnIdx)n; column->SortDirection = (c == '^') ? ImGuiSortDirection_Descending : ImGuiSortDirection_Ascending; settings->SaveFlags |= ImGuiTableFlags_Sortable; }
+ }
+}
+
+static void TableSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
+{
+ ImGuiContext& g = *ctx;
+ for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
+ {
+ if (settings->ID == 0) // Skip ditched settings
+ continue;
+
+ // TableSaveSettings() may clear some of those flags when we establish that the data can be stripped
+ // (e.g. Order was unchanged)
+ const bool save_size = (settings->SaveFlags & ImGuiTableFlags_Resizable) != 0;
+ const bool save_visible = (settings->SaveFlags & ImGuiTableFlags_Hideable) != 0;
+ const bool save_order = (settings->SaveFlags & ImGuiTableFlags_Reorderable) != 0;
+ const bool save_sort = (settings->SaveFlags & ImGuiTableFlags_Sortable) != 0;
+ if (!save_size && !save_visible && !save_order && !save_sort)
+ continue;
+
+ buf->reserve(buf->size() + 30 + settings->ColumnsCount * 50); // ballpark reserve
+ buf->appendf("[%s][0x%08X,%d]\n", handler->TypeName, settings->ID, settings->ColumnsCount);
+ if (settings->RefScale != 0.0f)
+ buf->appendf("RefScale=%g\n", settings->RefScale);
+ ImGuiTableColumnSettings* column = settings->GetColumnSettings();
+ for (int column_n = 0; column_n < settings->ColumnsCount; column_n++, column++)
+ {
+ // "Column 0 UserID=0x42AD2D21 Width=100 Visible=1 Order=0 Sort=0v"
+ buf->appendf("Column %-2d", column_n);
+ if (column->UserID != 0) buf->appendf(" UserID=%08X", column->UserID);
+ if (save_size && column->IsStretch) buf->appendf(" Weight=%.4f", column->WidthOrWeight);
+ if (save_size && !column->IsStretch) buf->appendf(" Width=%d", (int)column->WidthOrWeight);
+ if (save_visible) buf->appendf(" Visible=%d", column->IsEnabled);
+ if (save_order) buf->appendf(" Order=%d", column->DisplayOrder);
+ if (save_sort && column->SortOrder != -1) buf->appendf(" Sort=%d%c", column->SortOrder, (column->SortDirection == ImGuiSortDirection_Ascending) ? 'v' : '^');
+ buf->append("\n");
+ }
+ buf->append("\n");
+ }
+}
+
+void ImGui::TableSettingsInstallHandler(ImGuiContext* context)
+{
+ ImGuiContext& g = *context;
+ ImGuiSettingsHandler ini_handler;
+ ini_handler.TypeName = "Table";
+ ini_handler.TypeHash = ImHashStr("Table");
+ ini_handler.ClearAllFn = TableSettingsHandler_ClearAll;
+ ini_handler.ReadOpenFn = TableSettingsHandler_ReadOpen;
+ ini_handler.ReadLineFn = TableSettingsHandler_ReadLine;
+ ini_handler.ApplyAllFn = TableSettingsHandler_ApplyAll;
+ ini_handler.WriteAllFn = TableSettingsHandler_WriteAll;
+ g.SettingsHandlers.push_back(ini_handler);
+}
+
+//-------------------------------------------------------------------------
+// [SECTION] Tables: Garbage Collection
+//-------------------------------------------------------------------------
+// - TableRemove() [Internal]
+// - TableGcCompactTransientBuffers() [Internal]
+// - TableGcCompactSettings() [Internal]
+//-------------------------------------------------------------------------
+
+// Remove Table (currently only used by TestEngine)
+void ImGui::TableRemove(ImGuiTable* table)
+{
+ //IMGUI_DEBUG_LOG("TableRemove() id=0x%08X\n", table->ID);
+ ImGuiContext& g = *GImGui;
+ int table_idx = g.Tables.GetIndex(table);
+ //memset(table->RawData.Data, 0, table->RawData.size_in_bytes());
+ //memset(table, 0, sizeof(ImGuiTable));
+ g.Tables.Remove(table->ID, table);
+ g.TablesLastTimeActive[table_idx] = -1.0f;
+}
+
+// Free up/compact internal Table buffers for when it gets unused
+void ImGui::TableGcCompactTransientBuffers(ImGuiTable* table)
+{
+ //IMGUI_DEBUG_LOG("TableGcCompactTransientBuffers() id=0x%08X\n", table->ID);
+ ImGuiContext& g = *GImGui;
+ IM_ASSERT(table->MemoryCompacted == false);
+ table->DrawSplitter.ClearFreeMemory();
+ table->SortSpecsMulti.clear();
+ table->SortSpecs.Specs = NULL;
+ table->IsSortSpecsDirty = true;
+ table->ColumnsNames.clear();
+ table->MemoryCompacted = true;
+ for (int n = 0; n < table->ColumnsCount; n++)
+ table->Columns[n].NameOffset = -1;
+ g.TablesLastTimeActive[g.Tables.GetIndex(table)] = -1.0f;
+}
+
+// Compact and remove unused settings data (currently only used by TestEngine)
+void ImGui::TableGcCompactSettings()
+{
+ ImGuiContext& g = *GImGui;
+ int required_memory = 0;
+ for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
+ if (settings->ID != 0)
+ required_memory += (int)TableSettingsCalcChunkSize(settings->ColumnsCount);
+ if (required_memory == g.SettingsTables.Buf.Size)
+ return;
+ ImChunkStream new_chunk_stream;
+ new_chunk_stream.Buf.reserve(required_memory);
+ for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
+ if (settings->ID != 0)
+ memcpy(new_chunk_stream.alloc_chunk(TableSettingsCalcChunkSize(settings->ColumnsCount)), settings, TableSettingsCalcChunkSize(settings->ColumnsCount));
+ g.SettingsTables.swap(new_chunk_stream);
+}
+
+
+//-------------------------------------------------------------------------
+// [SECTION] Tables: Debugging
+//-------------------------------------------------------------------------
+// - DebugNodeTable() [Internal]
+//-------------------------------------------------------------------------
+
+#ifndef IMGUI_DISABLE_METRICS_WINDOW
+
+static const char* DebugNodeTableGetSizingPolicyDesc(ImGuiTableFlags sizing_policy)
+{
+ sizing_policy &= ImGuiTableFlags_SizingMask_;
+ if (sizing_policy == ImGuiTableFlags_SizingFixedFit) { return "FixedFit"; }
+ if (sizing_policy == ImGuiTableFlags_SizingFixedSame) { return "FixedSame"; }
+ if (sizing_policy == ImGuiTableFlags_SizingStretchProp) { return "StretchProp"; }
+ if (sizing_policy == ImGuiTableFlags_SizingStretchSame) { return "StretchSame"; }
+ return "N/A";
+}
+
+void ImGui::DebugNodeTable(ImGuiTable* table)
+{
+ char buf[512];
+ char* p = buf;
+ const char* buf_end = buf + IM_ARRAYSIZE(buf);
+ const bool is_active = (table->LastFrameActive >= ImGui::GetFrameCount() - 2); // Note that fully clipped early out scrolling tables will appear as inactive here.
+ ImFormatString(p, buf_end - p, "Table 0x%08X (%d columns, in '%s')%s", table->ID, table->ColumnsCount, table->OuterWindow->Name, is_active ? "" : " *Inactive*");
+ if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
+ bool open = TreeNode(table, "%s", buf);
+ if (!is_active) { PopStyleColor(); }
+ if (IsItemHovered())
+ GetForegroundDrawList()->AddRect(table->OuterRect.Min, table->OuterRect.Max, IM_COL32(255, 255, 0, 255));
+ if (IsItemVisible() && table->HoveredColumnBody != -1)
+ GetForegroundDrawList()->AddRect(GetItemRectMin(), GetItemRectMax(), IM_COL32(255, 255, 0, 255));
+ if (!open)
+ return;
+ bool clear_settings = SmallButton("Clear settings");
+ BulletText("OuterRect: Pos: (%.1f,%.1f) Size: (%.1f,%.1f) Sizing: '%s'", table->OuterRect.Min.x, table->OuterRect.Min.y, table->OuterRect.GetWidth(), table->OuterRect.GetHeight(), DebugNodeTableGetSizingPolicyDesc(table->Flags));
+ BulletText("ColumnsGivenWidth: %.1f, ColumnsAutoFitWidth: %.1f, InnerWidth: %.1f%s", table->ColumnsGivenWidth, table->ColumnsAutoFitWidth, table->InnerWidth, table->InnerWidth == 0.0f ? " (auto)" : "");
+ BulletText("CellPaddingX: %.1f, CellSpacingX: %.1f/%.1f, OuterPaddingX: %.1f", table->CellPaddingX, table->CellSpacingX1, table->CellSpacingX2, table->OuterPaddingX);
+ BulletText("HoveredColumnBody: %d, HoveredColumnBorder: %d", table->HoveredColumnBody, table->HoveredColumnBorder);
+ BulletText("ResizedColumn: %d, ReorderColumn: %d, HeldHeaderColumn: %d", table->ResizedColumn, table->ReorderColumn, table->HeldHeaderColumn);
+ //BulletText("BgDrawChannels: %d/%d", 0, table->BgDrawChannelUnfrozen);
+ float sum_weights = 0.0f;
+ for (int n = 0; n < table->ColumnsCount; n++)
+ if (table->Columns[n].Flags & ImGuiTableColumnFlags_WidthStretch)
+ sum_weights += table->Columns[n].StretchWeight;
+ for (int n = 0; n < table->ColumnsCount; n++)
+ {
+ ImGuiTableColumn* column = &table->Columns[n];
+ const char* name = TableGetColumnName(table, n);
+ ImFormatString(buf, IM_ARRAYSIZE(buf),
+ "Column %d order %d '%s': offset %+.2f to %+.2f%s\n"
+ "Enabled: %d, VisibleX/Y: %d/%d, RequestOutput: %d, SkipItems: %d, DrawChannels: %d,%d\n"
+ "WidthGiven: %.1f, Request/Auto: %.1f/%.1f, StretchWeight: %.3f (%.1f%%)\n"
+ "MinX: %.1f, MaxX: %.1f (%+.1f), ClipRect: %.1f to %.1f (+%.1f)\n"
+ "ContentWidth: %.1f,%.1f, HeadersUsed/Ideal %.1f/%.1f\n"
+ "Sort: %d%s, UserID: 0x%08X, Flags: 0x%04X: %s%s%s..",
+ n, column->DisplayOrder, name, column->MinX - table->WorkRect.Min.x, column->MaxX - table->WorkRect.Min.x, (n < table->FreezeColumnsRequest) ? " (Frozen)" : "",
+ column->IsEnabled, column->IsVisibleX, column->IsVisibleY, column->IsRequestOutput, column->IsSkipItems, column->DrawChannelFrozen, column->DrawChannelUnfrozen,
+ column->WidthGiven, column->WidthRequest, column->WidthAuto, column->StretchWeight, column->StretchWeight > 0.0f ? (column->StretchWeight / sum_weights) * 100.0f : 0.0f,
+ column->MinX, column->MaxX, column->MaxX - column->MinX, column->ClipRect.Min.x, column->ClipRect.Max.x, column->ClipRect.Max.x - column->ClipRect.Min.x,
+ column->ContentMaxXFrozen - column->WorkMinX, column->ContentMaxXUnfrozen - column->WorkMinX, column->ContentMaxXHeadersUsed - column->WorkMinX, column->ContentMaxXHeadersIdeal - column->WorkMinX,
+ column->SortOrder, (column->SortDirection == ImGuiSortDirection_Ascending) ? " (Asc)" : (column->SortDirection == ImGuiSortDirection_Descending) ? " (Des)" : "", column->UserID, column->Flags,
+ (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? "WidthStretch " : "",
+ (column->Flags & ImGuiTableColumnFlags_WidthFixed) ? "WidthFixed " : "",
+ (column->Flags & ImGuiTableColumnFlags_NoResize) ? "NoResize " : "");
+ Bullet();
+ Selectable(buf);
+ if (IsItemHovered())
+ {
+ ImRect r(column->MinX, table->OuterRect.Min.y, column->MaxX, table->OuterRect.Max.y);
+ GetForegroundDrawList()->AddRect(r.Min, r.Max, IM_COL32(255, 255, 0, 255));
+ }
+ }
+ if (ImGuiTableSettings* settings = TableGetBoundSettings(table))
+ DebugNodeTableSettings(settings);
+ if (clear_settings)
+ table->IsResetAllRequest = true;
+ TreePop();
+}
+
+void ImGui::DebugNodeTableSettings(ImGuiTableSettings* settings)
+{
+ if (!TreeNode((void*)(intptr_t)settings->ID, "Settings 0x%08X (%d columns)", settings->ID, settings->ColumnsCount))
+ return;
+ BulletText("SaveFlags: 0x%08X", settings->SaveFlags);
+ BulletText("ColumnsCount: %d (max %d)", settings->ColumnsCount, settings->ColumnsCountMax);
+ for (int n = 0; n < settings->ColumnsCount; n++)
+ {
+ ImGuiTableColumnSettings* column_settings = &settings->GetColumnSettings()[n];
+ ImGuiSortDirection sort_dir = (column_settings->SortOrder != -1) ? (ImGuiSortDirection)column_settings->SortDirection : ImGuiSortDirection_None;
+ BulletText("Column %d Order %d SortOrder %d %s Vis %d %s %7.3f UserID 0x%08X",
+ n, column_settings->DisplayOrder, column_settings->SortOrder,
+ (sort_dir == ImGuiSortDirection_Ascending) ? "Asc" : (sort_dir == ImGuiSortDirection_Descending) ? "Des" : "---",
+ column_settings->IsEnabled, column_settings->IsStretch ? "Weight" : "Width ", column_settings->WidthOrWeight, column_settings->UserID);
+ }
+ TreePop();
+}
+
+#else // #ifndef IMGUI_DISABLE_METRICS_WINDOW
+
+void ImGui::DebugNodeTable(ImGuiTable*) {}
+void ImGui::DebugNodeTableSettings(ImGuiTableSettings*) {}
+
+#endif
+
+
+//-------------------------------------------------------------------------
+// [SECTION] Columns, BeginColumns, EndColumns, etc.
+// (This is a legacy API, prefer using BeginTable/EndTable!)
+//-------------------------------------------------------------------------
+// FIXME: sizing is lossy when columns width is very small (default width may turn negative etc.)
+//-------------------------------------------------------------------------
+// - SetWindowClipRectBeforeSetChannel() [Internal]
+// - GetColumnIndex()
+// - GetColumnsCount()
+// - GetColumnOffset()
+// - GetColumnWidth()
+// - SetColumnOffset()
+// - SetColumnWidth()
+// - PushColumnClipRect() [Internal]
+// - PushColumnsBackground() [Internal]
+// - PopColumnsBackground() [Internal]
+// - FindOrCreateColumns() [Internal]
+// - GetColumnsID() [Internal]
+// - BeginColumns()
+// - NextColumn()
+// - EndColumns()
+// - Columns()
+//-------------------------------------------------------------------------
+
+// [Internal] Small optimization to avoid calls to PopClipRect/SetCurrentChannel/PushClipRect in sequences,
+// they would meddle many times with the underlying ImDrawCmd.
+// Instead, we do a preemptive overwrite of clipping rectangle _without_ altering the command-buffer and let
+// the subsequent single call to SetCurrentChannel() does it things once.
+void ImGui::SetWindowClipRectBeforeSetChannel(ImGuiWindow* window, const ImRect& clip_rect)
+{
+ ImVec4 clip_rect_vec4 = clip_rect.ToVec4();
+ window->ClipRect = clip_rect;
+ window->DrawList->_CmdHeader.ClipRect = clip_rect_vec4;
+ window->DrawList->_ClipRectStack.Data[window->DrawList->_ClipRectStack.Size - 1] = clip_rect_vec4;
+}
+
+int ImGui::GetColumnIndex()
+{
+ ImGuiWindow* window = GetCurrentWindowRead();
+ return window->DC.CurrentColumns ? window->DC.CurrentColumns->Current : 0;
+}
+
+int ImGui::GetColumnsCount()
+{
+ ImGuiWindow* window = GetCurrentWindowRead();
+ return window->DC.CurrentColumns ? window->DC.CurrentColumns->Count : 1;
+}
+
+float ImGui::GetColumnOffsetFromNorm(const ImGuiOldColumns* columns, float offset_norm)
+{
+ return offset_norm * (columns->OffMaxX - columns->OffMinX);
+}
+
+float ImGui::GetColumnNormFromOffset(const ImGuiOldColumns* columns, float offset)
+{
+ return offset / (columns->OffMaxX - columns->OffMinX);
+}
+
+static const float COLUMNS_HIT_RECT_HALF_WIDTH = 4.0f;
+
+static float GetDraggedColumnOffset(ImGuiOldColumns* columns, int column_index)
+{
+ // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing
+ // window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning.
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ IM_ASSERT(column_index > 0); // We are not supposed to drag column 0.
+ IM_ASSERT(g.ActiveId == columns->ID + ImGuiID(column_index));
+
+ float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x + COLUMNS_HIT_RECT_HALF_WIDTH - window->Pos.x;
+ x = ImMax(x, ImGui::GetColumnOffset(column_index - 1) + g.Style.ColumnsMinSpacing);
+ if ((columns->Flags & ImGuiOldColumnFlags_NoPreserveWidths))
+ x = ImMin(x, ImGui::GetColumnOffset(column_index + 1) - g.Style.ColumnsMinSpacing);
+
+ return x;
+}
+
+float ImGui::GetColumnOffset(int column_index)
+{
+ ImGuiWindow* window = GetCurrentWindowRead();
+ ImGuiOldColumns* columns = window->DC.CurrentColumns;
+ if (columns == NULL)
+ return 0.0f;
+
+ if (column_index < 0)
+ column_index = columns->Current;
+ IM_ASSERT(column_index < columns->Columns.Size);
+
+ const float t = columns->Columns[column_index].OffsetNorm;
+ const float x_offset = ImLerp(columns->OffMinX, columns->OffMaxX, t);
+ return x_offset;
+}
+
+static float GetColumnWidthEx(ImGuiOldColumns* columns, int column_index, bool before_resize = false)
+{
+ if (column_index < 0)
+ column_index = columns->Current;
+
+ float offset_norm;
+ if (before_resize)
+ offset_norm = columns->Columns[column_index + 1].OffsetNormBeforeResize - columns->Columns[column_index].OffsetNormBeforeResize;
+ else
+ offset_norm = columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm;
+ return ImGui::GetColumnOffsetFromNorm(columns, offset_norm);
+}
+
+float ImGui::GetColumnWidth(int column_index)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ ImGuiOldColumns* columns = window->DC.CurrentColumns;
+ if (columns == NULL)
+ return GetContentRegionAvail().x;
+
+ if (column_index < 0)
+ column_index = columns->Current;
+ return GetColumnOffsetFromNorm(columns, columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm);
+}
+
+void ImGui::SetColumnOffset(int column_index, float offset)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ ImGuiOldColumns* columns = window->DC.CurrentColumns;
+ IM_ASSERT(columns != NULL);
+
+ if (column_index < 0)
+ column_index = columns->Current;
+ IM_ASSERT(column_index < columns->Columns.Size);
+
+ const bool preserve_width = !(columns->Flags & ImGuiOldColumnFlags_NoPreserveWidths) && (column_index < columns->Count - 1);
+ const float width = preserve_width ? GetColumnWidthEx(columns, column_index, columns->IsBeingResized) : 0.0f;
+
+ if (!(columns->Flags & ImGuiOldColumnFlags_NoForceWithinWindow))
+ offset = ImMin(offset, columns->OffMaxX - g.Style.ColumnsMinSpacing * (columns->Count - column_index));
+ columns->Columns[column_index].OffsetNorm = GetColumnNormFromOffset(columns, offset - columns->OffMinX);
+
+ if (preserve_width)
+ SetColumnOffset(column_index + 1, offset + ImMax(g.Style.ColumnsMinSpacing, width));
+}
+
+void ImGui::SetColumnWidth(int column_index, float width)
+{
+ ImGuiWindow* window = GetCurrentWindowRead();
+ ImGuiOldColumns* columns = window->DC.CurrentColumns;
+ IM_ASSERT(columns != NULL);
+
+ if (column_index < 0)
+ column_index = columns->Current;
+ SetColumnOffset(column_index + 1, GetColumnOffset(column_index) + width);
+}
+
+void ImGui::PushColumnClipRect(int column_index)
+{
+ ImGuiWindow* window = GetCurrentWindowRead();
+ ImGuiOldColumns* columns = window->DC.CurrentColumns;
+ if (column_index < 0)
+ column_index = columns->Current;
+
+ ImGuiOldColumnData* column = &columns->Columns[column_index];
+ PushClipRect(column->ClipRect.Min, column->ClipRect.Max, false);
+}
+
+// Get into the columns background draw command (which is generally the same draw command as before we called BeginColumns)
+void ImGui::PushColumnsBackground()
+{
+ ImGuiWindow* window = GetCurrentWindowRead();
+ ImGuiOldColumns* columns = window->DC.CurrentColumns;
+ if (columns->Count == 1)
+ return;
+
+ // Optimization: avoid SetCurrentChannel() + PushClipRect()
+ columns->HostBackupClipRect = window->ClipRect;
+ SetWindowClipRectBeforeSetChannel(window, columns->HostInitialClipRect);
+ columns->Splitter.SetCurrentChannel(window->DrawList, 0);
+}
+
+void ImGui::PopColumnsBackground()
+{
+ ImGuiWindow* window = GetCurrentWindowRead();
+ ImGuiOldColumns* columns = window->DC.CurrentColumns;
+ if (columns->Count == 1)
+ return;
+
+ // Optimization: avoid PopClipRect() + SetCurrentChannel()
+ SetWindowClipRectBeforeSetChannel(window, columns->HostBackupClipRect);
+ columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1);
+}
+
+ImGuiOldColumns* ImGui::FindOrCreateColumns(ImGuiWindow* window, ImGuiID id)
+{
+ // We have few columns per window so for now we don't need bother much with turning this into a faster lookup.
+ for (int n = 0; n < window->ColumnsStorage.Size; n++)
+ if (window->ColumnsStorage[n].ID == id)
+ return &window->ColumnsStorage[n];
+
+ window->ColumnsStorage.push_back(ImGuiOldColumns());
+ ImGuiOldColumns* columns = &window->ColumnsStorage.back();
+ columns->ID = id;
+ return columns;
+}
+
+ImGuiID ImGui::GetColumnsID(const char* str_id, int columns_count)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+
+ // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget.
+ // In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer.
+ PushID(0x11223347 + (str_id ? 0 : columns_count));
+ ImGuiID id = window->GetID(str_id ? str_id : "columns");
+ PopID();
+
+ return id;
+}
+
+void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiOldColumnFlags flags)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = GetCurrentWindow();
+
+ IM_ASSERT(columns_count >= 1);
+ IM_ASSERT(window->DC.CurrentColumns == NULL); // Nested columns are currently not supported
+
+ // Acquire storage for the columns set
+ ImGuiID id = GetColumnsID(str_id, columns_count);
+ ImGuiOldColumns* columns = FindOrCreateColumns(window, id);
+ IM_ASSERT(columns->ID == id);
+ columns->Current = 0;
+ columns->Count = columns_count;
+ columns->Flags = flags;
+ window->DC.CurrentColumns = columns;
+
+ columns->HostCursorPosY = window->DC.CursorPos.y;
+ columns->HostCursorMaxPosX = window->DC.CursorMaxPos.x;
+ columns->HostInitialClipRect = window->ClipRect;
+ columns->HostBackupParentWorkRect = window->ParentWorkRect;
+ window->ParentWorkRect = window->WorkRect;
+
+ // Set state for first column
+ // We aim so that the right-most column will have the same clipping width as other after being clipped by parent ClipRect
+ const float column_padding = g.Style.ItemSpacing.x;
+ const float half_clip_extend_x = ImFloor(ImMax(window->WindowPadding.x * 0.5f, window->WindowBorderSize));
+ const float max_1 = window->WorkRect.Max.x + column_padding - ImMax(column_padding - window->WindowPadding.x, 0.0f);
+ const float max_2 = window->WorkRect.Max.x + half_clip_extend_x;
+ columns->OffMinX = window->DC.Indent.x - column_padding + ImMax(column_padding - window->WindowPadding.x, 0.0f);
+ columns->OffMaxX = ImMax(ImMin(max_1, max_2) - window->Pos.x, columns->OffMinX + 1.0f);
+ columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y;
+
+ // Clear data if columns count changed
+ if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1)
+ columns->Columns.resize(0);
+
+ // Initialize default widths
+ columns->IsFirstFrame = (columns->Columns.Size == 0);
+ if (columns->Columns.Size == 0)
+ {
+ columns->Columns.reserve(columns_count + 1);
+ for (int n = 0; n < columns_count + 1; n++)
+ {
+ ImGuiOldColumnData column;
+ column.OffsetNorm = n / (float)columns_count;
+ columns->Columns.push_back(column);
+ }
+ }
+
+ for (int n = 0; n < columns_count; n++)
+ {
+ // Compute clipping rectangle
+ ImGuiOldColumnData* column = &columns->Columns[n];
+ float clip_x1 = IM_ROUND(window->Pos.x + GetColumnOffset(n));
+ float clip_x2 = IM_ROUND(window->Pos.x + GetColumnOffset(n + 1) - 1.0f);
+ column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX);
+ column->ClipRect.ClipWithFull(window->ClipRect);
+ }
+
+ if (columns->Count > 1)
+ {
+ columns->Splitter.Split(window->DrawList, 1 + columns->Count);
+ columns->Splitter.SetCurrentChannel(window->DrawList, 1);
+ PushColumnClipRect(0);
+ }
+
+ // We don't generally store Indent.x inside ColumnsOffset because it may be manipulated by the user.
+ float offset_0 = GetColumnOffset(columns->Current);
+ float offset_1 = GetColumnOffset(columns->Current + 1);
+ float width = offset_1 - offset_0;
+ PushItemWidth(width * 0.65f);
+ window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f);
+ window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
+ window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding;
+}
+
+void ImGui::NextColumn()
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ if (window->SkipItems || window->DC.CurrentColumns == NULL)
+ return;
+
+ ImGuiContext& g = *GImGui;
+ ImGuiOldColumns* columns = window->DC.CurrentColumns;
+
+ if (columns->Count == 1)
+ {
+ window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
+ IM_ASSERT(columns->Current == 0);
+ return;
+ }
+
+ // Next column
+ if (++columns->Current == columns->Count)
+ columns->Current = 0;
+
+ PopItemWidth();
+
+ // Optimization: avoid PopClipRect() + SetCurrentChannel() + PushClipRect()
+ // (which would needlessly attempt to update commands in the wrong channel, then pop or overwrite them),
+ ImGuiOldColumnData* column = &columns->Columns[columns->Current];
+ SetWindowClipRectBeforeSetChannel(window, column->ClipRect);
+ columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1);
+
+ const float column_padding = g.Style.ItemSpacing.x;
+ columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);
+ if (columns->Current > 0)
+ {
+ // Columns 1+ ignore IndentX (by canceling it out)
+ // FIXME-COLUMNS: Unnecessary, could be locked?
+ window->DC.ColumnsOffset.x = GetColumnOffset(columns->Current) - window->DC.Indent.x + column_padding;
+ }
+ else
+ {
+ // New row/line: column 0 honor IndentX.
+ window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f);
+ columns->LineMinY = columns->LineMaxY;
+ }
+ window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
+ window->DC.CursorPos.y = columns->LineMinY;
+ window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
+ window->DC.CurrLineTextBaseOffset = 0.0f;
+
+ // FIXME-COLUMNS: Share code with BeginColumns() - move code on columns setup.
+ float offset_0 = GetColumnOffset(columns->Current);
+ float offset_1 = GetColumnOffset(columns->Current + 1);
+ float width = offset_1 - offset_0;
+ PushItemWidth(width * 0.65f);
+ window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding;
+}
+
+void ImGui::EndColumns()
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = GetCurrentWindow();
+ ImGuiOldColumns* columns = window->DC.CurrentColumns;
+ IM_ASSERT(columns != NULL);
+
+ PopItemWidth();
+ if (columns->Count > 1)
+ {
+ PopClipRect();
+ columns->Splitter.Merge(window->DrawList);
+ }
+
+ const ImGuiOldColumnFlags flags = columns->Flags;
+ columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);
+ window->DC.CursorPos.y = columns->LineMaxY;
+ if (!(flags & ImGuiOldColumnFlags_GrowParentContentsSize))
+ window->DC.CursorMaxPos.x = columns->HostCursorMaxPosX; // Restore cursor max pos, as columns don't grow parent
+
+ // Draw columns borders and handle resize
+ // The IsBeingResized flag ensure we preserve pre-resize columns width so back-and-forth are not lossy
+ bool is_being_resized = false;
+ if (!(flags & ImGuiOldColumnFlags_NoBorder) && !window->SkipItems)
+ {
+ // We clip Y boundaries CPU side because very long triangles are mishandled by some GPU drivers.
+ const float y1 = ImMax(columns->HostCursorPosY, window->ClipRect.Min.y);
+ const float y2 = ImMin(window->DC.CursorPos.y, window->ClipRect.Max.y);
+ int dragging_column = -1;
+ for (int n = 1; n < columns->Count; n++)
+ {
+ ImGuiOldColumnData* column = &columns->Columns[n];
+ float x = window->Pos.x + GetColumnOffset(n);
+ const ImGuiID column_id = columns->ID + ImGuiID(n);
+ const float column_hit_hw = COLUMNS_HIT_RECT_HALF_WIDTH;
+ const ImRect column_hit_rect(ImVec2(x - column_hit_hw, y1), ImVec2(x + column_hit_hw, y2));
+ KeepAliveID(column_id);
+ if (IsClippedEx(column_hit_rect, column_id, false))
+ continue;
+
+ bool hovered = false, held = false;
+ if (!(flags & ImGuiOldColumnFlags_NoResize))
+ {
+ ButtonBehavior(column_hit_rect, column_id, &hovered, &held);
+ if (hovered || held)
+ g.MouseCursor = ImGuiMouseCursor_ResizeEW;
+ if (held && !(column->Flags & ImGuiOldColumnFlags_NoResize))
+ dragging_column = n;
+ }
+
+ // Draw column
+ const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator);
+ const float xi = IM_FLOOR(x);
+ window->DrawList->AddLine(ImVec2(xi, y1 + 1.0f), ImVec2(xi, y2), col);
+ }
+
+ // Apply dragging after drawing the column lines, so our rendered lines are in sync with how items were displayed during the frame.
+ if (dragging_column != -1)
+ {
+ if (!columns->IsBeingResized)
+ for (int n = 0; n < columns->Count + 1; n++)
+ columns->Columns[n].OffsetNormBeforeResize = columns->Columns[n].OffsetNorm;
+ columns->IsBeingResized = is_being_resized = true;
+ float x = GetDraggedColumnOffset(columns, dragging_column);
+ SetColumnOffset(dragging_column, x);
+ }
+ }
+ columns->IsBeingResized = is_being_resized;
+
+ window->WorkRect = window->ParentWorkRect;
+ window->ParentWorkRect = columns->HostBackupParentWorkRect;
+ window->DC.CurrentColumns = NULL;
+ window->DC.ColumnsOffset.x = 0.0f;
+ window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
+}
+
+void ImGui::Columns(int columns_count, const char* id, bool border)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ IM_ASSERT(columns_count >= 1);
+
+ ImGuiOldColumnFlags flags = (border ? 0 : ImGuiOldColumnFlags_NoBorder);
+ //flags |= ImGuiOldColumnFlags_NoPreserveWidths; // NB: Legacy behavior
+ ImGuiOldColumns* columns = window->DC.CurrentColumns;
+ if (columns != NULL && columns->Count == columns_count && columns->Flags == flags)
+ return;
+
+ if (columns != NULL)
+ EndColumns();
+
+ if (columns_count != 1)
+ BeginColumns(id, columns_count, flags);
+}
+
+//-------------------------------------------------------------------------
+
+#endif // #ifndef IMGUI_DISABLE
diff --git a/dep/imgui/src/imgui_widgets.cpp b/dep/imgui/src/imgui_widgets.cpp
index 2fb029245..b765701fd 100644
--- a/dep/imgui/src/imgui_widgets.cpp
+++ b/dep/imgui/src/imgui_widgets.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.74 WIP
+// dear imgui, v1.81 WIP
// (widgets code)
/*
@@ -33,11 +33,14 @@ Index of this file:
#endif
#include "imgui.h"
+#ifndef IMGUI_DISABLE
+
#ifndef IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_MATH_OPERATORS
#endif
#include "imgui_internal.h"
+// System includes
#include // toupper
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
#include // intptr_t
@@ -45,34 +48,48 @@ Index of this file:
#include // intptr_t
#endif
+//-------------------------------------------------------------------------
+// Warnings
+//-------------------------------------------------------------------------
+
// Visual Studio warnings
#ifdef _MSC_VER
-#pragma warning (disable: 4127) // condition expression is constant
-#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
+#pragma warning (disable: 4127) // condition expression is constant
+#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
+#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later
+#pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types
+#endif
#endif
// Clang/GCC warnings with -Weverything
#if defined(__clang__)
-#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse.
-#pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
-#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning : format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
-#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness //
-#if __has_warning("-Wzero-as-null-pointer-constant")
-#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning : zero as null pointer constant // some standard header variations use #define NULL 0
-#endif
-#if __has_warning("-Wdouble-promotion")
-#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
+#if __has_warning("-Wunknown-warning-option")
+#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
#endif
+#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
+#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
+#pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
+#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning: format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
+#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
+#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
+#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
+#pragma clang diagnostic ignored "-Wenum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_')
+#pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion"// warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated
+#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
#elif defined(__GNUC__)
-#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
-#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
-#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
+#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
+#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
+#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
#endif
//-------------------------------------------------------------------------
// Data
//-------------------------------------------------------------------------
+// Widgets
+static const float DRAGDROP_HOLD_TO_OPEN_TIMER = 0.70f; // Time for drag-hold to activate items accepting the ImGuiButtonFlags_PressedOnDragDropHold button behavior.
+static const float DRAG_MOUSE_THRESHOLD_FACTOR = 0.50f; // Multiplier for the default value of io.MouseDragThreshold to make DragFloat/DragInt react faster to mouse drags.
+
// Those MIN/MAX values are not define because we need to point to them
static const signed char IM_S8_MIN = -128;
static const signed char IM_S8_MAX = 127;
@@ -152,7 +169,7 @@ void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags)
// - We use memchr(), pay attention that well optimized versions of those str/mem functions are much faster than a casually written loop.
const char* line = text;
const float line_height = GetTextLineHeight();
- ImVec2 text_size(0,0);
+ ImVec2 text_size(0, 0);
// Lines to skip (can't skip when logging text)
ImVec2 pos = text_pos;
@@ -266,7 +283,10 @@ void ImGui::TextColored(const ImVec4& col, const char* fmt, ...)
void ImGui::TextColoredV(const ImVec4& col, const char* fmt, va_list args)
{
PushStyleColor(ImGuiCol_Text, col);
- TextV(fmt, args);
+ if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
+ TextEx(va_arg(args, const char*), NULL, ImGuiTextFlags_NoWidthForLargeClippedText); // Skip formatting
+ else
+ TextV(fmt, args);
PopStyleColor();
}
@@ -280,8 +300,12 @@ void ImGui::TextDisabled(const char* fmt, ...)
void ImGui::TextDisabledV(const char* fmt, va_list args)
{
- PushStyleColor(ImGuiCol_Text, GImGui->Style.Colors[ImGuiCol_TextDisabled]);
- TextV(fmt, args);
+ ImGuiContext& g = *GImGui;
+ PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
+ if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
+ TextEx(va_arg(args, const char*), NULL, ImGuiTextFlags_NoWidthForLargeClippedText); // Skip formatting
+ else
+ TextV(fmt, args);
PopStyleColor();
}
@@ -295,11 +319,14 @@ void ImGui::TextWrapped(const char* fmt, ...)
void ImGui::TextWrappedV(const char* fmt, va_list args)
{
- ImGuiWindow* window = GetCurrentWindow();
- bool need_backup = (window->DC.TextWrapPos < 0.0f); // Keep existing wrap position if one is already set
+ ImGuiContext& g = *GImGui;
+ bool need_backup = (g.CurrentWindow->DC.TextWrapPos < 0.0f); // Keep existing wrap position if one is already set
if (need_backup)
PushTextWrapPos(0.0f);
- TextV(fmt, args);
+ if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
+ TextEx(va_arg(args, const char*), NULL, ImGuiTextFlags_NoWidthForLargeClippedText); // Skip formatting
+ else
+ TextV(fmt, args);
if (need_backup)
PopTextWrapPos();
}
@@ -324,8 +351,8 @@ void ImGui::LabelTextV(const char* label, const char* fmt, va_list args)
const float w = CalcItemWidth();
const ImVec2 label_size = CalcTextSize(label, NULL, true);
- const ImRect value_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2));
- const ImRect total_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w + (label_size.x > 0.0f ? style.ItemInnerSpacing.x : 0.0f), style.FramePadding.y*2) + label_size);
+ const ImRect value_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2));
+ const ImRect total_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w + (label_size.x > 0.0f ? style.ItemInnerSpacing.x : 0.0f), style.FramePadding.y * 2) + label_size);
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, 0))
return;
@@ -333,7 +360,7 @@ void ImGui::LabelTextV(const char* label, const char* fmt, va_list args)
// Render
const char* value_text_begin = &g.TempBuffer[0];
const char* value_text_end = value_text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
- RenderTextClipped(value_bb.Min, value_bb.Max, value_text_begin, value_text_end, NULL, ImVec2(0.0f,0.5f));
+ RenderTextClipped(value_bb.Min, value_bb.Max, value_text_begin, value_text_end, NULL, ImVec2(0.0f, 0.5f));
if (label_size.x > 0.0f)
RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label);
}
@@ -369,7 +396,7 @@ void ImGui::BulletTextV(const char* fmt, va_list args)
// Render
ImU32 text_col = GetColorU32(ImGuiCol_Text);
- RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, g.FontSize*0.5f), text_col);
+ RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize * 0.5f, g.FontSize * 0.5f), text_col);
RenderText(bb.Min + ImVec2(g.FontSize + style.FramePadding.x * 2, 0.0f), text_begin, text_end, false);
}
@@ -383,11 +410,14 @@ void ImGui::BulletTextV(const char* fmt, va_list args)
// - ArrowButton()
// - CloseButton() [Internal]
// - CollapseButton() [Internal]
-// - ScrollbarEx() [Internal]
+// - GetWindowScrollbarID() [Internal]
+// - GetWindowScrollbarRect() [Internal]
// - Scrollbar() [Internal]
+// - ScrollbarEx() [Internal]
// - Image()
// - ImageButton()
// - Checkbox()
+// - CheckboxFlagsT() [Internal]
// - CheckboxFlags()
// - RadioButton()
// - ProgressBar()
@@ -461,18 +491,22 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
return false;
}
- // Default behavior requires click+release on same spot
- if ((flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick)) == 0)
- flags |= ImGuiButtonFlags_PressedOnClickRelease;
+ // Default only reacts to left mouse button
+ if ((flags & ImGuiButtonFlags_MouseButtonMask_) == 0)
+ flags |= ImGuiButtonFlags_MouseButtonDefault_;
+
+ // Default behavior requires click + release inside bounding box
+ if ((flags & ImGuiButtonFlags_PressedOnMask_) == 0)
+ flags |= ImGuiButtonFlags_PressedOnDefault_;
ImGuiWindow* backup_hovered_window = g.HoveredWindow;
- const bool flatten_hovered_children = (flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredRootWindow == window->RootWindow;
+ const bool flatten_hovered_children = (flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredRootWindow == window;
if (flatten_hovered_children)
g.HoveredWindow = window;
#ifdef IMGUI_ENABLE_TEST_ENGINE
if (id != 0 && window->DC.LastItemId != id)
- ImGuiTestEngineHook_ItemAdd(&g, bb, id);
+ IMGUI_TEST_ENGINE_ITEM_ADD(bb, id);
#endif
bool pressed = false;
@@ -488,9 +522,10 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
{
hovered = true;
SetHoveredID(id);
- if (CalcTypematicRepeatAmount(g.HoveredIdTimer + 0.0001f - g.IO.DeltaTime, g.HoveredIdTimer + 0.0001f, 0.70f, 0.00f))
+ if (CalcTypematicRepeatAmount(g.HoveredIdTimer + 0.0001f - g.IO.DeltaTime, g.HoveredIdTimer + 0.0001f, DRAGDROP_HOLD_TO_OPEN_TIMER, 0.00f))
{
pressed = true;
+ g.DragDropHoldJustPressedId = id;
FocusWindow(window);
}
}
@@ -502,38 +537,56 @@ 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
+ // Mouse handling
if (hovered)
{
if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt))
{
- if ((flags & ImGuiButtonFlags_PressedOnClickRelease) && g.IO.MouseClicked[0])
+ // Poll buttons
+ int mouse_button_clicked = -1;
+ int mouse_button_released = -1;
+ if ((flags & ImGuiButtonFlags_MouseButtonLeft) && g.IO.MouseClicked[0]) { mouse_button_clicked = 0; }
+ else if ((flags & ImGuiButtonFlags_MouseButtonRight) && g.IO.MouseClicked[1]) { mouse_button_clicked = 1; }
+ else if ((flags & ImGuiButtonFlags_MouseButtonMiddle) && g.IO.MouseClicked[2]) { mouse_button_clicked = 2; }
+ if ((flags & ImGuiButtonFlags_MouseButtonLeft) && g.IO.MouseReleased[0]) { mouse_button_released = 0; }
+ else if ((flags & ImGuiButtonFlags_MouseButtonRight) && g.IO.MouseReleased[1]) { mouse_button_released = 1; }
+ else if ((flags & ImGuiButtonFlags_MouseButtonMiddle) && g.IO.MouseReleased[2]) { mouse_button_released = 2; }
+
+ if (mouse_button_clicked != -1 && g.ActiveId != id)
{
- SetActiveID(id, window);
- if (!(flags & ImGuiButtonFlags_NoNavFocus))
- SetFocusID(id, window);
- FocusWindow(window);
+ if (flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere))
+ {
+ SetActiveID(id, window);
+ g.ActiveIdMouseButton = mouse_button_clicked;
+ if (!(flags & ImGuiButtonFlags_NoNavFocus))
+ SetFocusID(id, window);
+ FocusWindow(window);
+ }
+ if ((flags & ImGuiButtonFlags_PressedOnClick) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDoubleClicked[mouse_button_clicked]))
+ {
+ pressed = true;
+ if (flags & ImGuiButtonFlags_NoHoldingActiveId)
+ ClearActiveID();
+ else
+ SetActiveID(id, window); // Hold on ID
+ g.ActiveIdMouseButton = mouse_button_clicked;
+ FocusWindow(window);
+ }
}
- if (((flags & ImGuiButtonFlags_PressedOnClick) && g.IO.MouseClicked[0]) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDoubleClicked[0]))
+ if ((flags & ImGuiButtonFlags_PressedOnRelease) && mouse_button_released != -1)
{
- pressed = true;
- if (flags & ImGuiButtonFlags_NoHoldingActiveID)
- ClearActiveID();
- else
- SetActiveID(id, window); // Hold on ID
- FocusWindow(window);
- }
- if ((flags & ImGuiButtonFlags_PressedOnRelease) && g.IO.MouseReleased[0])
- {
- if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps
+ // Repeat mode trumps on release behavior
+ const bool has_repeated_at_least_once = (flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[mouse_button_released] >= g.IO.KeyRepeatDelay;
+ if (!has_repeated_at_least_once)
pressed = true;
ClearActiveID();
}
// 'Repeat' mode acts when held regardless of _PressedOn flags (see table above).
// Relies on repeat logic of IsMouseClicked() but we may as well do it ourselves if we end up exposing finer RepeatDelay/RepeatRate settings.
- if ((flags & ImGuiButtonFlags_Repeat) && g.ActiveId == id && g.IO.MouseDownDuration[0] > 0.0f && IsMouseClicked(0, true))
- pressed = true;
+ if (g.ActiveId == id && (flags & ImGuiButtonFlags_Repeat))
+ if (g.IO.MouseDownDuration[g.ActiveIdMouseButton] > 0.0f && IsMouseClicked(g.ActiveIdMouseButton, true))
+ pressed = true;
}
if (pressed)
@@ -543,13 +596,12 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
// 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))
- if (!(flags & ImGuiButtonFlags_NoHoveredOnNav))
+ if (!(flags & ImGuiButtonFlags_NoHoveredOnFocus))
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);
+ bool nav_activated_by_inputs = IsNavInputTest(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)
@@ -562,25 +614,30 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
}
}
+ // Process while held
bool held = false;
if (g.ActiveId == id)
{
- if (pressed)
- g.ActiveIdHasBeenPressedBefore = true;
if (g.ActiveIdSource == ImGuiInputSource_Mouse)
{
if (g.ActiveIdIsJustActivated)
g.ActiveIdClickOffset = g.IO.MousePos - bb.Min;
- if (g.IO.MouseDown[0])
+
+ const int mouse_button = g.ActiveIdMouseButton;
+ IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
+ if (g.IO.MouseDown[mouse_button])
{
held = true;
}
else
{
- if (hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease) && !g.DragDropActive)
+ bool release_in = hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease) != 0;
+ bool release_anywhere = (flags & ImGuiButtonFlags_PressedOnClickReleaseAnywhere) != 0;
+ if ((release_in || release_anywhere) && !g.DragDropActive)
{
- bool is_double_click_release = (flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDownWasDoubleClick[0];
- bool is_repeating_already = (flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay; // Repeat mode trumps
+ // Report as pressed when releasing the mouse (this is the most common path)
+ bool is_double_click_release = (flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDownWasDoubleClick[mouse_button];
+ bool is_repeating_already = (flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[mouse_button] >= g.IO.KeyRepeatDelay; // Repeat mode trumps
if (!is_double_click_release && !is_repeating_already)
pressed = true;
}
@@ -591,9 +648,12 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
}
else if (g.ActiveIdSource == ImGuiInputSource_Nav)
{
+ // When activated using Nav, we hold on the ActiveID until activation button is released
if (g.NavActivateDownId != id)
ClearActiveID();
}
+ if (pressed)
+ g.ActiveIdHasBeenPressedBefore = true;
}
if (out_hovered) *out_hovered = hovered;
@@ -644,7 +704,7 @@ bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags
bool ImGui::Button(const char* label, const ImVec2& size_arg)
{
- return ButtonEx(label, size_arg, 0);
+ return ButtonEx(label, size_arg, ImGuiButtonFlags_None);
}
// Small buttons fits within text without additional vertical spacing.
@@ -660,7 +720,7 @@ bool ImGui::SmallButton(const char* label)
// 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::InvisibleButton(const char* str_id, const ImVec2& size_arg, ImGuiButtonFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
@@ -677,7 +737,7 @@ bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg)
return false;
bool hovered, held;
- bool pressed = ButtonBehavior(bb, id, &hovered, &held);
+ bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
return pressed;
}
@@ -715,7 +775,7 @@ bool ImGui::ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size, ImGuiBu
bool ImGui::ArrowButton(const char* str_id, ImGuiDir dir)
{
float sz = GetFrameHeight();
- return ArrowButtonEx(str_id, dir, ImVec2(sz, sz), 0);
+ return ArrowButtonEx(str_id, dir, ImVec2(sz, sz), ImGuiButtonFlags_None);
}
// Button to close a window
@@ -743,14 +803,13 @@ bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos)//, float size)
float cross_extent = g.FontSize * 0.5f * 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);
+ 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;
}
-// The Collapse button also functions as a Dock Menu button.
-bool ImGui::CollapseButton(ImGuiID id, const ImVec2& pos, ImGuiDockNode* dock_node)
+bool ImGui::CollapseButton(ImGuiID id, const ImVec2& pos)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
@@ -761,31 +820,68 @@ bool ImGui::CollapseButton(ImGuiID id, const ImVec2& pos, ImGuiDockNode* dock_no
bool pressed = ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_None);
// Render
- //bool is_dock_menu = (window->DockNodeAsHost && !window->Collapsed);
- ImVec2 off = dock_node ? ImVec2(IM_FLOOR(-g.Style.ItemInnerSpacing.x * 0.5f) + 0.5f, 0.0f) : ImVec2(0.0f, 0.0f);
ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
ImU32 text_col = GetColorU32(ImGuiCol_Text);
ImVec2 center = bb.GetCenter();
if (hovered || held)
- window->DrawList->AddCircleFilled(center + off + ImVec2(0,-0.5f), g.FontSize * 0.5f + 1.0f, bg_col, 12);
-
- if (dock_node)
- RenderArrowDockMenu(window->DrawList, bb.Min + g.Style.FramePadding, g.FontSize, text_col);
- else
- RenderArrow(window->DrawList, bb.Min + g.Style.FramePadding, text_col, window->Collapsed ? ImGuiDir_Right : ImGuiDir_Down, 1.0f);
+ window->DrawList->AddCircleFilled(center/*+ ImVec2(0.0f, -0.5f)*/, g.FontSize * 0.5f + 1.0f, bg_col, 12);
+ RenderArrow(window->DrawList, bb.Min + g.Style.FramePadding, text_col, window->Collapsed ? ImGuiDir_Right : ImGuiDir_Down, 1.0f);
// Switch to moving the window after mouse is moved beyond the initial drag threshold
if (IsItemActive() && IsMouseDragging(0))
- StartMouseDragFromTitleBar(window, dock_node, true);
+ StartMouseMovingWindow(window);
return pressed;
}
-ImGuiID ImGui::GetScrollbarID(ImGuiWindow* window, ImGuiAxis axis)
+ImGuiID ImGui::GetWindowScrollbarID(ImGuiWindow* window, ImGuiAxis axis)
{
return window->GetIDNoKeepAlive(axis == ImGuiAxis_X ? "#SCROLLX" : "#SCROLLY");
}
+// Return scrollbar rectangle, must only be called for corresponding axis if window->ScrollbarX/Y is set.
+ImRect ImGui::GetWindowScrollbarRect(ImGuiWindow* window, ImGuiAxis axis)
+{
+ const ImRect outer_rect = window->Rect();
+ const ImRect inner_rect = window->InnerRect;
+ const float border_size = window->WindowBorderSize;
+ const float scrollbar_size = window->ScrollbarSizes[axis ^ 1]; // (ScrollbarSizes.x = width of Y scrollbar; ScrollbarSizes.y = height of X scrollbar)
+ IM_ASSERT(scrollbar_size > 0.0f);
+ if (axis == ImGuiAxis_X)
+ return ImRect(inner_rect.Min.x, ImMax(outer_rect.Min.y, outer_rect.Max.y - border_size - scrollbar_size), inner_rect.Max.x, outer_rect.Max.y);
+ else
+ return ImRect(ImMax(outer_rect.Min.x, outer_rect.Max.x - border_size - scrollbar_size), inner_rect.Min.y, outer_rect.Max.x, inner_rect.Max.y);
+}
+
+void ImGui::Scrollbar(ImGuiAxis axis)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+
+ const ImGuiID id = GetWindowScrollbarID(window, axis);
+ KeepAliveID(id);
+
+ // Calculate scrollbar bounding box
+ ImRect bb = GetWindowScrollbarRect(window, axis);
+ ImDrawCornerFlags rounding_corners = 0;
+ if (axis == ImGuiAxis_X)
+ {
+ rounding_corners |= ImDrawCornerFlags_BotLeft;
+ if (!window->ScrollbarY)
+ rounding_corners |= ImDrawCornerFlags_BotRight;
+ }
+ else
+ {
+ if ((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar))
+ rounding_corners |= ImDrawCornerFlags_TopRight;
+ if (!window->ScrollbarX)
+ rounding_corners |= ImDrawCornerFlags_BotRight;
+ }
+ float size_avail = window->InnerRect.Max[axis] - window->InnerRect.Min[axis];
+ float size_contents = window->ContentSize[axis] + window->WindowPadding[axis] * 2.0f;
+ ScrollbarEx(bb, id, axis, &window->Scroll[axis], size_avail, size_contents, rounding_corners);
+}
+
// Vertical/Horizontal scrollbar
// The entire piece of code below is rather confusing because:
// - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab)
@@ -804,7 +900,7 @@ bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, floa
if (bb_frame_width <= 0.0f || bb_frame_height <= 0.0f)
return false;
- // When we are too small, start hiding and disabling the grab (this reduce visual noise on very small window and facilitate using the resize grab)
+ // When we are too small, start hiding and disabling the grab (this reduce visual noise on very small window and facilitate using the window resize grab)
float alpha = 1.0f;
if ((axis == ImGuiAxis_Y) && bb_frame_height < g.FontSize + g.Style.FramePadding.y * 2.0f)
alpha = ImSaturate((bb_frame_height - g.FontSize) / (g.Style.FramePadding.y * 2.0f));
@@ -813,13 +909,12 @@ bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, floa
const ImGuiStyle& style = g.Style;
const bool allow_interaction = (alpha >= 1.0f);
- const bool horizontal = (axis == ImGuiAxis_X);
ImRect bb = bb_frame;
bb.Expand(ImVec2(-ImClamp(IM_FLOOR((bb_frame_width - 2.0f) * 0.5f), 0.0f, 3.0f), -ImClamp(IM_FLOOR((bb_frame_height - 2.0f) * 0.5f), 0.0f, 3.0f)));
// V denote the main, longer axis of the scrollbar (= height for a vertical scrollbar)
- const float scrollbar_size_v = horizontal ? bb.GetWidth() : bb.GetHeight();
+ const float scrollbar_size_v = (axis == ImGuiAxis_X) ? bb.GetWidth() : bb.GetHeight();
// Calculate the height of our grabbable box. It generally represent the amount visible (vs the total scrollable amount)
// But we maintain a minimum size in pixel to allow for the user to still aim inside.
@@ -835,11 +930,11 @@ bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, floa
float scroll_max = ImMax(1.0f, size_contents_v - size_avail_v);
float scroll_ratio = ImSaturate(*p_scroll_v / scroll_max);
- float grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v;
+ float grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; // Grab position in normalized space
if (held && allow_interaction && grab_h_norm < 1.0f)
{
- float scrollbar_pos_v = horizontal ? bb.Min.x : bb.Min.y;
- float mouse_pos_v = horizontal ? g.IO.MousePos.x : g.IO.MousePos.y;
+ float scrollbar_pos_v = bb.Min[axis];
+ float mouse_pos_v = g.IO.MousePos[axis];
// Click position in scrollbar normalized space (0.0f->1.0f)
const float clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v);
@@ -856,10 +951,10 @@ bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, floa
g.ScrollbarClickDeltaToGrabCenter = clicked_v_norm - grab_v_norm - grab_h_norm * 0.5f;
}
- // Apply scroll
+ // Apply scroll (p_scroll_v will generally point on one member of window->Scroll)
// It is ok to modify Scroll here because we are being called in Begin() after the calculation of ContentSize and before setting up our starting position
const float scroll_v_norm = ImSaturate((clicked_v_norm - g.ScrollbarClickDeltaToGrabCenter - grab_h_norm * 0.5f) / (1.0f - grab_h_norm));
- *p_scroll_v = IM_FLOOR(0.5f + scroll_v_norm * scroll_max);//(win_size_contents_v - win_size_v));
+ *p_scroll_v = IM_ROUND(scroll_v_norm * scroll_max);//(win_size_contents_v - win_size_v));
// Update values for rendering
scroll_ratio = ImSaturate(*p_scroll_v / scroll_max);
@@ -871,10 +966,11 @@ bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, floa
}
// Render
- window->DrawList->AddRectFilled(bb_frame.Min, bb_frame.Max, GetColorU32(ImGuiCol_ScrollbarBg), window->WindowRounding, rounding_corners);
+ const ImU32 bg_col = GetColorU32(ImGuiCol_ScrollbarBg);
const ImU32 grab_col = GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab, alpha);
+ window->DrawList->AddRectFilled(bb_frame.Min, bb_frame.Max, bg_col, window->WindowRounding, rounding_corners);
ImRect grab_rect;
- if (horizontal)
+ if (axis == ImGuiAxis_X)
grab_rect = ImRect(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y, ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, bb.Max.y);
else
grab_rect = ImRect(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm), bb.Max.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels);
@@ -883,38 +979,6 @@ bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, floa
return held;
}
-void ImGui::Scrollbar(ImGuiAxis axis)
-{
- ImGuiContext& g = *GImGui;
- ImGuiWindow* window = g.CurrentWindow;
-
- const ImGuiID id = GetScrollbarID(window, axis);
- KeepAliveID(id);
-
- // Calculate scrollbar bounding box
- const ImRect outer_rect = window->Rect();
- const ImRect inner_rect = window->InnerRect;
- const float border_size = window->WindowBorderSize;
- const float scrollbar_size = window->ScrollbarSizes[axis ^ 1];
- IM_ASSERT(scrollbar_size > 0.0f);
- const float other_scrollbar_size = window->ScrollbarSizes[axis];
- ImDrawCornerFlags rounding_corners = (other_scrollbar_size <= 0.0f) ? ImDrawCornerFlags_BotRight : 0;
- ImRect bb;
- if (axis == ImGuiAxis_X)
- {
- bb.Min = ImVec2(inner_rect.Min.x, ImMax(outer_rect.Min.y, outer_rect.Max.y - border_size - scrollbar_size));
- bb.Max = ImVec2(inner_rect.Max.x, outer_rect.Max.y);
- rounding_corners |= ImDrawCornerFlags_BotLeft;
- }
- else
- {
- bb.Min = ImVec2(ImMax(outer_rect.Min.x, outer_rect.Max.x - border_size - scrollbar_size), inner_rect.Min.y);
- bb.Max = ImVec2(outer_rect.Max.x, window->InnerRect.Max.y);
- rounding_corners |= ((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? ImDrawCornerFlags_TopRight : 0;
- }
- ScrollbarEx(bb, id, axis, &window->Scroll[axis], inner_rect.Max[axis] - inner_rect.Min[axis], window->ContentSize[axis] + window->WindowPadding[axis] * 2.0f, rounding_corners);
-}
-
void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col)
{
ImGuiWindow* window = GetCurrentWindow();
@@ -939,28 +1003,16 @@ void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2&
}
}
-// frame_padding < 0: uses FramePadding from style (default)
-// frame_padding = 0: no framing
-// frame_padding > 0: set framing size
-// The color used are the button colors.
-bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col)
+// ImageButton() is flawed as 'id' is always derived from 'texture_id' (see #2464 #1390)
+// We provide this internal helper to write your own variant while we figure out how to redesign the public ImageButton() API.
+bool ImGui::ImageButtonEx(ImGuiID id, ImTextureID texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec2& padding, const ImVec4& bg_col, const ImVec4& tint_col)
{
+ ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
- ImGuiContext& g = *GImGui;
- const ImGuiStyle& style = g.Style;
-
- // Default to using texture ID as ID. User can still push string/integer prefixes.
- // We could hash the size/uv to create a unique ID but that would prevent the user from animating UV.
- PushID((void*)(intptr_t)user_texture_id);
- const ImGuiID id = window->GetID("#image");
- PopID();
-
- const ImVec2 padding = (frame_padding >= 0) ? ImVec2((float)frame_padding, (float)frame_padding) : style.FramePadding;
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size + padding * 2);
- const ImRect image_bb(window->DC.CursorPos + padding, window->DC.CursorPos + padding + size);
ItemSize(bb);
if (!ItemAdd(bb, id))
return false;
@@ -971,14 +1023,33 @@ bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const I
// Render
const ImU32 col = GetColorU32((held && hovered) ? 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));
+ RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, g.Style.FrameRounding));
if (bg_col.w > 0.0f)
- window->DrawList->AddRectFilled(image_bb.Min, image_bb.Max, GetColorU32(bg_col));
- window->DrawList->AddImage(user_texture_id, image_bb.Min, image_bb.Max, uv0, uv1, GetColorU32(tint_col));
+ window->DrawList->AddRectFilled(bb.Min + padding, bb.Max - padding, GetColorU32(bg_col));
+ window->DrawList->AddImage(texture_id, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col));
return pressed;
}
+// frame_padding < 0: uses FramePadding from style (default)
+// frame_padding = 0: no framing
+// frame_padding > 0: set framing size
+bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ if (window->SkipItems)
+ return false;
+
+ // Default to using texture ID as ID. User can still push string/integer prefixes.
+ PushID((void*)(intptr_t)user_texture_id);
+ const ImGuiID id = window->GetID("#image");
+ PopID();
+
+ const ImVec2 padding = (frame_padding >= 0) ? ImVec2((float)frame_padding, (float)frame_padding) : g.Style.FramePadding;
+ return ImageButtonEx(id, user_texture_id, size, uv0, uv1, padding, bg_col, tint_col);
+}
+
bool ImGui::Checkbox(const char* label, bool* v)
{
ImGuiWindow* window = GetCurrentWindow();
@@ -995,7 +1066,10 @@ bool ImGui::Checkbox(const char* label, bool* v)
const ImRect total_bb(pos, pos + ImVec2(square_sz + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), label_size.y + style.FramePadding.y * 2.0f));
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, id))
+ {
+ IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0));
return false;
+ }
bool hovered, held;
bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);
@@ -1009,20 +1083,22 @@ bool ImGui::Checkbox(const char* label, bool* 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);
ImU32 check_col = GetColorU32(ImGuiCol_CheckMark);
- if (window->DC.ItemFlags & ImGuiItemFlags_MixedValue)
+ bool mixed_value = (window->DC.ItemFlags & ImGuiItemFlags_MixedValue) != 0;
+ if (mixed_value)
{
// Undocumented tristate/mixed/indeterminate checkbox (#2644)
+ // This may seem awkwardly designed because the aim is to make ImGuiItemFlags_MixedValue supported by all widgets (not just checkbox)
ImVec2 pad(ImMax(1.0f, IM_FLOOR(square_sz / 3.6f)), ImMax(1.0f, IM_FLOOR(square_sz / 3.6f)));
window->DrawList->AddRectFilled(check_bb.Min + pad, check_bb.Max - pad, check_col, style.FrameRounding);
}
else if (*v)
{
const float pad = ImMax(1.0f, IM_FLOOR(square_sz / 6.0f));
- RenderCheckMark(check_bb.Min + ImVec2(pad, pad), check_col, square_sz - pad*2.0f);
+ RenderCheckMark(window->DrawList, check_bb.Min + ImVec2(pad, pad), check_col, square_sz - pad * 2.0f);
}
if (g.LogEnabled)
- LogRenderedText(&total_bb.Min, *v ? "[x]" : "[ ]");
+ LogRenderedText(&total_bb.Min, mixed_value ? "[~]" : *v ? "[x]" : "[ ]");
if (label_size.x > 0.0f)
RenderText(ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y), label);
@@ -1030,21 +1106,55 @@ bool ImGui::Checkbox(const char* label, bool* v)
return pressed;
}
-bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value)
+template
+bool ImGui::CheckboxFlagsT(const char* label, T* flags, T flags_value)
{
- bool v = ((*flags & flags_value) == flags_value);
- bool pressed = Checkbox(label, &v);
+ bool all_on = (*flags & flags_value) == flags_value;
+ bool any_on = (*flags & flags_value) != 0;
+ bool pressed;
+ if (!all_on && any_on)
+ {
+ ImGuiWindow* window = GetCurrentWindow();
+ ImGuiItemFlags backup_item_flags = window->DC.ItemFlags;
+ window->DC.ItemFlags |= ImGuiItemFlags_MixedValue;
+ pressed = Checkbox(label, &all_on);
+ window->DC.ItemFlags = backup_item_flags;
+ }
+ else
+ {
+ pressed = Checkbox(label, &all_on);
+
+ }
if (pressed)
{
- if (v)
+ if (all_on)
*flags |= flags_value;
else
*flags &= ~flags_value;
}
-
return pressed;
}
+bool ImGui::CheckboxFlags(const char* label, int* flags, int flags_value)
+{
+ return CheckboxFlagsT(label, flags, flags_value);
+}
+
+bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value)
+{
+ return CheckboxFlagsT(label, flags, flags_value);
+}
+
+bool ImGui::CheckboxFlags(const char* label, ImS64* flags, ImS64 flags_value)
+{
+ return CheckboxFlagsT(label, flags, flags_value);
+}
+
+bool ImGui::CheckboxFlags(const char* label, ImU64* flags, ImU64 flags_value)
+{
+ return CheckboxFlagsT(label, flags, flags_value);
+}
+
bool ImGui::RadioButton(const char* label, bool active)
{
ImGuiWindow* window = GetCurrentWindow();
@@ -1065,8 +1175,8 @@ bool ImGui::RadioButton(const char* label, bool active)
return false;
ImVec2 center = check_bb.GetCenter();
- center.x = IM_FLOOR(center.x + 0.5f);
- center.y = IM_FLOOR(center.y + 0.5f);
+ center.x = IM_ROUND(center.x);
+ center.y = IM_ROUND(center.y);
const float radius = (square_sz - 1.0f) * 0.5f;
bool hovered, held;
@@ -1084,7 +1194,7 @@ bool ImGui::RadioButton(const char* label, bool active)
if (style.FrameBorderSize > 0.0f)
{
- window->DrawList->AddCircle(center + ImVec2(1,1), radius, GetColorU32(ImGuiCol_BorderShadow), 16, style.FrameBorderSize);
+ window->DrawList->AddCircle(center + ImVec2(1, 1), radius, GetColorU32(ImGuiCol_BorderShadow), 16, style.FrameBorderSize);
window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), 16, style.FrameBorderSize);
}
@@ -1093,6 +1203,7 @@ bool ImGui::RadioButton(const char* label, bool active)
if (label_size.x > 0.0f)
RenderText(ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y), label);
+ IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags);
return pressed;
}
@@ -1116,7 +1227,7 @@ void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* over
const ImGuiStyle& style = g.Style;
ImVec2 pos = window->DC.CursorPos;
- ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y*2.0f);
+ ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y * 2.0f);
ImRect bb(pos, pos + size);
ItemSize(size, style.FramePadding.y);
if (!ItemAdd(bb, 0))
@@ -1133,13 +1244,13 @@ void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* over
char overlay_buf[32];
if (!overlay)
{
- ImFormatString(overlay_buf, IM_ARRAYSIZE(overlay_buf), "%.0f%%", fraction*100+0.01f);
+ ImFormatString(overlay_buf, IM_ARRAYSIZE(overlay_buf), "%.0f%%", fraction * 100 + 0.01f);
overlay = overlay_buf;
}
ImVec2 overlay_size = CalcTextSize(overlay, NULL);
if (overlay_size.x > 0.0f)
- RenderTextClipped(ImVec2(ImClamp(fill_br.x + style.ItemSpacing.x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y), bb.Max, overlay, NULL, &overlay_size, ImVec2(0.0f,0.5f), &bb);
+ RenderTextClipped(ImVec2(ImClamp(fill_br.x + style.ItemSpacing.x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y), bb.Max, overlay, NULL, &overlay_size, ImVec2(0.0f, 0.5f), &bb);
}
void ImGui::Bullet()
@@ -1150,18 +1261,18 @@ void ImGui::Bullet()
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
- const float line_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + g.Style.FramePadding.y*2), g.FontSize);
+ const float line_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + g.Style.FramePadding.y * 2), g.FontSize);
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize, line_height));
ItemSize(bb);
if (!ItemAdd(bb, 0))
{
- SameLine(0, style.FramePadding.x*2);
+ SameLine(0, style.FramePadding.x * 2);
return;
}
// Render and stay on same line
ImU32 text_col = GetColorU32(ImGuiCol_Text);
- RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f), text_col);
+ RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize * 0.5f, line_height * 0.5f), text_col);
SameLine(0, style.FramePadding.x * 2.0f);
}
@@ -1183,7 +1294,7 @@ void ImGui::Spacing()
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
- ItemSize(ImVec2(0,0));
+ ItemSize(ImVec2(0, 0));
}
void ImGui::Dummy(const ImVec2& size)
@@ -1207,7 +1318,7 @@ void ImGui::NewLine()
const ImGuiLayoutType backup_layout_type = window->DC.LayoutType;
window->DC.LayoutType = ImGuiLayoutType_Vertical;
if (window->DC.CurrLineSize.y > 0.0f) // In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height.
- ItemSize(ImVec2(0,0));
+ ItemSize(ImVec2(0, 0));
else
ItemSize(ImVec2(0.0f, g.FontSize));
window->DC.LayoutType = backup_layout_type;
@@ -1256,31 +1367,26 @@ void ImGui::SeparatorEx(ImGuiSeparatorFlags flags)
// Horizontal Separator
float x1 = window->Pos.x;
float x2 = window->Pos.x + window->Size.x;
- if (!window->DC.GroupStack.empty())
+
+ // FIXME-WORKRECT: old hack (#205) until we decide of consistent behavior with WorkRect/Indent and Separator
+ if (g.GroupStack.Size > 0 && g.GroupStack.back().WindowID == window->ID)
x1 += window->DC.Indent.x;
- ImGuiColumns* columns = (flags & ImGuiSeparatorFlags_SpanAllColumns) ? window->DC.CurrentColumns : NULL;
+ ImGuiOldColumns* columns = (flags & ImGuiSeparatorFlags_SpanAllColumns) ? window->DC.CurrentColumns : NULL;
if (columns)
PushColumnsBackground();
// We don't provide our width to the layout so that it doesn't get feed back into AutoFit
const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y + thickness_draw));
ItemSize(ImVec2(0.0f, thickness_layout));
- if (!ItemAdd(bb, 0))
+ const bool item_visible = ItemAdd(bb, 0);
+ if (item_visible)
{
- if (columns)
- {
- PopColumnsBackground();
- columns->LineMinY = window->DC.CursorPos.y;
- }
- return;
+ // Draw
+ window->DrawList->AddLine(bb.Min, ImVec2(bb.Max.x, bb.Min.y), GetColorU32(ImGuiCol_Separator));
+ if (g.LogEnabled)
+ LogRenderedText(&bb.Min, "--------------------------------");
}
-
- // Draw
- window->DrawList->AddLine(bb.Min, ImVec2(bb.Max.x, bb.Min.y), GetColorU32(ImGuiCol_Separator));
- if (g.LogEnabled)
- LogRenderedText(&bb.Min, "--------------------------------");
-
if (columns)
{
PopColumnsBackground();
@@ -1355,7 +1461,7 @@ bool ImGui::SplitterBehavior(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float
// Render
const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : (hovered && g.HoveredIdTimer >= hover_visibility_delay) ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator);
- window->DrawList->AddRectFilled(bb_render.Min, bb_render.Max, col, g.Style.FrameRounding);
+ window->DrawList->AddRectFilled(bb_render.Min, bb_render.Max, col, 0.0f);
return held;
}
@@ -1370,11 +1476,13 @@ static int IMGUI_CDECL ShrinkWidthItemComparer(const void* lhs, const void* rhs)
}
// Shrink excess width from a set of item, by removing width from the larger items first.
+// Set items Width to -1.0f to disable shrinking this item.
void ImGui::ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess)
{
if (count == 1)
{
- items[0].Width = ImMax(items[0].Width - width_excess, 1.0f);
+ if (items[0].Width >= 0.0f)
+ items[0].Width = ImMax(items[0].Width - width_excess, 1.0f);
return;
}
ImQsort(items, (size_t)count, sizeof(ImGuiShrinkWidthItem), ShrinkWidthItemComparer);
@@ -1383,7 +1491,9 @@ void ImGui::ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_exc
{
while (count_same_width < count && items[0].Width <= items[count_same_width].Width)
count_same_width++;
- float max_width_to_remove_per_item = (count_same_width < count) ? (items[0].Width - items[count_same_width].Width) : (items[0].Width - 1.0f);
+ float max_width_to_remove_per_item = (count_same_width < count && items[count_same_width].Width >= 0.0f) ? (items[0].Width - items[count_same_width].Width) : (items[0].Width - 1.0f);
+ if (max_width_to_remove_per_item <= 0.0f)
+ break;
float width_to_remove_per_item = ImMin(width_excess / count_same_width, max_width_to_remove_per_item);
for (int item_n = 0; item_n < count_same_width; item_n++)
items[item_n].Width -= width_to_remove_per_item;
@@ -1441,7 +1551,7 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const float expected_w = CalcItemWidth();
const float w = (flags & ImGuiComboFlags_NoPreview) ? arrow_size : expected_w;
- const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));
+ 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, &frame_bb))
@@ -1449,7 +1559,7 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF
bool hovered, held;
bool pressed = ButtonBehavior(frame_bb, id, &hovered, &held);
- bool popup_open = IsPopupOpen(id);
+ bool popup_open = IsPopupOpen(id, ImGuiPopupFlags_None);
const ImU32 frame_col = GetColorU32(hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
const float value_x2 = ImMax(frame_bb.Min.x, frame_bb.Max.x - arrow_size);
@@ -1466,7 +1576,7 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF
}
RenderFrameBorder(frame_bb.Min, frame_bb.Max, style.FrameRounding);
if (preview_value != NULL && !(flags & ImGuiComboFlags_NoPreview))
- RenderTextClipped(frame_bb.Min + style.FramePadding, ImVec2(value_x2, frame_bb.Max.y), preview_value, NULL, NULL, ImVec2(0.0f,0.0f));
+ RenderTextClipped(frame_bb.Min + style.FramePadding, ImVec2(value_x2, frame_bb.Max.y), 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);
@@ -1474,7 +1584,7 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF
{
if (window->DC.NavLayerCurrent == 0)
window->NavLastIds[0] = id;
- OpenPopupEx(id);
+ OpenPopupEx(id, ImGuiPopupFlags_None);
popup_open = true;
}
@@ -1501,13 +1611,17 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF
char name[16];
ImFormatString(name, IM_ARRAYSIZE(name), "##Combo_%02d", g.BeginPopupStack.Size); // Recycle windows based on depth
- // Peak into expected window size so we can position it
+ // Position the window given a custom constraint (peak into expected window size so we can position it)
+ // This might be easier to express with an hypothetical SetNextWindowPosConstraints() function.
if (ImGuiWindow* popup_window = FindWindowByName(name))
if (popup_window->WasActive)
{
- ImVec2 size_expected = CalcWindowExpectedSize(popup_window);
+ // Always override 'AutoPosLastDirection' to not leave a chance for a past value to affect us.
+ ImVec2 size_expected = CalcWindowNextAutoFitSize(popup_window);
if (flags & ImGuiComboFlags_PopupAlignLeft)
- popup_window->AutoPosLastDirection = ImGuiDir_Left;
+ popup_window->AutoPosLastDirection = ImGuiDir_Left; // "Below, Toward Left"
+ else
+ popup_window->AutoPosLastDirection = ImGuiDir_Down; // "Below, Toward Right (default)"
ImRect r_outer = GetWindowAllowedExtentRect(popup_window);
ImVec2 pos = FindBestWindowPosForPopupEx(frame_bb.GetBL(), size_expected, &popup_window->AutoPosLastDirection, r_outer, frame_bb, ImGuiPopupPositionPolicy_ComboBox);
SetNextWindowPos(pos);
@@ -1576,7 +1690,7 @@ bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(voi
// The old Combo() API exposed "popup_max_height_in_items". The new more general BeginCombo() API doesn't have/need it, but we emulate it here.
if (popup_max_height_in_items != -1 && !(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint))
- SetNextWindowSizeConstraints(ImVec2(0,0), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items)));
+ SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items)));
if (!BeginCombo(label, preview_value, ImGuiComboFlags_None))
return false;
@@ -1602,6 +1716,9 @@ bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(voi
}
EndCombo();
+ if (value_changed)
+ MarkItemEdited(g.CurrentWindow->DC.LastItemId);
+
return value_changed;
}
@@ -1634,27 +1751,28 @@ bool ImGui::Combo(const char* label, int* current_item, const char* items_separa
// - DataTypeFormatString()
// - DataTypeApplyOp()
// - DataTypeApplyOpFromText()
+// - DataTypeClamp()
// - GetMinimumStepAtDecimalPrecision
// - RoundScalarWithFormat<>()
//-------------------------------------------------------------------------
static const ImGuiDataTypeInfo GDataTypeInfo[] =
{
- { sizeof(char), "%d", "%d" }, // ImGuiDataType_S8
- { sizeof(unsigned char), "%u", "%u" },
- { sizeof(short), "%d", "%d" }, // ImGuiDataType_S16
- { sizeof(unsigned short), "%u", "%u" },
- { sizeof(int), "%d", "%d" }, // ImGuiDataType_S32
- { sizeof(unsigned int), "%u", "%u" },
+ { sizeof(char), "S8", "%d", "%d" }, // ImGuiDataType_S8
+ { sizeof(unsigned char), "U8", "%u", "%u" },
+ { sizeof(short), "S16", "%d", "%d" }, // ImGuiDataType_S16
+ { sizeof(unsigned short), "U16", "%u", "%u" },
+ { sizeof(int), "S32", "%d", "%d" }, // ImGuiDataType_S32
+ { sizeof(unsigned int), "U32", "%u", "%u" },
#ifdef _MSC_VER
- { sizeof(ImS64), "%I64d","%I64d" }, // ImGuiDataType_S64
- { sizeof(ImU64), "%I64u","%I64u" },
+ { sizeof(ImS64), "S64", "%I64d","%I64d" }, // ImGuiDataType_S64
+ { sizeof(ImU64), "U64", "%I64u","%I64u" },
#else
- { sizeof(ImS64), "%lld", "%lld" }, // ImGuiDataType_S64
- { sizeof(ImU64), "%llu", "%llu" },
+ { sizeof(ImS64), "S64", "%lld", "%lld" }, // ImGuiDataType_S64
+ { sizeof(ImU64), "U64", "%llu", "%llu" },
#endif
- { sizeof(float), "%f", "%f" }, // ImGuiDataType_Float (float are promoted to double in va_arg)
- { sizeof(double), "%f", "%lf" }, // ImGuiDataType_Double
+ { sizeof(float), "float", "%f", "%f" }, // ImGuiDataType_Float (float are promoted to double in va_arg)
+ { sizeof(double), "double","%f", "%lf" }, // ImGuiDataType_Double
};
IM_STATIC_ASSERT(IM_ARRAYSIZE(GDataTypeInfo) == ImGuiDataType_COUNT);
@@ -1711,7 +1829,7 @@ int ImGui::DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type
return 0;
}
-void ImGui::DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* arg1, const void* arg2)
+void ImGui::DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, const void* arg1, const void* arg2)
{
IM_ASSERT(op == '+' || op == '-');
switch (data_type)
@@ -1785,11 +1903,9 @@ bool ImGui::DataTypeApplyOpFromText(const char* buf, const char* initial_value_b
return false;
// Copy the value in an opaque buffer so we can compare at the end of the function if it changed at all.
- IM_ASSERT(data_type < ImGuiDataType_COUNT);
- int data_backup[2];
- const ImGuiDataTypeInfo* type_info = ImGui::DataTypeGetInfo(data_type);
- IM_ASSERT(type_info->Size <= sizeof(data_backup));
- memcpy(data_backup, p_data, type_info->Size);
+ const ImGuiDataTypeInfo* type_info = DataTypeGetInfo(data_type);
+ ImGuiDataTypeTempStorage data_backup;
+ memcpy(&data_backup, p_data, type_info->Size);
if (format == NULL)
format = type_info->ScanFmt;
@@ -1861,7 +1977,64 @@ bool ImGui::DataTypeApplyOpFromText(const char* buf, const char* initial_value_b
IM_ASSERT(0);
}
- return memcmp(data_backup, p_data, type_info->Size) != 0;
+ return memcmp(&data_backup, p_data, type_info->Size) != 0;
+}
+
+template
+static int DataTypeCompareT(const T* lhs, const T* rhs)
+{
+ if (*lhs < *rhs) return -1;
+ if (*lhs > *rhs) return +1;
+ return 0;
+}
+
+int ImGui::DataTypeCompare(ImGuiDataType data_type, const void* arg_1, const void* arg_2)
+{
+ switch (data_type)
+ {
+ case ImGuiDataType_S8: return DataTypeCompareT((const ImS8* )arg_1, (const ImS8* )arg_2);
+ case ImGuiDataType_U8: return DataTypeCompareT((const ImU8* )arg_1, (const ImU8* )arg_2);
+ case ImGuiDataType_S16: return DataTypeCompareT((const ImS16* )arg_1, (const ImS16* )arg_2);
+ case ImGuiDataType_U16: return DataTypeCompareT((const ImU16* )arg_1, (const ImU16* )arg_2);
+ case ImGuiDataType_S32: return DataTypeCompareT((const ImS32* )arg_1, (const ImS32* )arg_2);
+ case ImGuiDataType_U32: return DataTypeCompareT((const ImU32* )arg_1, (const ImU32* )arg_2);
+ case ImGuiDataType_S64: return DataTypeCompareT((const ImS64* )arg_1, (const ImS64* )arg_2);
+ case ImGuiDataType_U64: return DataTypeCompareT((const ImU64* )arg_1, (const ImU64* )arg_2);
+ case ImGuiDataType_Float: return DataTypeCompareT((const float* )arg_1, (const float* )arg_2);
+ case ImGuiDataType_Double: return DataTypeCompareT((const double*)arg_1, (const double*)arg_2);
+ case ImGuiDataType_COUNT: break;
+ }
+ IM_ASSERT(0);
+ return 0;
+}
+
+template
+static bool DataTypeClampT(T* v, const T* v_min, const T* v_max)
+{
+ // Clamp, both sides are optional, return true if modified
+ if (v_min && *v < *v_min) { *v = *v_min; return true; }
+ if (v_max && *v > *v_max) { *v = *v_max; return true; }
+ return false;
+}
+
+bool ImGui::DataTypeClamp(ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max)
+{
+ switch (data_type)
+ {
+ case ImGuiDataType_S8: return DataTypeClampT((ImS8* )p_data, (const ImS8* )p_min, (const ImS8* )p_max);
+ case ImGuiDataType_U8: return DataTypeClampT((ImU8* )p_data, (const ImU8* )p_min, (const ImU8* )p_max);
+ case ImGuiDataType_S16: return DataTypeClampT((ImS16* )p_data, (const ImS16* )p_min, (const ImS16* )p_max);
+ case ImGuiDataType_U16: return DataTypeClampT((ImU16* )p_data, (const ImU16* )p_min, (const ImU16* )p_max);
+ case ImGuiDataType_S32: return DataTypeClampT((ImS32* )p_data, (const ImS32* )p_min, (const ImS32* )p_max);
+ case ImGuiDataType_U32: return DataTypeClampT((ImU32* )p_data, (const ImU32* )p_min, (const ImU32* )p_max);
+ case ImGuiDataType_S64: return DataTypeClampT((ImS64* )p_data, (const ImS64* )p_min, (const ImS64* )p_max);
+ case ImGuiDataType_U64: return DataTypeClampT((ImU64* )p_data, (const ImU64* )p_min, (const ImU64* )p_max);
+ case ImGuiDataType_Float: return DataTypeClampT((float* )p_data, (const float* )p_min, (const float* )p_max);
+ case ImGuiDataType_Double: return DataTypeClampT((double*)p_data, (const double*)p_min, (const double*)p_max);
+ case ImGuiDataType_COUNT: break;
+ }
+ IM_ASSERT(0);
+ return false;
}
static float GetMinimumStepAtDecimalPrecision(int decimal_precision)
@@ -1924,16 +2097,13 @@ TYPE ImGui::RoundScalarWithFormatT(const char* format, ImGuiDataType data_type,
// This is called by DragBehavior() when the widget is active (held by mouse or being manipulated with Nav controls)
template
-bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiDragFlags flags)
+bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_min, const TYPE v_max, const char* format, ImGuiSliderFlags flags)
{
ImGuiContext& g = *GImGui;
- const ImGuiAxis axis = (flags & ImGuiDragFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X;
+ const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X;
const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double);
const bool is_clamped = (v_min < v_max);
- const bool is_power = (power != 1.0f && is_decimal && is_clamped && (v_max - v_min < FLT_MAX));
- const bool is_locked = (v_min > v_max);
- if (is_locked)
- return false;
+ const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) && is_decimal;
// Default tweak speed
if (v_speed == 0.0f && is_clamped && (v_max - v_min < FLT_MAX))
@@ -1941,7 +2111,7 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const
// Inputs accumulates into g.DragCurrentAccum, which is flushed into the current value as soon as it makes a difference with our precision settings
float adjust_delta = 0.0f;
- if (g.ActiveIdSource == ImGuiInputSource_Mouse && IsMousePosValid() && g.IO.MouseDragMaxDistanceSqr[0] > 1.0f*1.0f)
+ if (g.ActiveIdSource == ImGuiInputSource_Mouse && IsMousePosValid() && IsMouseDragPastThreshold(0, g.IO.MouseDragThreshold * DRAG_MOUSE_THRESHOLD_FACTOR))
{
adjust_delta = g.IO.MouseDelta[axis];
if (g.IO.KeyAlt)
@@ -1961,12 +2131,15 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const
if (axis == ImGuiAxis_Y)
adjust_delta = -adjust_delta;
+ // For logarithmic use our range is effectively 0..1 so scale the delta into that range
+ if (is_logarithmic && (v_max - v_min < FLT_MAX) && ((v_max - v_min) > 0.000001f)) // Epsilon to avoid /0
+ adjust_delta /= (float)(v_max - v_min);
+
// Clear current value on activation
// Avoid altering values and clamping when we are _already_ past the limits and heading in the same direction, so e.g. if range is 0..255, current value is 300 and we are pushing to the right side, keep the 300.
bool is_just_activated = g.ActiveIdIsJustActivated;
bool is_already_past_limits_and_pushing_outward = is_clamped && ((*v >= v_max && adjust_delta > 0.0f) || (*v <= v_min && adjust_delta < 0.0f));
- bool is_drag_direction_change_with_power = is_power && ((adjust_delta < 0 && g.DragCurrentAccum > 0) || (adjust_delta > 0 && g.DragCurrentAccum < 0));
- if (is_just_activated || is_already_past_limits_and_pushing_outward || is_drag_direction_change_with_power)
+ if (is_just_activated || is_already_past_limits_and_pushing_outward)
{
g.DragCurrentAccum = 0.0f;
g.DragCurrentAccumDirty = false;
@@ -1983,13 +2156,19 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const
TYPE v_cur = *v;
FLOATTYPE v_old_ref_for_accum_remainder = (FLOATTYPE)0.0f;
- if (is_power)
+ float logarithmic_zero_epsilon = 0.0f; // Only valid when is_logarithmic is true
+ const float zero_deadzone_halfsize = 0.0f; // Drag widgets have no deadzone (as it doesn't make sense)
+ if (is_logarithmic)
{
- // Offset + round to user desired precision, with a curve on the v_min..v_max range to get more precision on one side of the range
- FLOATTYPE v_old_norm_curved = ImPow((FLOATTYPE)(v_cur - v_min) / (FLOATTYPE)(v_max - v_min), (FLOATTYPE)1.0f / power);
- FLOATTYPE v_new_norm_curved = v_old_norm_curved + (g.DragCurrentAccum / (v_max - v_min));
- v_cur = v_min + (SIGNEDTYPE)ImPow(ImSaturate((float)v_new_norm_curved), power) * (v_max - v_min);
- v_old_ref_for_accum_remainder = v_old_norm_curved;
+ // When using logarithmic sliders, we need to clamp to avoid hitting zero, but our choice of clamp value greatly affects slider precision. We attempt to use the specified precision to estimate a good lower bound.
+ const int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 1;
+ logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision);
+
+ // Convert to parametric space, apply delta, convert back
+ float v_old_parametric = ScaleRatioFromValueT(data_type, v_cur, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
+ float v_new_parametric = v_old_parametric + g.DragCurrentAccum;
+ v_cur = ScaleValueFromRatioT(data_type, v_new_parametric, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
+ v_old_ref_for_accum_remainder = v_old_parametric;
}
else
{
@@ -1997,14 +2176,16 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const
}
// Round to user desired precision based on format string
- v_cur = RoundScalarWithFormatT(format, data_type, v_cur);
+ if (!(flags & ImGuiSliderFlags_NoRoundToFormat))
+ v_cur = RoundScalarWithFormatT(format, data_type, v_cur);
// Preserve remainder after rounding has been applied. This also allow slow tweaking of values.
g.DragCurrentAccumDirty = false;
- if (is_power)
+ if (is_logarithmic)
{
- FLOATTYPE v_cur_norm_curved = ImPow((FLOATTYPE)(v_cur - v_min) / (FLOATTYPE)(v_max - v_min), (FLOATTYPE)1.0f / power);
- g.DragCurrentAccum -= (float)(v_cur_norm_curved - v_old_ref_for_accum_remainder);
+ // Convert to parametric space, apply delta, convert back
+ float v_new_parametric = ScaleRatioFromValueT(data_type, v_cur, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
+ g.DragCurrentAccum -= (float)(v_new_parametric - v_old_ref_for_accum_remainder);
}
else
{
@@ -2031,8 +2212,11 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const
return true;
}
-bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragFlags flags)
+bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags)
{
+ // Read imgui.cpp "API BREAKING CHANGES" section for 1.78 if you hit this assert.
+ IM_ASSERT((flags == 1 || (flags & ImGuiSliderFlags_InvalidMask_) == 0) && "Invalid ImGuiSliderFlags flags! Has the 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead.");
+
ImGuiContext& g = *GImGui;
if (g.ActiveId == id)
{
@@ -2043,19 +2227,21 @@ bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v
}
if (g.ActiveId != id)
return false;
+ if ((g.CurrentWindow->DC.ItemFlags & ImGuiItemFlags_ReadOnly) || (flags & ImGuiSliderFlags_ReadOnly))
+ return false;
switch (data_type)
{
- case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)p_v; bool r = DragBehaviorT(ImGuiDataType_S32, &v32, v_speed, p_min ? *(const ImS8*) p_min : IM_S8_MIN, p_max ? *(const ImS8*)p_max : IM_S8_MAX, format, power, flags); if (r) *(ImS8*)p_v = (ImS8)v32; return r; }
- case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)p_v; bool r = DragBehaviorT(ImGuiDataType_U32, &v32, v_speed, p_min ? *(const ImU8*) p_min : IM_U8_MIN, p_max ? *(const ImU8*)p_max : IM_U8_MAX, format, power, flags); if (r) *(ImU8*)p_v = (ImU8)v32; return r; }
- case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)p_v; bool r = DragBehaviorT(ImGuiDataType_S32, &v32, v_speed, p_min ? *(const ImS16*)p_min : IM_S16_MIN, p_max ? *(const ImS16*)p_max : IM_S16_MAX, format, power, flags); if (r) *(ImS16*)p_v = (ImS16)v32; return r; }
- case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)p_v; bool r = DragBehaviorT(ImGuiDataType_U32, &v32, v_speed, p_min ? *(const ImU16*)p_min : IM_U16_MIN, p_max ? *(const ImU16*)p_max : IM_U16_MAX, format, power, flags); if (r) *(ImU16*)p_v = (ImU16)v32; return r; }
- case ImGuiDataType_S32: return DragBehaviorT(data_type, (ImS32*)p_v, v_speed, p_min ? *(const ImS32* )p_min : IM_S32_MIN, p_max ? *(const ImS32* )p_max : IM_S32_MAX, format, power, flags);
- case ImGuiDataType_U32: return DragBehaviorT(data_type, (ImU32*)p_v, v_speed, p_min ? *(const ImU32* )p_min : IM_U32_MIN, p_max ? *(const ImU32* )p_max : IM_U32_MAX, format, power, flags);
- case ImGuiDataType_S64: return DragBehaviorT(data_type, (ImS64*)p_v, v_speed, p_min ? *(const ImS64* )p_min : IM_S64_MIN, p_max ? *(const ImS64* )p_max : IM_S64_MAX, format, power, flags);
- case ImGuiDataType_U64: return DragBehaviorT(data_type, (ImU64*)p_v, v_speed, p_min ? *(const ImU64* )p_min : IM_U64_MIN, p_max ? *(const ImU64* )p_max : IM_U64_MAX, format, power, flags);
- case ImGuiDataType_Float: return DragBehaviorT(data_type, (float*)p_v, v_speed, p_min ? *(const float* )p_min : -FLT_MAX, p_max ? *(const float* )p_max : FLT_MAX, format, power, flags);
- case ImGuiDataType_Double: return DragBehaviorT(data_type, (double*)p_v, v_speed, p_min ? *(const double*)p_min : -DBL_MAX, p_max ? *(const double*)p_max : DBL_MAX, format, power, flags);
+ case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)p_v; bool r = DragBehaviorT(ImGuiDataType_S32, &v32, v_speed, p_min ? *(const ImS8*) p_min : IM_S8_MIN, p_max ? *(const ImS8*)p_max : IM_S8_MAX, format, flags); if (r) *(ImS8*)p_v = (ImS8)v32; return r; }
+ case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)p_v; bool r = DragBehaviorT(ImGuiDataType_U32, &v32, v_speed, p_min ? *(const ImU8*) p_min : IM_U8_MIN, p_max ? *(const ImU8*)p_max : IM_U8_MAX, format, flags); if (r) *(ImU8*)p_v = (ImU8)v32; return r; }
+ case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)p_v; bool r = DragBehaviorT(ImGuiDataType_S32, &v32, v_speed, p_min ? *(const ImS16*)p_min : IM_S16_MIN, p_max ? *(const ImS16*)p_max : IM_S16_MAX, format, flags); if (r) *(ImS16*)p_v = (ImS16)v32; return r; }
+ case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)p_v; bool r = DragBehaviorT(ImGuiDataType_U32, &v32, v_speed, p_min ? *(const ImU16*)p_min : IM_U16_MIN, p_max ? *(const ImU16*)p_max : IM_U16_MAX, format, flags); if (r) *(ImU16*)p_v = (ImU16)v32; return r; }
+ case ImGuiDataType_S32: return DragBehaviorT