git repos / blockattack-game

commit 4e9e2555

Poul Sander · 2025-10-05 10:15
4e9e25555f8c9808165beb2e50ae990dc75a20fe patch · browse files
parent 66d34b8a1bd5ba8f1cdd35b729d9abaa099c0744

Updated ImGui to 1.92.3-docker

Changed files

M source/code/Libs/imgui/LICENSE.txt before
M source/code/Libs/imgui/backends/imgui_impl_sdl2.cpp before
M source/code/Libs/imgui/backends/imgui_impl_sdl2.h before
M source/code/Libs/imgui/backends/imgui_impl_sdlrenderer2.cpp before
M source/code/Libs/imgui/backends/imgui_impl_sdlrenderer2.h before
M source/code/Libs/imgui/imconfig.h before
M source/code/Libs/imgui/imgui.cpp before
M source/code/Libs/imgui/imgui.h before
M source/code/Libs/imgui/imgui_draw.cpp before
M source/code/Libs/imgui/imgui_internal.h before
M source/code/Libs/imgui/imgui_tables.cpp before
M source/code/Libs/imgui/imgui_widgets.cpp before
M source/code/Libs/imgui/imstb_textedit.h before
M source/code/Libs/imgui/imstb_truetype.h before
diff --git a/source/code/Libs/imgui/LICENSE.txt b/source/code/Libs/imgui/LICENSE.txt index 3282f5b..00ae473 100644 --- a/source/code/Libs/imgui/LICENSE.txt +++ b/source/code/Libs/imgui/LICENSE.txt
@@ -1,6 +1,6 @@
The MIT License (MIT)
-Copyright (c) 2014-2024 Omar Cornut
+Copyright (c) 2014-2025 Omar Cornut
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
diff --git a/source/code/Libs/imgui/backends/imgui_impl_sdl2.cpp b/source/code/Libs/imgui/backends/imgui_impl_sdl2.cpp index 37e3f00..26a8ad7 100644 --- a/source/code/Libs/imgui/backends/imgui_impl_sdl2.cpp +++ b/source/code/Libs/imgui/backends/imgui_impl_sdl2.cpp
@@ -6,14 +6,14 @@
// Implemented features:
// [X] Platform: Clipboard support.
// [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen.
-// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set]
-// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
-// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
+// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values are obsolete since 1.87 and not supported since 1.91.5]
+// [X] Platform: Gamepad support.
+// [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
+// [X] Platform: Basic IME support. App needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!.
// [X] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
-// Issues:
+// Missing features or Issues:
// [ ] Platform: Multi-viewport: Minimized windows seems to break mouse wheel events (at least under Windows).
// [ ] Platform: Multi-viewport: ParentViewportID not honored, and so io.ConfigViewportsNoDefaultParent has no effect (minor).
-// [x] Platform: Basic IME support. App needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!.
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
@@ -25,7 +25,23 @@
// CHANGELOG
// (minor and older changes stripped away, please see git history for details)
-// 2024-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
+// 2025-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
+// 2025-09-15: Content Scales are always reported as 1.0 on Wayland. (#8921)
+// 2025-07-08: Made ImGui_ImplSDL2_GetContentScaleForWindow(), ImGui_ImplSDL2_GetContentScaleForDisplay() helpers return 1.0f on Emscripten and Android platforms, matching macOS logic. (#8742, #8733)
+// 2025-06-11: Added ImGui_ImplSDL2_GetContentScaleForWindow(SDL_Window* window) and ImGui_ImplSDL2_GetContentScaleForDisplay(int display_index) helper to facilitate making DPI-aware apps.
+// 2025-05-15: [Docking] Add Platform_GetWindowFramebufferScale() handler, to allow varying Retina display density on multiple monitors.
+// 2025-04-09: [Docking] Revert update monitors and work areas information every frame. Only do it on Windows. (#8415, #8558)
+// 2025-04-09: Don't attempt to call SDL_CaptureMouse() on drivers where we don't call SDL_GetGlobalMouseState(). (#8561)
+// 2025-03-21: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad regardless of ImGuiConfigFlags_NavEnableGamepad being set.
+// 2025-03-10: When dealing with OEM keys, use scancodes instead of translated keycodes to choose ImGuiKey values. (#7136, #7201, #7206, #7306, #7670, #7672, #8468)
+// 2025-02-26: Only start SDL_CaptureMouse() when mouse is being dragged, to mitigate issues with e.g.Linux debuggers not claiming capture back. (#6410, #3650)
+// 2025-02-25: [Docking] Revert to use SDL_GetDisplayBounds() for WorkPos/WorkRect if SDL_GetDisplayUsableBounds() failed.
+// 2025-02-24: Avoid calling SDL_GetGlobalMouseState() when mouse is in relative mode.
+// 2025-02-21: [Docking] Update monitors and work areas information every frame, as the later may change regardless of monitor changes. (#8415)
+// 2025-02-18: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support.
+// 2025-02-10: Using SDL_OpenURL() in platform_io.Platform_OpenInShellFn handler.
+// 2025-01-20: Made ImGui_ImplSDL2_SetGamepadMode(ImGui_ImplSDL2_GamepadMode_Manual) accept an empty array.
+// 2024-10-24: Emscripten: from SDL 2.30.9, SDL_EVENT_MOUSE_WHEEL event doesn't require dividing by 100.0f.
// 2024-09-09: use SDL_Vulkan_GetDrawableSize() when available. (#7967, #3190)
// 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO:
// - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn
@@ -99,6 +115,7 @@
// Clang warnings with -Weverything
#if defined(__clang__)
#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
#endif
@@ -106,12 +123,14 @@
// (the multi-viewports feature requires SDL features supported from SDL 2.0.4+. SDL 2.0.5+ is highly recommended)
#include <SDL.h>
#include <SDL_syswm.h>
+#include <stdio.h> // for snprintf()
#ifdef __APPLE__
#include <TargetConditionals.h>
#endif
#ifdef __EMSCRIPTEN__
#include <emscripten/em_js.h>
#endif
+#undef Status // X11 headers are leaking this.
#if SDL_VERSION_ATLEAST(2,0,4) && !defined(__EMSCRIPTEN__) && !defined(__ANDROID__) && !(defined(__APPLE__) && TARGET_OS_IOS) && !defined(__amigaos4__)
#define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 1
@@ -124,10 +143,11 @@
#define SDL_HAS_PER_MONITOR_DPI SDL_VERSION_ATLEAST(2,0,4)
#define SDL_HAS_VULKAN SDL_VERSION_ATLEAST(2,0,6)
#define SDL_HAS_DISPLAY_EVENT SDL_VERSION_ATLEAST(2,0,9)
+#define SDL_HAS_OPEN_URL SDL_VERSION_ATLEAST(2,0,14)
#define SDL_HAS_SHOW_WINDOW_ACTIVATION_HINT SDL_VERSION_ATLEAST(2,0,18)
#if SDL_HAS_VULKAN
-extern "C" { extern DECLSPEC void SDLCALL SDL_Vulkan_GetDrawableSize(SDL_Window* window, int* w, int* h); }
-#elif
+#include <SDL_vulkan.h>
+#else
static const Uint32 SDL_WINDOW_VULKAN = 0x10000000;
#endif
@@ -135,10 +155,11 @@ static const Uint32 SDL_WINDOW_VULKAN = 0x10000000;
struct ImGui_ImplSDL2_Data
{
SDL_Window* Window;
- Uint32 WindowID;
+ Uint32 WindowID; // Stored in ImGuiViewport::PlatformHandle. Use SDL_GetWindowFromID() to get SDL_Window* from Uint32 WindowID.
SDL_Renderer* Renderer;
Uint64 Time;
char* ClipboardTextData;
+ char BackendPlatformName[48];
bool UseVulkan;
bool WantUpdateMonitors;
@@ -149,6 +170,7 @@ struct ImGui_ImplSDL2_Data
SDL_Cursor* MouseLastCursor;
int MouseLastLeaveFrame;
bool MouseCanUseGlobalState;
+ bool MouseCanUseCapture;
bool MouseCanReportHoveredViewport; // This is hard to use/unreliable on SDL so we'll set ImGuiBackendFlags_HasMouseHoveredViewport dynamically based on state.
// Gamepad handling
@@ -203,9 +225,9 @@ static void ImGui_ImplSDL2_PlatformSetImeData(ImGuiContext*, ImGuiViewport* view
}
// Not static to allow third-party code to use that if they want to (but undocumented)
+ImGuiKey ImGui_ImplSDL2_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode);
ImGuiKey ImGui_ImplSDL2_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode)
{
- IM_UNUSED(scancode);
switch (keycode)
{
case SDLK_TAB: return ImGuiKey_Tab;
@@ -223,17 +245,17 @@ ImGuiKey ImGui_ImplSDL2_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode sca
case SDLK_SPACE: return ImGuiKey_Space;
case SDLK_RETURN: return ImGuiKey_Enter;
case SDLK_ESCAPE: return ImGuiKey_Escape;
- case SDLK_QUOTE: return ImGuiKey_Apostrophe;
+ //case SDLK_QUOTE: return ImGuiKey_Apostrophe;
case SDLK_COMMA: return ImGuiKey_Comma;
- case SDLK_MINUS: return ImGuiKey_Minus;
+ //case SDLK_MINUS: return ImGuiKey_Minus;
case SDLK_PERIOD: return ImGuiKey_Period;
- case SDLK_SLASH: return ImGuiKey_Slash;
+ //case SDLK_SLASH: return ImGuiKey_Slash;
case SDLK_SEMICOLON: return ImGuiKey_Semicolon;
- case SDLK_EQUALS: return ImGuiKey_Equal;
- case SDLK_LEFTBRACKET: return ImGuiKey_LeftBracket;
- case SDLK_BACKSLASH: return ImGuiKey_Backslash;
- case SDLK_RIGHTBRACKET: return ImGuiKey_RightBracket;
- case SDLK_BACKQUOTE: return ImGuiKey_GraveAccent;
+ //case SDLK_EQUALS: return ImGuiKey_Equal;
+ //case SDLK_LEFTBRACKET: return ImGuiKey_LeftBracket;
+ //case SDLK_BACKSLASH: return ImGuiKey_Backslash;
+ //case SDLK_RIGHTBRACKET: return ImGuiKey_RightBracket;
+ //case SDLK_BACKQUOTE: return ImGuiKey_GraveAccent;
case SDLK_CAPSLOCK: return ImGuiKey_CapsLock;
case SDLK_SCROLLLOCK: return ImGuiKey_ScrollLock;
case SDLK_NUMLOCKCLEAR: return ImGuiKey_NumLock;
@@ -329,6 +351,24 @@ ImGuiKey ImGui_ImplSDL2_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode sca
case SDLK_AC_FORWARD: return ImGuiKey_AppForward;
default: break;
}
+
+ // Fallback to scancode
+ switch (scancode)
+ {
+ case SDL_SCANCODE_GRAVE: return ImGuiKey_GraveAccent;
+ case SDL_SCANCODE_MINUS: return ImGuiKey_Minus;
+ case SDL_SCANCODE_EQUALS: return ImGuiKey_Equal;
+ case SDL_SCANCODE_LEFTBRACKET: return ImGuiKey_LeftBracket;
+ case SDL_SCANCODE_RIGHTBRACKET: return ImGuiKey_RightBracket;
+ case SDL_SCANCODE_NONUSBACKSLASH: return ImGuiKey_Oem102;
+ case SDL_SCANCODE_BACKSLASH: return ImGuiKey_Backslash;
+ case SDL_SCANCODE_SEMICOLON: return ImGuiKey_Semicolon;
+ case SDL_SCANCODE_APOSTROPHE: return ImGuiKey_Apostrophe;
+ case SDL_SCANCODE_COMMA: return ImGuiKey_Comma;
+ case SDL_SCANCODE_PERIOD: return ImGuiKey_Period;
+ case SDL_SCANCODE_SLASH: return ImGuiKey_Slash;
+ default: break;
+ }
return ImGuiKey_None;
}
@@ -360,7 +400,7 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)
{
case SDL_MOUSEMOTION:
{
- if (ImGui_ImplSDL2_GetViewportForWindowID(event->motion.windowID) == NULL)
+ if (ImGui_ImplSDL2_GetViewportForWindowID(event->motion.windowID) == nullptr)
return false;
ImVec2 mouse_pos((float)event->motion.x, (float)event->motion.y);
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
@@ -376,7 +416,7 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)
}
case SDL_MOUSEWHEEL:
{
- if (ImGui_ImplSDL2_GetViewportForWindowID(event->wheel.windowID) == NULL)
+ if (ImGui_ImplSDL2_GetViewportForWindowID(event->wheel.windowID) == nullptr)
return false;
//IMGUI_DEBUG_LOG("wheel %.2f %.2f, precise %.2f %.2f\n", (float)event->wheel.x, (float)event->wheel.y, event->wheel.preciseX, event->wheel.preciseY);
#if SDL_VERSION_ATLEAST(2,0,18) // If this fails to compile on Emscripten: update to latest Emscripten!
@@ -386,7 +426,7 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)
float wheel_x = -(float)event->wheel.x;
float wheel_y = (float)event->wheel.y;
#endif
-#ifdef __EMSCRIPTEN__
+#if defined(__EMSCRIPTEN__) && !SDL_VERSION_ATLEAST(2,31,0)
wheel_x /= 100.0f;
#endif
io.AddMouseSourceEvent(event->wheel.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);
@@ -396,7 +436,7 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
{
- if (ImGui_ImplSDL2_GetViewportForWindowID(event->button.windowID) == NULL)
+ if (ImGui_ImplSDL2_GetViewportForWindowID(event->button.windowID) == nullptr)
return false;
int mouse_button = -1;
if (event->button.button == SDL_BUTTON_LEFT) { mouse_button = 0; }
@@ -413,7 +453,7 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)
}
case SDL_TEXTINPUT:
{
- if (ImGui_ImplSDL2_GetViewportForWindowID(event->text.windowID) == NULL)
+ if (ImGui_ImplSDL2_GetViewportForWindowID(event->text.windowID) == nullptr)
return false;
io.AddInputCharactersUTF8(event->text.text);
return true;
@@ -421,12 +461,15 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)
case SDL_KEYDOWN:
case SDL_KEYUP:
{
- if (ImGui_ImplSDL2_GetViewportForWindowID(event->key.windowID) == NULL)
+ ImGuiViewport* viewport = ImGui_ImplSDL2_GetViewportForWindowID(event->key.windowID);
+ if (viewport == nullptr)
return false;
+ //IMGUI_DEBUG_LOG("SDL_KEY%s : key=0x%08X ('%s'), scancode=%d ('%s'), mod=%X, windowID=%d, viewport=%08X\n",
+ // (event->type == SDL_KEYDOWN) ? "DOWN" : "UP ", event->key.keysym.sym, SDL_GetKeyName(event->key.keysym.sym), event->key.keysym.scancode, SDL_GetScancodeName(event->key.keysym.scancode), event->key.keysym.mod, event->key.windowID, viewport ? viewport->ID : 0);
ImGui_ImplSDL2_UpdateKeyModifiers((SDL_Keymod)event->key.keysym.mod);
ImGuiKey key = ImGui_ImplSDL2_KeyEventToImGuiKey(event->key.keysym.sym, event->key.keysym.scancode);
io.AddKeyEvent(key, (event->type == SDL_KEYDOWN));
- io.SetKeyEventNativeData(key, event->key.keysym.sym, event->key.keysym.scancode, event->key.keysym.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions.
+ io.SetKeyEventNativeData(key, (int)event->key.keysym.sym, (int)event->key.keysym.scancode, (int)event->key.keysym.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions.
return true;
}
#if SDL_HAS_DISPLAY_EVENT
@@ -457,15 +500,17 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)
}
if (window_event == SDL_WINDOWEVENT_LEAVE)
bd->MouseLastLeaveFrame = ImGui::GetFrameCount() + 1;
+ //if (window_event == SDL_WINDOWEVENT_FOCUS_GAINED) { IMGUI_DEBUG_LOG("SDL_WINDOWEVENT_FOCUS_GAINED: windowId %d, viewport: %08X\n", event->window.windowID, viewport ? viewport->ID : 0); }
+ //if (window_event == SDL_WINDOWEVENT_FOCUS_LOST) { IMGUI_DEBUG_LOG("SDL_WINDOWEVENT_FOCUS_LOST: windowId %d, viewport: %08X\n", event->window.windowID, viewport ? viewport->ID : 0); }
if (window_event == SDL_WINDOWEVENT_FOCUS_GAINED)
io.AddFocusEvent(true);
- else if (window_event == SDL_WINDOWEVENT_FOCUS_LOST)
+ if (window_event == SDL_WINDOWEVENT_FOCUS_LOST)
io.AddFocusEvent(false);
- else if (window_event == SDL_WINDOWEVENT_CLOSE)
+ if (window_event == SDL_WINDOWEVENT_CLOSE)
viewport->PlatformRequestClose = true;
- else if (window_event == SDL_WINDOWEVENT_MOVED)
+ if (window_event == SDL_WINDOWEVENT_MOVED)
viewport->PlatformRequestMove = true;
- else if (window_event == SDL_WINDOWEVENT_RESIZED)
+ if (window_event == SDL_WINDOWEVENT_RESIZED)
viewport->PlatformRequestResize = true;
return true;
}
@@ -475,6 +520,8 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)
bd->WantUpdateGamepadsList = true;
return true;
}
+ default:
+ break;
}
return false;
}
@@ -488,26 +535,23 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void
ImGuiIO& io = ImGui::GetIO();
IMGUI_CHECKVERSION();
IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!");
+ //SDL_SetHint(SDL_HINT_EVENT_LOGGING, "2");
- // Check and store if we are on a SDL backend that supports global mouse position
- // ("wayland" and "rpi" don't support it, but we chose to use a white-list instead of a black-list)
- bool mouse_can_use_global_state = false;
-#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE
- const char* sdl_backend = SDL_GetCurrentVideoDriver();
- const char* global_mouse_whitelist[] = { "windows", "cocoa", "x11", "DIVE", "VMAN" };
- for (int n = 0; n < IM_ARRAYSIZE(global_mouse_whitelist); n++)
- if (strncmp(sdl_backend, global_mouse_whitelist[n], strlen(global_mouse_whitelist[n])) == 0)
- mouse_can_use_global_state = true;
-#endif
+ // Obtain compiled and runtime versions
+ SDL_version ver_compiled;
+ SDL_version ver_runtime;
+ SDL_VERSION(&ver_compiled);
+ SDL_GetVersion(&ver_runtime);
// Setup backend capabilities flags
ImGui_ImplSDL2_Data* bd = IM_NEW(ImGui_ImplSDL2_Data)();
+ snprintf(bd->BackendPlatformName, sizeof(bd->BackendPlatformName), "imgui_impl_sdl2 (%u.%u.%u, %u.%u.%u)",
+ ver_compiled.major, ver_compiled.minor, ver_compiled.patch, ver_runtime.major, ver_runtime.minor, ver_runtime.patch);
io.BackendPlatformUserData = (void*)bd;
- io.BackendPlatformName = "imgui_impl_sdl2";
+ io.BackendPlatformName = bd->BackendPlatformName;
io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
- if (mouse_can_use_global_state)
- io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports; // We can create multi-viewports on the Platform side (optional)
+ // (ImGuiBackendFlags_PlatformHasViewports may be set just below)
bd->Window = window;
bd->WindowID = SDL_GetWindowID(window);
@@ -515,13 +559,26 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void
// SDL on Linux/OSX doesn't report events for unfocused windows (see https://github.com/ocornut/imgui/issues/4960)
// We will use 'MouseCanReportHoveredViewport' to set 'ImGuiBackendFlags_HasMouseHoveredViewport' dynamically each frame.
- bd->MouseCanUseGlobalState = mouse_can_use_global_state;
#ifndef __APPLE__
bd->MouseCanReportHoveredViewport = bd->MouseCanUseGlobalState;
#else
bd->MouseCanReportHoveredViewport = false;
#endif
+ // Check and store if we are on a SDL backend that supports SDL_GetGlobalMouseState() and SDL_CaptureMouse()
+ // ("wayland" and "rpi" don't support it, but we chose to use a white-list instead of a black-list)
+ bd->MouseCanUseGlobalState = false;
+ bd->MouseCanUseCapture = false;
+#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE
+ const char* sdl_backend = SDL_GetCurrentVideoDriver();
+ const char* capture_and_global_state_whitelist[] = { "windows", "cocoa", "x11", "DIVE", "VMAN" };
+ for (const char* item : capture_and_global_state_whitelist)
+ if (strncmp(sdl_backend, item, strlen(item)) == 0)
+ bd->MouseCanUseGlobalState = bd->MouseCanUseCapture = true;
+#endif
+ if (bd->MouseCanUseGlobalState)
+ io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports; // We can create multi-viewports on the Platform side (optional)
+
ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
platform_io.Platform_SetClipboardTextFn = ImGui_ImplSDL2_SetClipboardText;
platform_io.Platform_GetClipboardTextFn = ImGui_ImplSDL2_GetClipboardText;
@@ -529,6 +586,8 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void
platform_io.Platform_SetImeDataFn = ImGui_ImplSDL2_PlatformSetImeData;
#ifdef __EMSCRIPTEN__
platform_io.Platform_OpenInShellFn = [](ImGuiContext*, const char* url) { ImGui_ImplSDL2_EmscriptenOpenURL(url); return true; };
+#elif SDL_HAS_OPEN_URL
+ platform_io.Platform_OpenInShellFn = [](ImGuiContext*, const char* url) { return SDL_OpenURL(url) == 0; };
#endif
// Update monitor a first time during init
@@ -547,6 +606,8 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void
bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENESW);
bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENWSE);
bd->MouseCursors[ImGuiMouseCursor_Hand] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_HAND);
+ bd->MouseCursors[ImGuiMouseCursor_Wait] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_WAIT);
+ bd->MouseCursors[ImGuiMouseCursor_Progress] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_WAITARROW);
bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NO);
// Set platform dependent data in viewport
@@ -664,8 +725,17 @@ static void ImGui_ImplSDL2_UpdateMouseData()
// We forward mouse input when hovered or captured (via SDL_MOUSEMOTION) or when focused (below)
#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE
- // SDL_CaptureMouse() let the OS know e.g. that our imgui drag outside the SDL window boundaries shouldn't e.g. trigger other operations outside
- SDL_CaptureMouse((bd->MouseButtonsDown != 0) ? SDL_TRUE : SDL_FALSE);
+ // - SDL_CaptureMouse() let the OS know e.g. that our drags can extend outside of parent boundaries (we want updated position) and shouldn't trigger other operations outside.
+ // - Debuggers under Linux tends to leave captured mouse on break, which may be very inconvenient, so to mitigate the issue we wait until mouse has moved to begin capture.
+ if (bd->MouseCanUseCapture)
+ {
+ bool want_capture = false;
+ for (int button_n = 0; button_n < ImGuiMouseButton_COUNT && !want_capture; button_n++)
+ if (ImGui::IsMouseDragging(button_n, 1.0f))
+ want_capture = true;
+ SDL_CaptureMouse(want_capture ? SDL_TRUE : SDL_FALSE);
+ }
+
SDL_Window* focused_window = SDL_GetKeyboardFocus();
const bool is_app_focused = (focused_window && (bd->Window == focused_window || ImGui_ImplSDL2_GetViewportForWindowID(SDL_GetWindowID(focused_window)) != NULL));
#else
@@ -687,7 +757,8 @@ static void ImGui_ImplSDL2_UpdateMouseData()
}
// (Optional) Fallback to provide mouse position when focused (SDL_MOUSEMOTION already provides this when hovered or captured)
- if (bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0)
+ const bool is_relative_mouse_mode = SDL_GetRelativeMouseMode() != 0;
+ if (bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0 && !is_relative_mouse_mode)
{
// Single-viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window)
// Multi-viewport mode: mouse position in OS absolute coordinates (io.MousePos is (0,0) when the mouse is on the upper-left of the primary monitor)
@@ -745,6 +816,30 @@ static void ImGui_ImplSDL2_UpdateMouseCursor()
}
}
+// - On Windows the process needs to be marked DPI-aware!! SDL2 doesn't do it by default. You can call ::SetProcessDPIAware() or call ImGui_ImplWin32_EnableDpiAwareness() from Win32 backend.
+// - Apple platforms use FramebufferScale so we always return 1.0f.
+// - Some accessibility applications are declaring virtual monitors with a DPI of 0.0f, see #7902. We preserve this value for caller to handle.
+float ImGui_ImplSDL2_GetContentScaleForWindow(SDL_Window* window)
+{
+ return ImGui_ImplSDL2_GetContentScaleForDisplay(SDL_GetWindowDisplayIndex(window));
+}
+
+float ImGui_ImplSDL2_GetContentScaleForDisplay(int display_index)
+{
+ const char* sdl_driver = SDL_GetCurrentVideoDriver();
+ if (sdl_driver && strcmp(sdl_driver, "wayland") == 0)
+ return 1.0f;
+#if SDL_HAS_PER_MONITOR_DPI
+#if !defined(__APPLE__) && !defined(__EMSCRIPTEN__) && !defined(__ANDROID__)
+ float dpi = 0.0f;
+ if (SDL_GetDisplayDPI(display_index, &dpi, nullptr, nullptr) == 0)
+ return dpi / 96.0f;
+#endif
+#endif
+ IM_UNUSED(display_index);
+ return 1.0f;
+}
+
static void ImGui_ImplSDL2_CloseGamepads()
{
ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
@@ -760,7 +855,7 @@ void ImGui_ImplSDL2_SetGamepadMode(ImGui_ImplSDL2_GamepadMode mode, struct _SDL_
ImGui_ImplSDL2_CloseGamepads();
if (mode == ImGui_ImplSDL2_GamepadMode_Manual)
{
- IM_ASSERT(manual_gamepads_array != nullptr && manual_gamepads_count > 0);
+ IM_ASSERT(manual_gamepads_array != nullptr || manual_gamepads_count <= 0);
for (int n = 0; n < manual_gamepads_count; n++)
bd->Gamepads.push_back(manual_gamepads_array[n]);
}
@@ -814,9 +909,6 @@ static void ImGui_ImplSDL2_UpdateGamepads()
bd->WantUpdateGamepadsList = false;
}
- // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs.
- if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0)
- return;
io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
if (bd->Gamepads.Size == 0)
return;
@@ -867,51 +959,55 @@ static void ImGui_ImplSDL2_UpdateMonitors()
monitor.MainPos = monitor.WorkPos = ImVec2((float)r.x, (float)r.y);
monitor.MainSize = monitor.WorkSize = ImVec2((float)r.w, (float)r.h);
#if SDL_HAS_USABLE_DISPLAY_BOUNDS
- SDL_GetDisplayUsableBounds(n, &r);
- monitor.WorkPos = ImVec2((float)r.x, (float)r.y);
- monitor.WorkSize = ImVec2((float)r.w, (float)r.h);
-#endif
-#if SDL_HAS_PER_MONITOR_DPI
- // FIXME-VIEWPORT: On MacOS SDL reports actual monitor DPI scale, ignoring OS configuration. We may want to set
- // DpiScale to cocoa_window.backingScaleFactor here.
- float dpi = 0.0f;
- if (!SDL_GetDisplayDPI(n, &dpi, nullptr, nullptr))
+ if (SDL_GetDisplayUsableBounds(n, &r) == 0 && r.w > 0 && r.h > 0)
{
- if (dpi <= 0.0f)
- continue; // Some accessibility applications are declaring virtual monitors with a DPI of 0, see #7902.
- monitor.DpiScale = dpi / 96.0f;
+ monitor.WorkPos = ImVec2((float)r.x, (float)r.y);
+ monitor.WorkSize = ImVec2((float)r.w, (float)r.h);
}
#endif
+ float dpi_scale = ImGui_ImplSDL2_GetContentScaleForDisplay(n);
+ if (dpi_scale <= 0.0f)
+ continue; // Some accessibility applications are declaring virtual monitors with a DPI of 0, see #7902.
+ monitor.DpiScale = dpi_scale;
monitor.PlatformHandle = (void*)(intptr_t)n;
platform_io.Monitors.push_back(monitor);
}
}
-void ImGui_ImplSDL2_NewFrame()
+static void ImGui_ImplSDL2_GetWindowSizeAndFramebufferScale(SDL_Window* window, SDL_Renderer* renderer, ImVec2* out_size, ImVec2* out_framebuffer_scale)
{
- ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
- IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDL2_Init()?");
- ImGuiIO& io = ImGui::GetIO();
-
- // Setup display size (every frame to accommodate for window resizing)
int w, h;
int display_w, display_h;
- SDL_GetWindowSize(bd->Window, &w, &h);
- if (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_MINIMIZED)
+ SDL_GetWindowSize(window, &w, &h);
+ if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED)
w = h = 0;
- if (bd->Renderer != nullptr)
- SDL_GetRendererOutputSize(bd->Renderer, &display_w, &display_h);
+ if (renderer != nullptr)
+ SDL_GetRendererOutputSize(renderer, &display_w, &display_h);
#if SDL_HAS_VULKAN
- else if (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_VULKAN)
- SDL_Vulkan_GetDrawableSize(bd->Window, &display_w, &display_h);
+ else if (SDL_GetWindowFlags(window) & SDL_WINDOW_VULKAN)
+ SDL_Vulkan_GetDrawableSize(window, &display_w, &display_h);
#endif
else
- SDL_GL_GetDrawableSize(bd->Window, &display_w, &display_h);
- io.DisplaySize = ImVec2((float)w, (float)h);
- if (w > 0 && h > 0)
- io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h);
+ SDL_GL_GetDrawableSize(window, &display_w, &display_h);
+ if (out_size != nullptr)
+ *out_size = ImVec2((float)w, (float)h);
+ if (out_framebuffer_scale != nullptr)
+ *out_framebuffer_scale = (w > 0 && h > 0) ? ImVec2((float)display_w / w, (float)display_h / h) : ImVec2(1.0f, 1.0f);
+}
+
+void ImGui_ImplSDL2_NewFrame()
+{
+ ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
+ IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDL2_Init()?");
+ ImGuiIO& io = ImGui::GetIO();
+
+ // Setup main viewport size (every frame to accommodate for window resizing)
+ ImGui_ImplSDL2_GetWindowSizeAndFramebufferScale(bd->Window, bd->Renderer, &io.DisplaySize, &io.DisplayFramebufferScale);
// Update monitors
+#ifdef WIN32
+ bd->WantUpdateMonitors = true; // Keep polling under Windows to handle changes of work area when resizing task-bar (#8415)
+#endif
if (bd->WantUpdateMonitors)
ImGui_ImplSDL2_UpdateMonitors();
@@ -951,16 +1047,16 @@ void ImGui_ImplSDL2_NewFrame()
// If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
//--------------------------------------------------------------------------------------------------------
-// Helper structure we store in the void* RendererUserData field of each ImGuiViewport to easily retrieve our backend data.
+// Helper structure we store in the void* PlatformUserData field of each ImGuiViewport to easily retrieve our backend data.
struct ImGui_ImplSDL2_ViewportData
{
SDL_Window* Window;
- Uint32 WindowID;
+ Uint32 WindowID; // Stored in ImGuiViewport::PlatformHandle. Use SDL_GetWindowFromID() to get SDL_Window* from Uint32 WindowID.
bool WindowOwned;
SDL_GLContext GLContext;
- ImGui_ImplSDL2_ViewportData() { Window = nullptr; WindowID = 0; WindowOwned = false; GLContext = nullptr; }
- ~ImGui_ImplSDL2_ViewportData() { IM_ASSERT(Window == nullptr && GLContext == nullptr); }
+ ImGui_ImplSDL2_ViewportData() { Window = nullptr; WindowID = 0; WindowOwned = false; GLContext = nullptr; }
+ ~ImGui_ImplSDL2_ViewportData() { IM_ASSERT(Window == nullptr && GLContext == nullptr); }
};
static void ImGui_ImplSDL2_CreateWindow(ImGuiViewport* viewport)
@@ -1037,7 +1133,7 @@ static void ImGui_ImplSDL2_DestroyWindow(ImGuiViewport* viewport)
static void ImGui_ImplSDL2_ShowWindow(ImGuiViewport* viewport)
{
ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData;
-#if defined(_WIN32) && !(defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP || WINAPI_FAMILY == WINAPI_FAMILY_GAMES))
+#if defined(_WIN32) && !(defined(WINAPI_FAMILY) && ((defined(WINAPI_FAMILY_APP) && WINAPI_FAMILY == WINAPI_FAMILY_APP) || (defined(WINAPI_FAMILY_GAMES) && WINAPI_FAMILY == WINAPI_FAMILY_GAMES)))
HWND hwnd = (HWND)viewport->PlatformHandleRaw;
// SDL hack: Hide icon from task bar
@@ -1092,6 +1188,15 @@ static void ImGui_ImplSDL2_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
SDL_SetWindowSize(vd->Window, (int)size.x, (int)size.y);
}
+static ImVec2 ImGui_ImplSDL2_GetWindowFramebufferScale(ImGuiViewport* viewport)
+{
+ // FIXME: SDL_Renderer does not support multi-viewport.
+ ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData;
+ ImVec2 framebuffer_scale;
+ ImGui_ImplSDL2_GetWindowSizeAndFramebufferScale(vd->Window, nullptr, nullptr, &framebuffer_scale);
+ return framebuffer_scale;
+}
+
static void ImGui_ImplSDL2_SetWindowTitle(ImGuiViewport* viewport, const char* title)
{
ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData;
@@ -1165,6 +1270,7 @@ static void ImGui_ImplSDL2_InitMultiViewportSupport(SDL_Window* window, void* sd
platform_io.Platform_GetWindowPos = ImGui_ImplSDL2_GetWindowPos;
platform_io.Platform_SetWindowSize = ImGui_ImplSDL2_SetWindowSize;
platform_io.Platform_GetWindowSize = ImGui_ImplSDL2_GetWindowSize;
+ platform_io.Platform_GetWindowFramebufferScale = ImGui_ImplSDL2_GetWindowFramebufferScale;
platform_io.Platform_SetWindowFocus = ImGui_ImplSDL2_SetWindowFocus;
platform_io.Platform_GetWindowFocus = ImGui_ImplSDL2_GetWindowFocus;
platform_io.Platform_GetWindowMinimized = ImGui_ImplSDL2_GetWindowMinimized;
diff --git a/source/code/Libs/imgui/backends/imgui_impl_sdl2.h b/source/code/Libs/imgui/backends/imgui_impl_sdl2.h index 78c76a8..aeecfad 100644 --- a/source/code/Libs/imgui/backends/imgui_impl_sdl2.h +++ b/source/code/Libs/imgui/backends/imgui_impl_sdl2.h
@@ -5,14 +5,14 @@
// Implemented features:
// [X] Platform: Clipboard support.
// [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen.
-// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set]
-// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
-// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
+// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values are obsolete since 1.87 and not supported since 1.91.5]
+// [X] Platform: Gamepad support.
+// [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
+// [X] Platform: Basic IME support. App needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!.
// [X] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
-// Issues:
+// Missing features or Issues:
// [ ] Platform: Multi-viewport: Minimized windows seems to break mouse wheel events (at least under Windows).
// [ ] Platform: Multi-viewport: ParentViewportID not honored, and so io.ConfigViewportsNoDefaultParent has no effect (minor).
-// [x] Platform: Basic IME support. App needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!.
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
@@ -42,9 +42,13 @@ IMGUI_IMPL_API void ImGui_ImplSDL2_Shutdown();
IMGUI_IMPL_API void ImGui_ImplSDL2_NewFrame();
IMGUI_IMPL_API bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event);
+// DPI-related helpers (optional)
+IMGUI_IMPL_API float ImGui_ImplSDL2_GetContentScaleForWindow(SDL_Window* window);
+IMGUI_IMPL_API float ImGui_ImplSDL2_GetContentScaleForDisplay(int display_index);
+
// Gamepad selection automatically starts in AutoFirst mode, picking first available SDL_Gamepad. You may override this.
// When using manual mode, caller is responsible for opening/closing gamepad.
enum ImGui_ImplSDL2_GamepadMode { ImGui_ImplSDL2_GamepadMode_AutoFirst, ImGui_ImplSDL2_GamepadMode_AutoAll, ImGui_ImplSDL2_GamepadMode_Manual };
-IMGUI_IMPL_API void ImGui_ImplSDL2_SetGamepadMode(ImGui_ImplSDL2_GamepadMode mode, struct _SDL_GameController** manual_gamepads_array = NULL, int manual_gamepads_count = -1);
+IMGUI_IMPL_API void ImGui_ImplSDL2_SetGamepadMode(ImGui_ImplSDL2_GamepadMode mode, struct _SDL_GameController** manual_gamepads_array = nullptr, int manual_gamepads_count = -1);
#endif // #ifndef IMGUI_DISABLE
diff --git a/source/code/Libs/imgui/backends/imgui_impl_sdlrenderer2.cpp b/source/code/Libs/imgui/backends/imgui_impl_sdlrenderer2.cpp index 3436be4..6019b5e 100644 --- a/source/code/Libs/imgui/backends/imgui_impl_sdlrenderer2.cpp +++ b/source/code/Libs/imgui/backends/imgui_impl_sdlrenderer2.cpp
@@ -1,15 +1,18 @@
// dear imgui: Renderer Backend for SDL_Renderer for SDL2
// (Requires: SDL 2.0.17+)
-// Note how SDL_Renderer is an _optional_ component of SDL2.
-// For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX.
-// If your application will want to render any non trivial amount of graphics other than UI,
-// please be aware that SDL_Renderer currently offers a limited graphic API to the end-user and
-// it might be difficult to step out of those boundaries.
+// Note that SDL_Renderer is an _optional_ component of SDL2, which IMHO is now largely obsolete.
+// For a multi-platform app consider using other technologies:
+// - SDL3+SDL_GPU: SDL_GPU is SDL3 new graphics abstraction API. You will need to update to SDL3.
+// - SDL2+DirectX, SDL2+OpenGL, SDL2+Vulkan: combine SDL with dedicated renderers.
+// If your application wants to render any non trivial amount of graphics other than UI,
+// please be aware that SDL_Renderer currently offers a limited graphic API to the end-user
+// and it might be difficult to step out of those boundaries.
// Implemented features:
-// [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID!
-// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+// [X] Renderer: User texture binding. Use 'SDL_Texture*' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef!
+// [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
+// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures).
// [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
// Missing features:
// [ ] Renderer: Multi-viewport support (multiple windows).
@@ -23,6 +26,8 @@
// - Introduction, links and more at the top of imgui.cpp
// CHANGELOG
+// 2025-06-11: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplSDLRenderer2_CreateFontsTexture() and ImGui_ImplSDLRenderer2_DestroyFontsTexture().
+// 2025-01-18: Use endian-dependent RGBA32 texture format, to match SDL_Color.
// 2024-10-09: Expose selected render state in ImGui_ImplSDLRenderer2_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
// 2024-05-14: *BREAKING CHANGE* ImGui_ImplSDLRenderer3_RenderDrawData() requires SDL_Renderer* passed as parameter.
// 2023-05-30: Renamed imgui_impl_sdlrenderer.h/.cpp to imgui_impl_sdlrenderer2.h/.cpp to accommodate for upcoming SDL3.
@@ -41,6 +46,8 @@
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
+#elif defined(__GNUC__)
+#pragma GCC diagnostic ignored "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe
#endif
// SDL
@@ -53,7 +60,7 @@
struct ImGui_ImplSDLRenderer2_Data
{
SDL_Renderer* Renderer; // Main viewport's renderer
- SDL_Texture* FontTexture;
+
ImGui_ImplSDLRenderer2_Data() { memset((void*)this, 0, sizeof(*this)); }
};
@@ -77,6 +84,7 @@ bool ImGui_ImplSDLRenderer2_Init(SDL_Renderer* renderer)
io.BackendRendererUserData = (void*)bd;
io.BackendRendererName = "imgui_impl_sdlrenderer2";
io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
+ io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render.
bd->Renderer = renderer;
@@ -93,44 +101,49 @@ void ImGui_ImplSDLRenderer2_Shutdown()
io.BackendRendererName = nullptr;
io.BackendRendererUserData = nullptr;
- io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset;
+ io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures);
IM_DELETE(bd);
}
static void ImGui_ImplSDLRenderer2_SetupRenderState(SDL_Renderer* renderer)
{
- // Clear out any viewports and cliprect set by the user
+ // Clear out any viewports and cliprect set by the user
// FIXME: Technically speaking there are lots of other things we could backup/setup/restore during our render process.
- SDL_RenderSetViewport(renderer, nullptr);
- SDL_RenderSetClipRect(renderer, nullptr);
+ SDL_RenderSetViewport(renderer, nullptr);
+ SDL_RenderSetClipRect(renderer, nullptr);
}
void ImGui_ImplSDLRenderer2_NewFrame()
{
ImGui_ImplSDLRenderer2_Data* bd = ImGui_ImplSDLRenderer2_GetBackendData();
IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDLRenderer2_Init()?");
-
- if (!bd->FontTexture)
- ImGui_ImplSDLRenderer2_CreateDeviceObjects();
+ IM_UNUSED(bd);
}
void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* renderer)
{
- // If there's a scale factor set by the user, use that instead
+ // If there's a scale factor set by the user, use that instead
// If the user has specified a scale factor to SDL_Renderer already via SDL_RenderSetScale(), SDL will scale whatever we pass
// to SDL_RenderGeometryRaw() by that scale factor. In that case we don't want to be also scaling it ourselves here.
float rsx = 1.0f;
- float rsy = 1.0f;
- SDL_RenderGetScale(renderer, &rsx, &rsy);
+ float rsy = 1.0f;
+ SDL_RenderGetScale(renderer, &rsx, &rsy);
ImVec2 render_scale;
- render_scale.x = (rsx == 1.0f) ? draw_data->FramebufferScale.x : 1.0f;
- render_scale.y = (rsy == 1.0f) ? draw_data->FramebufferScale.y : 1.0f;
-
- // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
- int fb_width = (int)(draw_data->DisplaySize.x * render_scale.x);
- int fb_height = (int)(draw_data->DisplaySize.y * render_scale.y);
- if (fb_width == 0 || fb_height == 0)
- return;
+ render_scale.x = (rsx == 1.0f) ? draw_data->FramebufferScale.x : 1.0f;
+ render_scale.y = (rsy == 1.0f) ? draw_data->FramebufferScale.y : 1.0f;
+
+ // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
+ int fb_width = (int)(draw_data->DisplaySize.x * render_scale.x);
+ int fb_height = (int)(draw_data->DisplaySize.y * render_scale.y);
+ if (fb_width == 0 || fb_height == 0)
+ return;
+
+ // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do.
+ // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates).
+ if (draw_data->Textures != nullptr)
+ for (ImTextureData* tex : *draw_data->Textures)
+ if (tex->Status != ImTextureStatus_OK)
+ ImGui_ImplSDLRenderer2_UpdateTexture(tex);
// Backup SDL_Renderer state that will be modified to restore it afterwards
struct BackupSDLRendererState
@@ -153,14 +166,13 @@ void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data, SDL_Renderer*
render_state.Renderer = renderer;
platform_io.Renderer_RenderState = &render_state;
- // Will project scissor/clipping rectangles into framebuffer space
- ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
- ImVec2 clip_scale = render_scale;
+ // Will project scissor/clipping rectangles into framebuffer space
+ ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
+ ImVec2 clip_scale = render_scale;
// Render command lists
- for (int n = 0; n < draw_data->CmdListsCount; n++)
+ for (const ImDrawList* draw_list : draw_data->CmdLists)
{
- const ImDrawList* draw_list = draw_data->CmdLists[n];
const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data;
const ImDrawIdx* idx_buffer = draw_list->IdxBuffer.Data;
@@ -200,7 +212,7 @@ void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data, SDL_Renderer*
#endif
// Bind texture, Draw
- SDL_Texture* tex = (SDL_Texture*)pcmd->GetTexID();
+ SDL_Texture* tex = (SDL_Texture*)pcmd->GetTexID();
SDL_RenderGeometryRaw(renderer, tex,
xy, (int)sizeof(ImDrawVert),
color, (int)sizeof(ImDrawVert),
@@ -210,62 +222,74 @@ void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data, SDL_Renderer*
}
}
}
- platform_io.Renderer_RenderState = NULL;
+ platform_io.Renderer_RenderState = nullptr;
// Restore modified SDL_Renderer state
SDL_RenderSetViewport(renderer, &old.Viewport);
SDL_RenderSetClipRect(renderer, old.ClipEnabled ? &old.ClipRect : nullptr);
}
-// Called by Init/NewFrame/Shutdown
-bool ImGui_ImplSDLRenderer2_CreateFontsTexture()
+void ImGui_ImplSDLRenderer2_UpdateTexture(ImTextureData* tex)
{
- ImGuiIO& io = ImGui::GetIO();
ImGui_ImplSDLRenderer2_Data* bd = ImGui_ImplSDLRenderer2_GetBackendData();
- // Build texture atlas
- unsigned char* pixels;
- int width, height;
- io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory.
-
- // Upload texture to graphics system
- // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
- bd->FontTexture = SDL_CreateTexture(bd->Renderer, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STATIC, width, height);
- if (bd->FontTexture == nullptr)
+ if (tex->Status == ImTextureStatus_WantCreate)
{
- SDL_Log("error creating texture");
- return false;
+ // Create and upload new texture to graphics system
+ //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height);
+ IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr);
+ IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
+
+ // Create texture
+ // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
+ SDL_Texture* sdl_texture = SDL_CreateTexture(bd->Renderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_STATIC, tex->Width, tex->Height);
+ IM_ASSERT(sdl_texture != nullptr && "Backend failed to create texture!");
+ SDL_UpdateTexture(sdl_texture, nullptr, tex->GetPixels(), tex->GetPitch());
+ SDL_SetTextureBlendMode(sdl_texture, SDL_BLENDMODE_BLEND);
+ SDL_SetTextureScaleMode(sdl_texture, SDL_ScaleModeLinear);
+
+ // Store identifiers
+ tex->SetTexID((ImTextureID)(intptr_t)sdl_texture);
+ tex->SetStatus(ImTextureStatus_OK);
}
- SDL_UpdateTexture(bd->FontTexture, nullptr, pixels, 4 * width);
- SDL_SetTextureBlendMode(bd->FontTexture, SDL_BLENDMODE_BLEND);
- SDL_SetTextureScaleMode(bd->FontTexture, SDL_ScaleModeLinear);
-
- // Store our identifier
- io.Fonts->SetTexID((ImTextureID)(intptr_t)bd->FontTexture);
-
- return true;
-}
-
-void ImGui_ImplSDLRenderer2_DestroyFontsTexture()
-{
- ImGuiIO& io = ImGui::GetIO();
- ImGui_ImplSDLRenderer2_Data* bd = ImGui_ImplSDLRenderer2_GetBackendData();
- if (bd->FontTexture)
+ else if (tex->Status == ImTextureStatus_WantUpdates)
{
- io.Fonts->SetTexID(0);
- SDL_DestroyTexture(bd->FontTexture);
- bd->FontTexture = nullptr;
+ // Update selected blocks. We only ever write to textures regions which have never been used before!
+ // This backend choose to use tex->Updates[] but you can use tex->UpdateRect to upload a single region.
+ SDL_Texture* sdl_texture = (SDL_Texture*)(intptr_t)tex->TexID;
+ for (ImTextureRect& r : tex->Updates)
+ {
+ SDL_Rect sdl_r = { r.x, r.y, r.w, r.h };
+ SDL_UpdateTexture(sdl_texture, &sdl_r, tex->GetPixelsAt(r.x, r.y), tex->GetPitch());
+ }
+ tex->SetStatus(ImTextureStatus_OK);
+ }
+ else if (tex->Status == ImTextureStatus_WantDestroy)
+ {
+ SDL_Texture* sdl_texture = (SDL_Texture*)(intptr_t)tex->TexID;
+ if (sdl_texture == nullptr)
+ return;
+ SDL_DestroyTexture(sdl_texture);
+
+ // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running)
+ tex->SetTexID(ImTextureID_Invalid);
+ tex->SetStatus(ImTextureStatus_Destroyed);
}
}
-bool ImGui_ImplSDLRenderer2_CreateDeviceObjects()
+void ImGui_ImplSDLRenderer2_CreateDeviceObjects()
{
- return ImGui_ImplSDLRenderer2_CreateFontsTexture();
}
void ImGui_ImplSDLRenderer2_DestroyDeviceObjects()
{
- ImGui_ImplSDLRenderer2_DestroyFontsTexture();
+ // Destroy all textures
+ for (ImTextureData* tex : ImGui::GetPlatformIO().Textures)
+ if (tex->RefCount == 1)
+ {
+ tex->SetStatus(ImTextureStatus_WantDestroy);
+ ImGui_ImplSDLRenderer2_UpdateTexture(tex);
+ }
}
//-----------------------------------------------------------------------------
diff --git a/source/code/Libs/imgui/backends/imgui_impl_sdlrenderer2.h b/source/code/Libs/imgui/backends/imgui_impl_sdlrenderer2.h index fe2ef62..3d8de5f 100644 --- a/source/code/Libs/imgui/backends/imgui_impl_sdlrenderer2.h +++ b/source/code/Libs/imgui/backends/imgui_impl_sdlrenderer2.h
@@ -1,15 +1,18 @@
// dear imgui: Renderer Backend for SDL_Renderer for SDL2
// (Requires: SDL 2.0.17+)
-// Note how SDL_Renderer is an _optional_ component of SDL2.
-// For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX.
-// If your application will want to render any non trivial amount of graphics other than UI,
-// please be aware that SDL_Renderer currently offers a limited graphic API to the end-user and
-// it might be difficult to step out of those boundaries.
+// Note that SDL_Renderer is an _optional_ component of SDL2, which IMHO is now largely obsolete.
+// For a multi-platform app consider using other technologies:
+// - SDL3+SDL_GPU: SDL_GPU is SDL3 new graphics abstraction API. You will need to update to SDL3.
+// - SDL2+DirectX, SDL2+OpenGL, SDL2+Vulkan: combine SDL with dedicated renderers.
+// If your application wants to render any non trivial amount of graphics other than UI,
+// please be aware that SDL_Renderer currently offers a limited graphic API to the end-user
+// and it might be difficult to step out of those boundaries.
// Implemented features:
-// [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID!
-// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+// [X] Renderer: User texture binding. Use 'SDL_Texture*' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef!
+// [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
+// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures).
// [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
// Missing features:
// [ ] Renderer: Multi-viewport support (multiple windows).
@@ -35,11 +38,12 @@ IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_NewFrame();
IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* renderer);
// Called by Init/NewFrame/Shutdown
-IMGUI_IMPL_API bool ImGui_ImplSDLRenderer2_CreateFontsTexture();
-IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_DestroyFontsTexture();
-IMGUI_IMPL_API bool ImGui_ImplSDLRenderer2_CreateDeviceObjects();
+IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_CreateDeviceObjects();
IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_DestroyDeviceObjects();
+// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually.
+IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_UpdateTexture(ImTextureData* tex);
+
// [BETA] Selected render state data shared with callbacks.
// This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplSDLRenderer2_RenderDrawData() call.
// (Please open an issue if you feel you need access to more data)
diff --git a/source/code/Libs/imgui/imconfig.h b/source/code/Libs/imgui/imconfig.h index 63d6ba0..4dab1b6 100644 --- a/source/code/Libs/imgui/imconfig.h +++ b/source/code/Libs/imgui/imconfig.h
@@ -29,7 +29,6 @@
//---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to clean your code of obsolete function/names.
//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS
-//#define IMGUI_DISABLE_OBSOLETE_KEYIO // 1.87+ disable legacy io.KeyMap[]+io.KeysDown[] in favor io.AddKeyEvent(). This is automatically done by IMGUI_DISABLE_OBSOLETE_FUNCTIONS.
//---- Disable all of Dear ImGui or don't implement standard windows/tools.
// It is very strongly recommended to NOT disable the demo windows and debug tool during development. They are extremely useful in day to day work. Please read comments in imgui_demo.cpp.
@@ -49,6 +48,7 @@
//#define IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle at all (replace them with dummies)
//#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle 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().
+//#define IMGUI_DISABLE_DEFAULT_FONT // Disable default embedded font (ProggyClean.ttf), remove ~9.5 KB from output binary. AddFontDefault() will assert.
//#define IMGUI_DISABLE_SSE // Disable use of SSE intrinsics even if available
//---- Enable Test Engine / Automation features.
@@ -59,9 +59,12 @@
//#define IMGUI_INCLUDE_IMGUI_USER_H
//#define IMGUI_USER_H_FILENAME "my_folder/my_imgui_user.h"
-//---- Pack colors to BGRA8 instead of RGBA8 (to avoid converting from one to another)
+//---- Pack vertex colors as BGRA8 instead of RGBA8 (to avoid converting from one to another). Need dedicated backend support.
//#define IMGUI_USE_BGRA_PACKED_COLOR
+//---- Use legacy CRC32-adler tables (used before 1.91.6), in order to preserve old .ini data that you cannot afford to invalidate.
+//#define IMGUI_USE_LEGACY_CRC32_ADLER
+
//---- 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
@@ -85,8 +88,7 @@
//---- Use FreeType + plutosvg or lunasvg to render OpenType SVG fonts (SVGinOT)
// Only works in combination with IMGUI_ENABLE_FREETYPE.
-// - lunasvg is currently easier to acquire/install, as e.g. it is part of vcpkg.
-// - plutosvg will support more fonts and may load them faster. It currently requires to be built manually but it is fairly easy. See misc/freetype/README for instructions.
+// - plutosvg is currently easier to install, as e.g. it is part of vcpkg. It will support more fonts and may load them faster. See misc/freetype/README for instructions.
// - Both require headers to be available in the include path + program to be linked with the library code (not provided).
// - (note: lunasvg implementation is based on Freetype's rsvg-port.c which is licensed under CeCILL-C Free Software License Agreement)
//#define IMGUI_ENABLE_FREETYPE_PLUTOSVG
@@ -127,6 +129,10 @@
//#define IM_DEBUG_BREAK IM_ASSERT(0)
//#define IM_DEBUG_BREAK __debugbreak()
+//---- Debug Tools: Enable highlight ID conflicts _before_ hovering items. When io.ConfigDebugHighlightIdConflicts is set.
+// (THIS WILL SLOW DOWN DEAR IMGUI. Only use occasionally and disable after use)
+//#define IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS
+
//---- Debug Tools: Enable slower asserts
//#define IMGUI_DEBUG_PARANOID
diff --git a/source/code/Libs/imgui/imgui.cpp b/source/code/Libs/imgui/imgui.cpp index 455063a..0c635c6 100644 --- a/source/code/Libs/imgui/imgui.cpp +++ b/source/code/Libs/imgui/imgui.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.4
+// dear imgui, v1.92.3
// (main code and documentation)
// Help:
@@ -21,11 +21,12 @@
// - Issues & support ........... https://github.com/ocornut/imgui/issues
// - Test Engine & Automation ... https://github.com/ocornut/imgui_test_engine (test suite, test engine to automate your apps)
-// For first-time users having issues compiling/linking/running/loading fonts:
+// For first-time users having issues compiling/linking/running:
// please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
// Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there.
+// Since 1.92, we encourage font loading questions to also be posted in 'Issues'.
-// Copyright (c) 2014-2024 Omar Cornut
+// Copyright (c) 2014-2025 Omar Cornut
// 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 needs your support to sustain development and maintenance.
@@ -52,7 +53,7 @@ DOCUMENTATION
- 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 CUSTOM BACKEND / CUSTOM ENGINE
- API BREAKING CHANGES (read me when you update!)
- FREQUENTLY ASKED QUESTIONS (FAQ)
- Read all answers online: https://www.dearimgui.com/faq, or in docs/FAQ.md (with a Markdown viewer)
@@ -77,6 +78,7 @@ CODE
// [SECTION] RENDER HELPERS
// [SECTION] INITIALIZATION, SHUTDOWN
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
+// [SECTION] FONTS, TEXTURES
// [SECTION] ID STACK
// [SECTION] INPUTS
// [SECTION] ERROR CHECKING, STATE RECOVERY
@@ -85,6 +87,7 @@ CODE
// [SECTION] SCROLLING
// [SECTION] TOOLTIPS
// [SECTION] POPUPS
+// [SECTION] WINDOW FOCUS
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
// [SECTION] DRAG AND DROP
// [SECTION] LOGGING/CAPTURING
@@ -142,7 +145,8 @@ CODE
- CTRL+Shift+Left/Right: Select words.
- CTRL+A or Double-Click: Select All.
- CTRL+X, CTRL+C, CTRL+V: Use OS clipboard.
- - CTRL+Z, CTRL+Y: Undo, Redo.
+ - CTRL+Z Undo.
+ - CTRL+Y or CTRL+Shift+Z: Redo.
- ESCAPE: Revert text to its original value.
- On OSX, controls are automatically adjusted to match standard OSX text editing 2ts and behaviors.
@@ -175,7 +179,6 @@ CODE
- Set 'io.BackendFlags |= ImGuiBackendFlags_HasGamepad' + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
- For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
- - BEFORE 1.87, BACKENDS USED TO WRITE TO io.NavInputs[]. This is now obsolete. Please call io functions instead!
- If you need to share inputs between your game and the Dear ImGui interface, 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.
@@ -272,7 +275,8 @@ CODE
HOW A SIMPLE APPLICATION MAY LOOK LIKE
--------------------------------------
- EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
+
+ USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
The sub-folders in examples/ contain examples applications following this structure.
// Application init: create a dear imgui context, setup some options, load fonts
@@ -297,7 +301,7 @@ CODE
// Any application code here
ImGui::Text("Hello, world!");
- // Render dear imgui into screen
+ // Render dear imgui into framebuffer
ImGui::Render();
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
g_pSwapChain->Present(1, 0);
@@ -308,26 +312,36 @@ CODE
ImGui_ImplWin32_Shutdown();
ImGui::DestroyContext();
- EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
+ To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
+ you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
+ Please read the FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" about this.
+
- // Application init: create a dear imgui context, setup some options, load fonts
+USING CUSTOM BACKEND / CUSTOM ENGINE
+------------------------------------
+
+IMPLEMENTING YOUR PLATFORM BACKEND:
+ -> see https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md for basic instructions.
+ -> the Platform backends in impl_impl_XXX.cpp files contain many implementations.
+
+IMPLEMENTING YOUR RenderDrawData() function:
+ -> see https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md
+ -> the Renderer Backends in impl_impl_XXX.cpp files contain many implementations of a ImGui_ImplXXXX_RenderDrawData() function.
+
+IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures:
+ -> see https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md
+ -> the Renderer Backends in impl_impl_XXX.cpp files contain many implementations of a ImGui_ImplXXXX_UpdateTexture() function.
+
+ Basic application/backend skeleton:
+
+ // Application init: create a Dear ImGui context, setup some options, load fonts
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
- // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
- // TODO: Fill optional fields of the io structure later.
- // TODO: Load TTF/OTF fonts if you don't want to use the default font.
+ // TODO: set io.ConfigXXX values, e.g.
+ io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable keyboard controls
- // Build and load the texture atlas into a texture
- // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
- int width, height;
- unsigned char* pixels = nullptr;
- io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
-
- // At this point you've got the texture data and you need to upload that to your graphic system:
- // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
- // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
- MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
- io.Fonts->SetTexID((void*)texture);
+ // TODO: Load TTF/OTF fonts if you don't want to use the default font.
+ io.Fonts->AddFontFromFileTTF("NotoSans.ttf");
// Application main loop
while (true)
@@ -350,77 +364,25 @@ CODE
MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
MyGameRender(); // may use any Dear ImGui functions as well!
- // Render dear imgui, swap buffers
+ // End the dear imgui frame
// (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
- ImGui::EndFrame();
+ ImGui::EndFrame(); // this is automatically called by Render(), but available
ImGui::Render();
+
+ // Update textures
ImDrawData* draw_data = ImGui::GetDrawData();
- MyImGuiRenderFunction(draw_data);
+ for (ImTextureData* tex : *draw_data->Textures)
+ if (tex->Status != ImTextureStatus_OK)
+ MyImGuiBackend_UpdateTexture(tex);
+
+ // Render dear imgui contents, swap buffers
+ MyImGuiBackend_RenderDrawData(draw_data);
SwapBuffers();
}
// Shutdown
ImGui::DestroyContext();
- To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
- you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
- Please read the FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" about this.
-
-
- HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
- ---------------------------------------------
- The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
-
- void MyImGuiRenderFunction(ImDrawData* draw_data)
- {
- // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
- // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering.
- // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
- // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
- // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
- ImVec2 clip_off = draw_data->DisplayPos;
- for (int n = 0; n < draw_data->CmdListsCount; n++)
- {
- const ImDrawList* cmd_list = draw_data->CmdLists[n];
- const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by Dear ImGui
- const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by Dear ImGui
- for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
- {
- const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
- if (pcmd->UserCallback)
- {
- pcmd->UserCallback(cmd_list, pcmd);
- }
- else
- {
- // Project scissor/clipping rectangles into framebuffer space
- ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
- ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
- if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
- continue;
-
- // We are using scissoring to clip some objects. All low-level graphics API should support it.
- // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
- // (some elements visible outside their bounds) but you can fix that once everything else works!
- // - Clipping coordinates are provided in imgui coordinates space:
- // - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
- // - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values.
- // - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
- // always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
- // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
- MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y);
-
- // The texture for the draw call is specified by pcmd->GetTexID().
- // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
- MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
-
- // Render 'pcmd->ElemCount/3' indexed triangles.
- // 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 + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset);
- }
- }
- }
- }
API BREAKING CHANGES
@@ -432,12 +394,139 @@ CODE
You can read releases logs https://github.com/ocornut/imgui/releases for more details.
(Docking/Viewport Branch)
- - 2024/XX/XX (1.XXXX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
+ - 2025/XX/XX (1.XXXX) - 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.
+ - 2025/08/08 (1.92.2) - Backends: SDL_GPU3: Changed ImTextureID type from SDL_GPUTextureSamplerBinding* to SDL_GPUTexture*, which is more natural and easier for user to manage. If you need to change the current sampler, you can access the ImGui_ImplSDLGPU3_RenderState struct. (#8866, #8163, #7998, #7988)
+ - 2025/07/31 (1.92.2) - Tabs: Renamed ImGuiTabBarFlags_FittingPolicyResizeDown to ImGuiTabBarFlags_FittingPolicyShrink. Kept inline redirection enum (will obsolete).
+ - 2025/06/25 (1.92.0) - Layout: commented out legacy ErrorCheckUsingSetCursorPosToExtendParentBoundaries() fallback obsoleted in 1.89 (August 2022) which allowed a SetCursorPos()/SetCursorScreenPos() call WITHOUT AN ITEM
+ to extend parent window/cell boundaries. Replaced with assert/tooltip that would already happens if previously using IMGUI_DISABLE_OBSOLETE_FUNCTIONS. (#5548, #4510, #3355, #1760, #1490, #4152, #150)
+ - Incorrect way to make a window content size 200x200:
+ Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
+ - Correct ways to make a window content size 200x200:
+ Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
+ Begin(...) + Dummy(ImVec2(200,200)) + End();
+ - TL;DR; if the assert triggers, you can add a Dummy({0,0}) call to validate extending parent boundaries.
+ - 2025/06/11 (1.92.0) - Renamed/moved ImGuiConfigFlags_DpiEnableScaleFonts -> bool io.ConfigDpiScaleFonts.
+ - Renamed/moved ImGuiConfigFlags_DpiEnableScaleViewports -> bool io.ConfigDpiScaleViewports. **Neither of those flags are very useful in current code. They will be useful once we merge font changes.**
+ [there was a bug on 2025/06/12: when using the old config flags names, they were not imported correctly into the new ones, fixed on 2025/09/12]
+ - 2025/06/11 (1.92.0) - THIS VERSION CONTAINS THE LARGEST AMOUNT OF BREAKING CHANGES SINCE 2015! I TRIED REALLY HARD TO KEEP THEM TO A MINIMUM, REDUCE THE AMOUNT OF INTERFERENCES, BUT INEVITABLY SOME USERS WILL BE AFFECTED.
+ IN ORDER TO HELP US IMPROVE THE TRANSITION PROCESS, INCL. DOCUMENTATION AND COMMENTS, PLEASE REPORT **ANY** DOUBT, CONFUSION, QUESTIONS, FEEDBACK TO: https://github.com/ocornut/imgui/issues/
+ As part of the plan to reduce impact of API breaking changes, several unfinished changes/features/refactors related to font and text systems and scaling will be part of subsequent releases (1.92.1+).
+ If you are updating from an old version, and expecting a massive or difficult update, consider first updating to 1.91.9 to reduce the amount of changes.
+ - Hard to read? Refer to 'docs/Changelog.txt' for a less compact and more complete version of this!
+ - Fonts: **IMPORTANT**: if your app was solving the OSX/iOS Retina screen specific logical vs display scale problem by setting io.DisplayFramebufferScale (e.g. to 2.0f) + setting io.FontGlobalScale (e.g. to 1.0f/2.0f) + loading fonts at scaled sizes (e.g. size X * 2.0f):
+ This WILL NOT map correctly to the new system! Because font will rasterize as requested size.
+ - With a legacy backend (< 1.92): Instead of setting io.FontGlobalScale = 1.0f/N -> set ImFontCfg::RasterizerDensity = N. This already worked before, but is now pretty much required.
+ - With a new backend (1.92+): This should be all automatic. FramebufferScale is automatically used to set current font RasterizerDensity. FramebufferScale is a per-viewport property provided by backend through the Platform_GetWindowFramebufferScale() handler in 'docking' branch.
+ - Fonts: **IMPORTANT** on Font Sizing: Before 1.92, fonts were of a single size. They can now be dynamically sized.
+ - PushFont() API now has a REQUIRED size parameter.
+ - Before 1.92: PushFont() always used font "default" size specified in AddFont() call. It is equivalent to calling PushFont(font, font->LegacySize).
+ - Since 1.92: PushFont(font, 0.0f) preserve the current font size which is a shared value.
+ - To use old behavior: use 'ImGui::PushFont(font, font->LegacySize)' at call site.
+ - Kept inline single parameter function. Will obsolete.
+ - Fonts: **IMPORTANT** on Font Merging:
+ - When searching for a glyph in multiple merged fonts: we search for the FIRST font source which contains the desired glyph.
+ Because the user doesn't need to provide glyph ranges any more, it is possible that a glyph that you expected to fetch from a secondary/merged icon font may be erroneously fetched from the primary font.
+ - When searching for a glyph in multiple merged fonts: we now search for the FIRST font source which contains the desired glyph. This is technically a different behavior than before!
+ - e.g. If you are merging fonts you may have glyphs that you expected to load from Font Source 2 which exists in Font Source 1.
+ After the update and when using a new backend, those glyphs may now loaded from Font Source 1!
+ - We added `ImFontConfig::GlyphExcludeRanges[]` to specify ranges to exclude from a given font source:
+ // Add Font Source 1 but ignore ICON_MIN_FA..ICON_MAX_FA range
+ static ImWchar exclude_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 };
+ ImFontConfig cfg1;
+ cfg1.GlyphExcludeRanges = exclude_ranges;
+ io.Fonts->AddFontFromFileTTF("segoeui.ttf", 0.0f, &cfg1);
+ // Add Font Source 2, which expects to use the range above
+ ImFontConfig cfg2;
+ cfg2.MergeMode = true;
+ io.Fonts->AddFontFromFileTTF("FontAwesome4.ttf", 0.0f, &cfg2);
+ - You can use `Metrics/Debugger->Fonts->Font->Input Glyphs Overlap Detection Tool` to see list of glyphs available in multiple font sources. This can facilitate unde
+ - Fonts: **IMPORTANT** on Thread Safety:
+ - A few functions such as font->CalcTextSizeA() were, by sheer luck (== accidentally) thread-safe even thou we had never provided that guarantee. They are definitively not thread-safe anymore as new glyphs may be loaded.
+ - Fonts: ImFont::FontSize was removed and does not make sense anymore. ImFont::LegacySize is the size passed to AddFont().
+ - Fonts: Removed support for PushFont(NULL) which was a shortcut for "default font".
+ - Fonts: Renamed/moved 'io.FontGlobalScale' to 'style.FontScaleMain'.
+ - Textures: all API functions taking a 'ImTextureID' parameter are now taking a 'ImTextureRef'. Affected functions are: ImGui::Image(), ImGui::ImageWithBg(), ImGui::ImageButton(), ImDrawList::AddImage(), ImDrawList::AddImageQuad(), ImDrawList::AddImageRounded().
+ - Fonts: obsoleted ImFontAtlas::GetTexDataAsRGBA32(), GetTexDataAsAlpha8(), Build(), SetTexID(), IsBuilt() functions. The new protocol for backends to handle textures doesn't need them. Kept redirection functions (will obsolete).
+ - Fonts: ImFontConfig::OversampleH/OversampleV default to automatic (== 0) since v1.91.8. It is quite important you keep it automatic until we decide if we want to provide a way to express finer policy, otherwise you will likely waste texture space when using large glyphs. Note that the imgui_freetype backend doesn't use and does not need oversampling.
+ - Fonts: specifying glyph ranges is now unnecessary. The value of ImFontConfig::GlyphRanges[] is only useful for legacy backends. All GetGlyphRangesXXXX() functions are now marked obsolete: GetGlyphRangesDefault(), GetGlyphRangesGreek(), GetGlyphRangesKorean(), GetGlyphRangesJapanese(), GetGlyphRangesChineseSimplifiedCommon(), GetGlyphRangesChineseFull(), GetGlyphRangesCyrillic(), GetGlyphRangesThai(), GetGlyphRangesVietnamese().
+ - Fonts: removed ImFontAtlas::TexDesiredWidth to enforce a texture width. (#327)
+ - Fonts: if you create and manage ImFontAtlas instances yourself (instead of relying on ImGuiContext to create one), you'll need to call ImFontAtlasUpdateNewFrame() yourself. An assert will trigger if you don't.
+ - Fonts: obsolete ImGui::SetWindowFontScale() which is not useful anymore. Prefer using 'PushFont(NULL, style.FontSizeBase * factor)' or to manipulate other scaling factors.
+ - Fonts: obsoleted ImFont::Scale which is not useful anymore.
+ - Fonts: generally reworked Internals of ImFontAtlas and ImFont. While in theory a vast majority of users shouldn't be affected, some use cases or extensions might be. Among other things:
+ - ImDrawCmd::TextureId has been changed to ImDrawCmd::TexRef.
+ - ImFontAtlas::TexID has been changed to ImFontAtlas::TexRef.
+ - ImFontAtlas::ConfigData[] has been renamed to ImFontAtlas::Sources[]
+ - ImFont::ConfigData[], ConfigDataCount has been renamed to Sources[], SourceCount.
+ - Each ImFont has a number of ImFontBaked instances corresponding to actively used sizes. ImFont::GetFontBaked(size) retrieves the one for a given size.
+ - Fields moved from ImFont to ImFontBaked: IndexAdvanceX[], Glyphs[], Ascent, Descent, FindGlyph(), FindGlyphNoFallback(), GetCharAdvance().
+ - Fields moved from ImFontAtlas to ImFontAtlas->Tex: ImFontAtlas::TexWidth => TexData->Width, ImFontAtlas::TexHeight => TexData->Height, ImFontAtlas::TexPixelsAlpha8/TexPixelsRGBA32 => TexData->GetPixels().
+ - Widget code may use ImGui::GetFontBaked() instead of ImGui::GetFont() to access font data for current font at current font size (and you may use font->GetFontBaked(size) to access it for any other size.)
+ - Fonts: (users of imgui_freetype): renamed ImFontAtlas::FontBuilderFlags to ImFontAtlas::FontLoaderFlags. Renamed ImFontConfig::FontBuilderFlags to ImFontConfig::FontLoaderFlags. Renamed ImGuiFreeTypeBuilderFlags to ImGuiFreeTypeLoaderFlags.
+ If you used runtime imgui_freetype selection rather than the default IMGUI_ENABLE_FREETYPE compile-time option: Renamed/reworked ImFontBuilderIO into ImFontLoader. Renamed ImGuiFreeType::GetBuilderForFreeType() to ImGuiFreeType::GetFontLoader().
+ - old: io.Fonts->FontBuilderIO = ImGuiFreeType::GetBuilderForFreeType()
+ - new: io.Fonts->FontLoader = ImGuiFreeType::GetFontLoader()
+ - new: io.Fonts->SetFontLoader(ImGuiFreeType::GetFontLoader()) to change dynamically at runtime [from 1.92.1]
+ - Fonts: (users of custom rectangles, see #8466): Renamed AddCustomRectRegular() to AddCustomRect(). Added GetCustomRect() as a replacement for GetCustomRectByIndex() + CalcCustomRectUV().
+ - The output type of GetCustomRect() is now ImFontAtlasRect, which include UV coordinates. X->x, Y->y, Width->w, Height->h.
+ - old:
+ const ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(custom_rect_id);
+ ImVec2 uv0, uv1;
+ atlas->GetCustomRectUV(r, &uv0, &uv1);
+ ImGui::Image(atlas->TexRef, ImVec2(r->w, r->h), uv0, uv1);
+ - new;
+ ImFontAtlasRect r;
+ atlas->GetCustomRect(custom_rect_id, &r);
+ ImGui::Image(atlas->TexRef, ImVec2(r.w, r.h), r.uv0, r.uv1);
+ - We added a redirecting typedef but haven't attempted to magically redirect the field names, as this API is rarely used and the fix is simple.
+ - Obsoleted AddCustomRectFontGlyph() as the API does not make sense for scalable fonts. Kept existing function which uses the font "default size" (Sources[0]->LegacySize). Added a helper AddCustomRectFontGlyphForSize() which is immediately marked obsolete, but can facilitate transitioning old code.
+ - Prefer adding a font source (ImFontConfig) using a custom/procedural loader.
+ - DrawList: Renamed ImDrawList::PushTextureID()/PopTextureID() to PushTexture()/PopTexture().
+ - Backends: removed ImGui_ImplXXXX_CreateFontsTexture()/ImGui_ImplXXXX_DestroyFontsTexture() for all backends that had them. They should not be necessary any more.
+ - 2025/05/23 (1.92.0) - Fonts: changed ImFont::CalcWordWrapPositionA() to ImFont::CalcWordWrapPosition()
+ - old: const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, ....);
+ - new: const char* ImFont::CalcWordWrapPosition (float size, const char* text, ....);
+ The leading 'float scale' parameters was changed to 'float size'. This was necessary as 'scale' is assuming standard font size which is a concept we aim to eliminate in an upcoming update. Kept inline redirection function.
+ - 2025/05/15 (1.92.0) - TreeNode: renamed ImGuiTreeNodeFlags_NavLeftJumpsBackHere to ImGuiTreeNodeFlags_NavLeftJumpsToParent for clarity. Kept inline redirection enum (will obsolete).
+ - 2025/05/15 (1.92.0) - Commented out PushAllowKeyboardFocus()/PopAllowKeyboardFocus() which was obsoleted in 1.89.4. Use PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop)/PopItemFlag() instead. (#3092)
+ - 2025/05/15 (1.92.0) - Commented out ImGuiListClipper::ForceDisplayRangeByIndices() which was obsoleted in 1.89.6. Use ImGuiListClipper::IncludeItemsByIndex() instead.
+ - 2025/03/05 (1.91.9) - BeginMenu(): Internals: reworked mangling of menu windows to use "###Menu_00" etc. instead of "##Menu_00", allowing them to also store the menu name before it. This shouldn't affect code unless directly accessing menu window from their mangled name.
+ - 2025/04/16 (1.91.9) - Internals: RenderTextEllipsis() function removed the 'float clip_max_x' parameter directly preceding 'float ellipsis_max_x'. Values were identical for a vast majority of users. (#8387)
+ - 2025/02/27 (1.91.9) - Image(): removed 'tint_col' and 'border_col' parameter from Image() function. Added ImageWithBg() replacement. (#8131, #8238)
+ - old: void Image (ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1), ImVec4 tint_col = (1,1,1,1), ImVec4 border_col = (0,0,0,0));
+ - new: void Image (ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1));
+ - new: void ImageWithBg(ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1), ImVec4 bg_col = (0,0,0,0), ImVec4 tint_col = (1,1,1,1));
+ - TL;DR: 'border_col' had misleading side-effect on layout, 'bg_col' was missing, parameter order couldn't be consistent with ImageButton().
+ - new behavior always use ImGuiCol_Border color + style.ImageBorderSize / ImGuiStyleVar_ImageBorderSize.
+ - old behavior altered border size (and therefore layout) based on border color's alpha, which caused variety of problems + old behavior a fixed 1.0f for border size which was not tweakable.
+ - kept legacy signature (will obsolete), which mimics the old behavior, but uses Max(1.0f, style.ImageBorderSize) when border_col is specified.
+ - added ImageWithBg() function which has both 'bg_col' (which was missing) and 'tint_col'. It was impossible to add 'bg_col' to Image() with a parameter order consistent with other functions, so we decided to remove 'tint_col' and introduce ImageWithBg().
+ - 2025/02/25 (1.91.9) - internals: fonts: ImFontAtlas::ConfigData[] has been renamed to ImFontAtlas::Sources[]. ImFont::ConfigData[], ConfigDataCount has been renamed to Sources[], SourcesCount.
+ - 2025/02/06 (1.91.9) - renamed ImFontConfig::GlyphExtraSpacing.x to ImFontConfig::GlyphExtraAdvanceX.
+ - 2025/01/22 (1.91.8) - removed ImGuiColorEditFlags_AlphaPreview (made value 0): it is now the default behavior.
+ prior to 1.91.8: alpha was made opaque in the preview by default _unless_ using ImGuiColorEditFlags_AlphaPreview. We now display the preview as transparent by default. You can use ImGuiColorEditFlags_AlphaOpaque to use old behavior.
+ the new flags (ImGuiColorEditFlags_AlphaOpaque, ImGuiColorEditFlags_AlphaNoBg + existing ImGuiColorEditFlags_AlphaPreviewHalf) may be combined better and allow finer controls:
+ - 2025/01/14 (1.91.7) - renamed ImGuiTreeNodeFlags_SpanTextWidth to ImGuiTreeNodeFlags_SpanLabelWidth for consistency with other names. Kept redirection enum (will obsolete). (#6937)
+ - 2024/11/27 (1.91.6) - changed CRC32 table from CRC32-adler to CRC32c polynomial in order to be compatible with the result of SSE 4.2 instructions.
+ As a result, old .ini data may be partially lost (docking and tables information particularly).
+ Because some users have crafted and storing .ini data as a way to workaround limitations of the docking API, we are providing a '#define IMGUI_USE_LEGACY_CRC32_ADLER' compile-time option to keep using old CRC32 tables if you cannot afford invalidating old .ini data.
+ - 2024/11/06 (1.91.5) - commented/obsoleted out pre-1.87 IO system (equivalent to using IMGUI_DISABLE_OBSOLETE_KEYIO or IMGUI_DISABLE_OBSOLETE_FUNCTIONS before)
+ - io.KeyMap[] and io.KeysDown[] are removed (obsoleted February 2022).
+ - io.NavInputs[] and ImGuiNavInput are removed (obsoleted July 2022).
+ - pre-1.87 backends are not supported:
+ - backends need to call io.AddKeyEvent(), io.AddMouseEvent() instead of writing to io.KeysDown[], io.MouseDown[] fields.
+ - backends need to call io.AddKeyAnalogEvent() for gamepad values instead of writing to io.NavInputs[] fields.
+ - for more reference:
+ - read 1.87 and 1.88 part of this section or read Changelog for 1.87 and 1.88.
+ - read https://github.com/ocornut/imgui/issues/4921
+ - if you have trouble updating a very old codebase using legacy backend-specific key codes: consider updating to 1.91.4 first, then #define IMGUI_DISABLE_OBSOLETE_KEYIO, then update to latest.
+ - obsoleted ImGuiKey_COUNT (it is unusually error-prone/misleading since valid keys don't start at 0). probably use ImGuiKey_NamedKey_BEGIN/ImGuiKey_NamedKey_END?
+ - fonts: removed const qualifiers from most font functions in prevision for upcoming font improvements.
- 2024/10/18 (1.91.4) - renamed ImGuiCol_NavHighlight to ImGuiCol_NavCursor (for consistency with newly exposed and reworked features). Kept inline redirection enum (will obsolete).
- 2024/10/14 (1.91.4) - moved ImGuiConfigFlags_NavEnableSetMousePos to standalone io.ConfigNavMoveSetMousePos bool.
moved ImGuiConfigFlags_NavNoCaptureKeyboard to standalone io.ConfigNavCaptureKeyboard bool (note the inverted value!).
@@ -448,12 +537,12 @@ CODE
in doubt it is almost always better to do an intermediate intptr_t cast, since it allows casting any pointer/integer type without warning:
- May warn: ImGui::Image((void*)MyTextureData, ...);
- May warn: ImGui::Image((void*)(intptr_t)MyTextureData, ...);
- - Won't warn: ImGui::Image((ImTextureID)(intptr_t)MyTextureData), ...);
+ - Won't warn: ImGui::Image((ImTextureID)(intptr_t)MyTextureData, ...);
- note that you can always define ImTextureID to be your own high-level structures (with dedicated constructors) if you like.
- 2024/10/03 (1.91.3) - drags: treat v_min==v_max as a valid clamping range when != 0.0f. Zero is a still special value due to legacy reasons, unless using ImGuiSliderFlags_ClampZeroRange. (#7968, #3361, #76)
- drags: extended behavior of ImGuiSliderFlags_AlwaysClamp to include _ClampZeroRange. It considers v_min==v_max==0.0f as a valid clamping range (aka edits not allowed).
although unlikely, it you wish to only clamp on text input but want v_min==v_max==0.0f to mean unclamped drags, you can use _ClampOnInput instead of _AlwaysClamp. (#7968, #3361, #76)
- - 2024/09/10 (1.91.2) - internals: using multiple overlayed ButtonBehavior() with same ID will now have io.ConfigDebugHighlightIdConflicts=true feature emit a warning. (#8030)
+ - 2024/09/10 (1.91.2) - internals: using multiple overlaid ButtonBehavior() with same ID will now have io.ConfigDebugHighlightIdConflicts=true feature emit a warning. (#8030)
it was one of the rare case where using same ID is legal. workarounds: (1) use single ButtonBehavior() call with multiple _MouseButton flags, or (2) surround the calls with PushItemFlag(ImGuiItemFlags_AllowDuplicateId, true); ... PopItemFlag()
- 2024/08/23 (1.91.1) - renamed ImGuiChildFlags_Border to ImGuiChildFlags_Borders for consistency. kept inline redirection flag.
- 2024/08/22 (1.91.1) - moved some functions from ImGuiIO to ImGuiPlatformIO structure:
@@ -635,7 +724,7 @@ CODE
- 2022/04/05 (1.88) - inputs: renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). This was never used in public API functions but technically present in imgui.h and ImGuiIO.
- 2022/01/20 (1.87) - inputs: reworded gamepad IO.
- Backend writing to io.NavInputs[] -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
- - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputing text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
+ - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputting text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
- 2022/01/17 (1.87) - inputs: reworked mouse IO.
- Backend writing to io.MousePos -> backend should call io.AddMousePosEvent()
- Backend writing to io.MouseDown[] -> backend should call io.AddMouseButtonEvent()
@@ -643,10 +732,10 @@ CODE
- Backend writing to io.MouseHoveredViewport -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
read https://github.com/ocornut/imgui/issues/4921 for details.
- - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unnecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.
+ - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(), ImGui::IsKeyDown(). Removed GetKeyIndex(), now unnecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.
- IsKeyPressed(MY_NATIVE_KEY_XXX) -> use IsKeyPressed(ImGuiKey_XXX)
- IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX)
- - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes).
+ - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to still function with legacy key codes).
- Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiMod_XXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiMod_XXX values.*
- one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert.
- inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper.
@@ -738,7 +827,7 @@ CODE
- ShowTestWindow() -> use ShowDemoWindow()
- IsRootWindowFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
- IsRootWindowOrAnyChildFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
- - SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
+ - SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f))
- GetItemsLineHeightWithSpacing() -> use GetFrameHeightWithSpacing()
- ImGuiCol_ChildWindowBg -> use ImGuiCol_ChildBg
- ImGuiStyleVar_ChildWindowRounding -> use ImGuiStyleVar_ChildRounding
@@ -855,7 +944,7 @@ CODE
- renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
- renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
- 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
- - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
+ - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicitly to fix.
- 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
- 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
- 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
@@ -1092,7 +1181,7 @@ CODE
#else
#include <windows.h>
#endif
-#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP || WINAPI_FAMILY == WINAPI_FAMILY_GAMES)
+#if defined(WINAPI_FAMILY) && ((defined(WINAPI_FAMILY_APP) && WINAPI_FAMILY == WINAPI_FAMILY_APP) || (defined(WINAPI_FAMILY_GAMES) && WINAPI_FAMILY == WINAPI_FAMILY_GAMES))
// The UWP and GDK Win32 API subsets don't support clipboard nor IME functions
#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
@@ -1125,41 +1214,45 @@ CODE
#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" // warning: format specifies type 'int' but the argument has type 'unsigned int'
#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 "-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 "-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
#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access
+#pragma clang diagnostic ignored "-Wnontrivial-memaccess" // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
+#pragma clang diagnostic ignored "-Wswitch-default" // warning: 'switch' missing 'default' label
#elif defined(__GNUC__)
// We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
-#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
-#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
-#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
-#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
-#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 "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
-#pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
-#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 "-Wunused-function" // warning: 'xxxx' defined but not used
+#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
+#pragma GCC diagnostic ignored "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe
+#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'int'/'void*', but argument X has type 'unsigned int'/'ImGuiWindow*'
+#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
+#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
+#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
+#pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
+#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 "-Wcast-qual" // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers
#endif
// Debug options
#define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Hold CTRL to display for all candidates. CTRL+Arrow to change last direction.
#define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window
+// Default font size if unspecified in both style.FontSizeBase and AddFontXXX() calls.
+static const float FONT_DEFAULT_SIZE = 20.0f;
+
// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in
static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear
-
static const float NAV_ACTIVATE_HIGHLIGHT_TIMER = 0.10f; // Time to highlight an item activated by a shortcut.
-
-// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
-static const float WINDOWS_HOVER_PADDING = 4.0f; // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. 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 = 0.70f; // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
@@ -1199,9 +1292,14 @@ namespace ImGui
// Item
static void ItemHandleShortcut(ImGuiID id);
+// Window Focus
+static int FindWindowFocusIndex(ImGuiWindow* window);
+static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags);
+
// Navigation
static void NavUpdate();
static void NavUpdateWindowing();
+static void NavUpdateWindowingApplyFocus(ImGuiWindow* window);
static void NavUpdateWindowingOverlay();
static void NavUpdateCancelRequest();
static void NavUpdateCreateMoveRequest();
@@ -1210,7 +1308,7 @@ static float NavUpdatePageUpPageDown();
static inline void NavUpdateAnyRequestFlag();
static void NavUpdateCreateWrappingRequest();
static void NavEndFrame();
-static bool NavScoreItem(ImGuiNavItemData* result);
+static bool NavScoreItem(ImGuiNavItemData* result, const ImRect& nav_bb);
static void NavApplyItemToResult(ImGuiNavItemData* result);
static void NavProcessItem();
static void NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags);
@@ -1219,14 +1317,15 @@ static ImVec2 NavCalcPreferredRefPos();
static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window);
static void NavRestoreLayer(ImGuiNavLayer layer);
-static int FindWindowFocusIndex(ImGuiWindow* window);
// Error Checking and Debug Tools
static void ErrorCheckNewFrameSanityChecks();
static void ErrorCheckEndFrameSanityChecks();
+#ifndef IMGUI_DISABLE_DEBUG_TOOLS
static void UpdateDebugToolItemPicker();
static void UpdateDebugToolStackQueries();
static void UpdateDebugToolFlashStyleColor();
+#endif
// Inputs
static void UpdateKeyboardInputs();
@@ -1235,6 +1334,10 @@ static void UpdateMouseWheel();
static void UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
// Misc
+static void UpdateFontsNewFrame();
+static void UpdateFontsEndFrame();
+static void UpdateTexturesNewFrame();
+static void UpdateTexturesEndFrame();
static void UpdateSettings();
static int UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
static void RenderWindowOuterBorders(ImGuiWindow* window);
@@ -1243,6 +1346,7 @@ static void RenderWindowTitleBarContents(ImGuiWindow* window, const
static void RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
static void RenderDimmedBackgrounds();
static void SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect);
+static void SetLastItemDataForChildWindowItem(ImGuiWindow* window, const ImRect& rect);
// 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.
@@ -1309,11 +1413,16 @@ static void* GImAllocatorUserData = NULL;
ImGuiStyle::ImGuiStyle()
{
+ FontSizeBase = 0.0f; // Will default to io.Fonts->Fonts[0] on first frame.
+ FontScaleMain = 1.0f; // Main scale factor. May be set by application once, or exposed to end-user.
+ FontScaleDpi = 1.0f; // Additional scale factor from viewport/monitor contents scale. When io.ConfigDpiScaleFonts is enabled, this is automatically overwritten when changing monitor DPI.
+
Alpha = 1.0f; // Global alpha applies to everything in Dear ImGui.
DisabledAlpha = 0.60f; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
WindowPadding = ImVec2(8,8); // Padding within a window
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.
+ WindowBorderHoverPadding = 4.0f; // Hit-testing extent outside/inside resizing border. Also extend determination of hovered window. Generally meaningfully larger than WindowBorderSize to make it easy to reach borders.
WindowMinSize = ImVec2(32,32); // Minimum window size
WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
WindowMenuButtonPosition = ImGuiDir_Left; // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
@@ -1332,16 +1441,24 @@ ImGuiStyle::ImGuiStyle()
ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
ScrollbarSize = 14.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
+ ScrollbarPadding = 2.0f; // Padding of scrollbar grab within its frame (same for both axises)
GrabMinSize = 12.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.
+ ImageBorderSize = 0.0f; // Thickness of border around tabs.
+ TabRounding = 5.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 appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
+ TabMinWidthBase = 1.0f; // Minimum tab width, to make tabs larger than their contents. TabBar buttons are not affected.
+ TabMinWidthShrink = 80.0f; // Minimum tab width after shrinking, when using ImGuiTabBarFlags_FittingPolicyMixed policy.
+ TabCloseButtonMinWidthSelected = -1.0f; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width.
+ TabCloseButtonMinWidthUnselected = 0.0f; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width. FLT_MAX: never show close button when unselected.
TabBarBorderSize = 1.0f; // Thickness of tab-bar separator, which takes on the tab active color to denote focus.
- TabBarOverlineSize = 2.0f; // Thickness of tab-bar overline, which highlights the selected tab-bar.
+ TabBarOverlineSize = 1.0f; // Thickness of tab-bar overline, which highlights the selected tab-bar.
TableAngledHeadersAngle = 35.0f * (IM_PI / 180.0f); // Angle of angled headers (supported values range from -50 degrees to +50 degrees).
TableAngledHeadersTextAlign = ImVec2(0.5f,0.0f);// Alignment of angled headers within the cell
+ TreeLinesFlags = ImGuiTreeNodeFlags_DrawLinesNone;
+ TreeLinesSize = 1.0f; // Thickness of outlines when using ImGuiTreeNodeFlags_DrawLines.
+ TreeLinesRounding = 0.0f; // Radius of lines connecting child nodes to the vertical line.
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. 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.
@@ -1350,6 +1467,7 @@ ImGuiStyle::ImGuiStyle()
SeparatorTextPadding = ImVec2(20.0f,3.f);// Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y.
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.
+ DockingNodeHasCloseButton = true; // Docking nodes have their own CloseButton() to close all docked windows.
DockingSeparatorSize = 2.0f; // Thickness of resizing border between docked windows
MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
@@ -1365,17 +1483,24 @@ ImGuiStyle::ImGuiStyle()
HoverFlagsForTooltipMouse = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse.
HoverFlagsForTooltipNav = ImGuiHoveredFlags_NoSharedDelay | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad.
+ // [Internal]
+ _MainScale = 1.0f;
+ _NextFrameFontSizeBase = 0.0f;
+
// Default theme
ImGui::StyleColorsDark(this);
}
-// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
+
+// Scale all spacing/padding/thickness values. Do not scale fonts.
// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
void ImGuiStyle::ScaleAllSizes(float scale_factor)
{
+ _MainScale *= scale_factor;
WindowPadding = ImTrunc(WindowPadding * scale_factor);
WindowRounding = ImTrunc(WindowRounding * scale_factor);
WindowMinSize = ImTrunc(WindowMinSize * scale_factor);
+ WindowBorderHoverPadding = ImTrunc(WindowBorderHoverPadding * scale_factor);
ChildRounding = ImTrunc(ChildRounding * scale_factor);
PopupRounding = ImTrunc(PopupRounding * scale_factor);
FramePadding = ImTrunc(FramePadding * scale_factor);
@@ -1388,12 +1513,18 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor)
ColumnsMinSpacing = ImTrunc(ColumnsMinSpacing * scale_factor);
ScrollbarSize = ImTrunc(ScrollbarSize * scale_factor);
ScrollbarRounding = ImTrunc(ScrollbarRounding * scale_factor);
+ ScrollbarPadding = ImTrunc(ScrollbarPadding * scale_factor);
GrabMinSize = ImTrunc(GrabMinSize * scale_factor);
GrabRounding = ImTrunc(GrabRounding * scale_factor);
LogSliderDeadzone = ImTrunc(LogSliderDeadzone * scale_factor);
+ ImageBorderSize = ImTrunc(ImageBorderSize * scale_factor);
TabRounding = ImTrunc(TabRounding * scale_factor);
- TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImTrunc(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
+ TabMinWidthBase = ImTrunc(TabMinWidthBase * scale_factor);
+ TabMinWidthShrink = ImTrunc(TabMinWidthShrink * scale_factor);
+ TabCloseButtonMinWidthSelected = (TabCloseButtonMinWidthSelected > 0.0f && TabCloseButtonMinWidthSelected != FLT_MAX) ? ImTrunc(TabCloseButtonMinWidthSelected * scale_factor) : TabCloseButtonMinWidthSelected;
+ TabCloseButtonMinWidthUnselected = (TabCloseButtonMinWidthUnselected > 0.0f && TabCloseButtonMinWidthUnselected != FLT_MAX) ? ImTrunc(TabCloseButtonMinWidthUnselected * scale_factor) : TabCloseButtonMinWidthUnselected;
TabBarOverlineSize = ImTrunc(TabBarOverlineSize * scale_factor);
+ TreeLinesRounding = ImTrunc(TreeLinesRounding * scale_factor);
SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor);
DockingSeparatorSize = ImTrunc(DockingSeparatorSize * scale_factor);
DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor);
@@ -1415,16 +1546,14 @@ ImGuiIO::ImGuiIO()
IniSavingRate = 5.0f;
IniFilename = "imgui.ini"; // Important: "imgui.ini" is relative to current working dir, most apps will want to lock this to an absolute path (e.g. same path as executables).
LogFilename = "imgui_log.txt";
-#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
- for (int i = 0; i < ImGuiKey_COUNT; i++)
- KeyMap[i] = -1;
-#endif
UserData = NULL;
Fonts = NULL;
- FontGlobalScale = 1.0f;
FontDefault = NULL;
FontAllowUserScaling = false;
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ FontGlobalScale = 1.0f; // Use style.FontScaleMain instead!
+#endif
DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
// Keyboard/Gamepad Navigation options
@@ -1447,6 +1576,7 @@ ImGuiIO::ImGuiIO()
ConfigViewportsNoTaskBarIcon = false;
ConfigViewportsNoDecoration = true;
ConfigViewportsNoDefaultParent = false;
+ ConfigViewportPlatformFocusSetsImGuiFocus = true;
// Miscellaneous options
MouseDrawCursor = false;
@@ -1461,10 +1591,12 @@ ImGuiIO::ImGuiIO()
ConfigDragClickToInputText = false;
ConfigWindowsResizeFromEdges = true;
ConfigWindowsMoveFromTitleBarOnly = false;
+ ConfigWindowsCopyContentsWithCtrlC = false;
ConfigScrollbarScrollByPage = true;
ConfigMemoryCompactTimer = 60.0f;
ConfigDebugIsDebuggerPresent = false;
ConfigDebugHighlightIdConflicts = true;
+ ConfigDebugHighlightIdConflictsShowItemPicker = true;
ConfigDebugBeginReturnValueOnce = false;
ConfigDebugBeginReturnValueLoop = false;
@@ -1492,8 +1624,6 @@ ImGuiIO::ImGuiIO()
for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
AppAcceptingEvents = true;
- BackendUsingLegacyKeyArrays = (ImS8)-1;
- BackendUsingLegacyNavInputArray = true; // assume using legacy array until proven wrong
}
// Pass in translated ASCII characters for text input.
@@ -1574,16 +1704,15 @@ void ImGuiIO::ClearEventsQueue()
// Clear current keyboard/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons.
void ImGuiIO::ClearInputKeys()
{
-#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
- memset(KeysDown, 0, sizeof(KeysDown));
-#endif
- for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)
+ ImGuiContext& g = *Ctx;
+ for (int key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key++)
{
- if (ImGui::IsMouseKey((ImGuiKey)(n + ImGuiKey_KeysData_OFFSET)))
+ if (ImGui::IsMouseKey((ImGuiKey)key))
continue;
- KeysData[n].Down = false;
- KeysData[n].DownDuration = -1.0f;
- KeysData[n].DownDurationPrev = -1.0f;
+ ImGuiKeyData* key_data = &g.IO.KeysData[key - ImGuiKey_NamedKey_BEGIN];
+ key_data->Down = false;
+ key_data->DownDuration = -1.0f;
+ key_data->DownDurationPrev = -1.0f;
}
KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
KeyMods = ImGuiMod_None;
@@ -1594,7 +1723,7 @@ void ImGuiIO::ClearInputMouse()
{
for (ImGuiKey key = ImGuiKey_Mouse_BEGIN; key < ImGuiKey_Mouse_END; key = (ImGuiKey)(key + 1))
{
- ImGuiKeyData* key_data = &KeysData[key - ImGuiKey_KeysData_OFFSET];
+ ImGuiKeyData* key_data = &KeysData[key - ImGuiKey_NamedKey_BEGIN];
key_data->Down = false;
key_data->DownDuration = -1.0f;
key_data->DownDurationPrev = -1.0f;
@@ -1661,17 +1790,6 @@ void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
else if (key == ImGuiKey_RightCtrl) { key = ImGuiKey_RightSuper; }
}
- // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data.
-#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
- IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
- if (BackendUsingLegacyKeyArrays == -1)
- for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
- IM_ASSERT(KeyMap[n] == -1 && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
- BackendUsingLegacyKeyArrays = 0;
-#endif
- if (ImGui::IsGamepadKey(key))
- BackendUsingLegacyNavInputArray = false;
-
// Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key);
const ImGuiKeyData* key_data = ImGui::GetKeyData(&g, key);
@@ -1707,20 +1825,10 @@ void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native
return;
IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
- IM_UNUSED(native_keycode); // Yet unused
- IM_UNUSED(native_scancode); // Yet unused
-
- // Build native->imgui map so old user code can still call key functions with native 0..511 values.
-#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
- const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode;
- if (!ImGui::IsLegacyKey((ImGuiKey)legacy_key))
- return;
- KeyMap[legacy_key] = key;
- KeyMap[key] = legacy_key;
-#else
- IM_UNUSED(key);
- IM_UNUSED(native_legacy_index);
-#endif
+ IM_UNUSED(key); // Yet unused
+ IM_UNUSED(native_keycode); // Yet unused
+ IM_UNUSED(native_scancode); // Yet unused
+ IM_UNUSED(native_legacy_index); // Yet unused
}
// Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen.
@@ -1767,7 +1875,7 @@ void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
// On MacOS X: Convert Ctrl(Super)+Left click into Right-click: handle held button.
if (ConfigMacOSXBehaviors && mouse_button == 0 && MouseCtrlLeftAsRightClick)
{
- // Order of both statements matterns: this event will still release mouse button 1
+ // Order of both statements matters: this event will still release mouse button 1
mouse_button = 1;
if (!down)
MouseCtrlLeftAsRightClick = false;
@@ -2023,21 +2131,27 @@ void ImStrncpy(char* dst, const char* src, size_t count)
if (count < 1)
return;
if (count > 1)
- strncpy(dst, src, count - 1);
+ strncpy(dst, src, count - 1); // FIXME-OPT: strncpy not only doesn't guarantee 0-termination, it also always writes the whole array
dst[count - 1] = 0;
}
char* ImStrdup(const char* str)
{
- size_t len = strlen(str);
+ size_t len = ImStrlen(str);
void* buf = IM_ALLOC(len + 1);
return (char*)memcpy(buf, (const void*)str, len + 1);
}
+void* ImMemdup(const void* src, size_t size)
+{
+ void* dst = IM_ALLOC(size);
+ return memcpy(dst, src, size);
+}
+
char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
{
- size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
- size_t src_size = strlen(src) + 1;
+ size_t dst_buf_size = p_dst_size ? *p_dst_size : ImStrlen(dst) + 1;
+ size_t src_size = ImStrlen(src) + 1;
if (dst_buf_size < src_size)
{
IM_FREE(dst);
@@ -2050,7 +2164,7 @@ char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
const char* ImStrchrRange(const char* str, const char* str_end, char c)
{
- const char* p = (const char*)memchr(str, (int)c, str_end - str);
+ const char* p = (const char*)ImMemchr(str, (int)c, str_end - str);
return p;
}
@@ -2065,12 +2179,13 @@ int ImStrlenW(const ImWchar* str)
// Find end-of-line. Return pointer will point to either first \n, either str_end.
const char* ImStreolRange(const char* str, const char* str_end)
{
- const char* p = (const char*)memchr(str, '\n', str_end - str);
+ const char* p = (const char*)ImMemchr(str, '\n', str_end - str);
return p ? p : str_end;
}
const char* ImStrbol(const char* buf_mid_line, const char* buf_begin) // find beginning-of-line
{
+ IM_ASSERT_PARANOID(buf_mid_line >= buf_begin && buf_mid_line <= buf_begin + ImStrlen(buf_begin));
while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
buf_mid_line--;
return buf_mid_line;
@@ -2079,7 +2194,7 @@ const char* ImStrbol(const char* buf_mid_line, const char* buf_begin) // find be
const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
{
if (!needle_end)
- needle_end = needle + strlen(needle);
+ needle_end = needle + ImStrlen(needle);
const char un0 = (char)ImToUpper(*needle);
while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
@@ -2200,7 +2315,7 @@ void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end,
if (buf == NULL)
buf = "(null)";
*out_buf = buf;
- if (out_buf_end) { *out_buf_end = buf + strlen(buf); }
+ if (out_buf_end) { *out_buf_end = buf + ImStrlen(buf); }
}
else if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '*' && fmt[3] == 's' && fmt[4] == 0)
{
@@ -2222,11 +2337,14 @@ void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end,
}
}
+#ifndef IMGUI_ENABLE_SSE4_2_CRC
// CRC32 needs a 1KB lookup table (not cache friendly)
// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
static const ImU32 GCrc32LookupTable[256] =
{
+#ifdef IMGUI_USE_LEGACY_CRC32_ADLER
+ // Legacy CRC32-adler table used pre 1.91.6 (before 2024/11/27). Only use if you cannot afford invalidating old .ini data.
0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
@@ -2243,7 +2361,27 @@ static const ImU32 GCrc32LookupTable[256] =
0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
+#else
+ // CRC32c table compatible with SSE 4.2 instructions
+ 0x00000000,0xF26B8303,0xE13B70F7,0x1350F3F4,0xC79A971F,0x35F1141C,0x26A1E7E8,0xD4CA64EB,0x8AD958CF,0x78B2DBCC,0x6BE22838,0x9989AB3B,0x4D43CFD0,0xBF284CD3,0xAC78BF27,0x5E133C24,
+ 0x105EC76F,0xE235446C,0xF165B798,0x030E349B,0xD7C45070,0x25AFD373,0x36FF2087,0xC494A384,0x9A879FA0,0x68EC1CA3,0x7BBCEF57,0x89D76C54,0x5D1D08BF,0xAF768BBC,0xBC267848,0x4E4DFB4B,
+ 0x20BD8EDE,0xD2D60DDD,0xC186FE29,0x33ED7D2A,0xE72719C1,0x154C9AC2,0x061C6936,0xF477EA35,0xAA64D611,0x580F5512,0x4B5FA6E6,0xB93425E5,0x6DFE410E,0x9F95C20D,0x8CC531F9,0x7EAEB2FA,
+ 0x30E349B1,0xC288CAB2,0xD1D83946,0x23B3BA45,0xF779DEAE,0x05125DAD,0x1642AE59,0xE4292D5A,0xBA3A117E,0x4851927D,0x5B016189,0xA96AE28A,0x7DA08661,0x8FCB0562,0x9C9BF696,0x6EF07595,
+ 0x417B1DBC,0xB3109EBF,0xA0406D4B,0x522BEE48,0x86E18AA3,0x748A09A0,0x67DAFA54,0x95B17957,0xCBA24573,0x39C9C670,0x2A993584,0xD8F2B687,0x0C38D26C,0xFE53516F,0xED03A29B,0x1F682198,
+ 0x5125DAD3,0xA34E59D0,0xB01EAA24,0x42752927,0x96BF4DCC,0x64D4CECF,0x77843D3B,0x85EFBE38,0xDBFC821C,0x2997011F,0x3AC7F2EB,0xC8AC71E8,0x1C661503,0xEE0D9600,0xFD5D65F4,0x0F36E6F7,
+ 0x61C69362,0x93AD1061,0x80FDE395,0x72966096,0xA65C047D,0x5437877E,0x4767748A,0xB50CF789,0xEB1FCBAD,0x197448AE,0x0A24BB5A,0xF84F3859,0x2C855CB2,0xDEEEDFB1,0xCDBE2C45,0x3FD5AF46,
+ 0x7198540D,0x83F3D70E,0x90A324FA,0x62C8A7F9,0xB602C312,0x44694011,0x5739B3E5,0xA55230E6,0xFB410CC2,0x092A8FC1,0x1A7A7C35,0xE811FF36,0x3CDB9BDD,0xCEB018DE,0xDDE0EB2A,0x2F8B6829,
+ 0x82F63B78,0x709DB87B,0x63CD4B8F,0x91A6C88C,0x456CAC67,0xB7072F64,0xA457DC90,0x563C5F93,0x082F63B7,0xFA44E0B4,0xE9141340,0x1B7F9043,0xCFB5F4A8,0x3DDE77AB,0x2E8E845F,0xDCE5075C,
+ 0x92A8FC17,0x60C37F14,0x73938CE0,0x81F80FE3,0x55326B08,0xA759E80B,0xB4091BFF,0x466298FC,0x1871A4D8,0xEA1A27DB,0xF94AD42F,0x0B21572C,0xDFEB33C7,0x2D80B0C4,0x3ED04330,0xCCBBC033,
+ 0xA24BB5A6,0x502036A5,0x4370C551,0xB11B4652,0x65D122B9,0x97BAA1BA,0x84EA524E,0x7681D14D,0x2892ED69,0xDAF96E6A,0xC9A99D9E,0x3BC21E9D,0xEF087A76,0x1D63F975,0x0E330A81,0xFC588982,
+ 0xB21572C9,0x407EF1CA,0x532E023E,0xA145813D,0x758FE5D6,0x87E466D5,0x94B49521,0x66DF1622,0x38CC2A06,0xCAA7A905,0xD9F75AF1,0x2B9CD9F2,0xFF56BD19,0x0D3D3E1A,0x1E6DCDEE,0xEC064EED,
+ 0xC38D26C4,0x31E6A5C7,0x22B65633,0xD0DDD530,0x0417B1DB,0xF67C32D8,0xE52CC12C,0x1747422F,0x49547E0B,0xBB3FFD08,0xA86F0EFC,0x5A048DFF,0x8ECEE914,0x7CA56A17,0x6FF599E3,0x9D9E1AE0,
+ 0xD3D3E1AB,0x21B862A8,0x32E8915C,0xC083125F,0x144976B4,0xE622F5B7,0xF5720643,0x07198540,0x590AB964,0xAB613A67,0xB831C993,0x4A5A4A90,0x9E902E7B,0x6CFBAD78,0x7FAB5E8C,0x8DC0DD8F,
+ 0xE330A81A,0x115B2B19,0x020BD8ED,0xF0605BEE,0x24AA3F05,0xD6C1BC06,0xC5914FF2,0x37FACCF1,0x69E9F0D5,0x9B8273D6,0x88D28022,0x7AB90321,0xAE7367CA,0x5C18E4C9,0x4F48173D,0xBD23943E,
+ 0xF36E6F75,0x0105EC76,0x12551F82,0xE03E9C81,0x34F4F86A,0xC69F7B69,0xD5CF889D,0x27A40B9E,0x79B737BA,0x8BDCB4B9,0x988C474D,0x6AE7C44E,0xBE2DA0A5,0x4C4623A6,0x5F16D052,0xAD7D5351
+#endif
};
+#endif
// Known size hash
// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
@@ -2252,10 +2390,22 @@ ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
{
ImU32 crc = ~seed;
const unsigned char* data = (const unsigned char*)data_p;
+ const unsigned char *data_end = (const unsigned char*)data_p + data_size;
+#ifndef IMGUI_ENABLE_SSE4_2_CRC
const ImU32* crc32_lut = GCrc32LookupTable;
- while (data_size-- != 0)
+ while (data < data_end)
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
return ~crc;
+#else
+ while (data + 4 <= data_end)
+ {
+ crc = _mm_crc32_u32(crc, *(ImU32*)data);
+ data += 4;
+ }
+ while (data < data_end)
+ crc = _mm_crc32_u8(crc, *data++);
+ return ~crc;
+#endif
}
// Zero-terminated string hash, with support for ### to reset back to seed value
@@ -2269,7 +2419,9 @@ ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
seed = ~seed;
ImU32 crc = seed;
const unsigned char* data = (const unsigned char*)data_p;
+#ifndef IMGUI_ENABLE_SSE4_2_CRC
const ImU32* crc32_lut = GCrc32LookupTable;
+#endif
if (data_size != 0)
{
while (data_size-- != 0)
@@ -2277,7 +2429,11 @@ ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
unsigned char c = *data++;
if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
crc = seed;
+#ifndef IMGUI_ENABLE_SSE4_2_CRC
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
+#else
+ crc = _mm_crc32_u8(crc, c);
+#endif
}
}
else
@@ -2286,12 +2442,27 @@ ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
{
if (c == '#' && data[0] == '#' && data[1] == '#')
crc = seed;
+#ifndef IMGUI_ENABLE_SSE4_2_CRC
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
+#else
+ crc = _mm_crc32_u8(crc, c);
+#endif
}
}
return ~crc;
}
+// Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
+// FIXME-OPT: This is not designed to be optimal. Use with care.
+const char* ImHashSkipUncontributingPrefix(const char* label)
+{
+ const char* result = label;
+ while (unsigned char c = *label++)
+ if (c == '#' && label[0] == '#' && label[1] == '#')
+ result = label - 1;
+ return result;
+}
+
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPERS/UTILITIES (File functions)
//-----------------------------------------------------------------------------
@@ -2301,7 +2472,7 @@ ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
ImFileHandle ImFileOpen(const char* filename, const char* mode)
{
-#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
+#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && (defined(__MINGW32__) || (!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);
@@ -2413,7 +2584,7 @@ int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char*
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 |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8; // out of range we can store in ImWchar (FIXME: May evolve)
e |= (s[1] & 0xc0) >> 2;
e |= (s[2] & 0xc0) >> 4;
e |= (s[3] ) >> 6;
@@ -2497,11 +2668,11 @@ static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int
return 0;
}
-const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
+int ImTextCharToUtf8(char out_buf[5], unsigned int c)
{
int count = ImTextCharToUtf8_inline(out_buf, 5, c);
out_buf[count] = 0;
- return out_buf;
+ return count;
}
// Not optimal but we very rarely use this function.
@@ -2564,11 +2735,11 @@ const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const cha
int ImTextCountLines(const char* in_text, const char* in_text_end)
{
if (in_text_end == NULL)
- in_text_end = in_text + strlen(in_text); // FIXME-OPT: Not optimal approach, discourage use for now.
+ in_text_end = in_text + ImStrlen(in_text); // FIXME-OPT: Not optimal approach, discourage use for now.
int count = 0;
while (in_text < in_text_end)
{
- const char* line_end = (const char*)memchr(in_text, '\n', in_text_end - in_text);
+ const char* line_end = (const char*)ImMemchr(in_text, '\n', in_text_end - in_text);
in_text = line_end ? line_end + 1 : in_text_end;
count++;
}
@@ -2849,7 +3020,7 @@ void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRa
void ImGuiTextFilter::Build()
{
Filters.resize(0);
- ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
+ ImGuiTextRange input_range(InputBuf, InputBuf + ImStrlen(InputBuf));
input_range.split(',', &Filters);
CountGrep = 0;
@@ -2917,7 +3088,7 @@ char ImGuiTextBuffer::EmptyString[1] = { 0 };
void ImGuiTextBuffer::append(const char* str, const char* str_end)
{
- int len = str_end ? (int)(str_end - str) : (int)strlen(str);
+ int len = str_end ? (int)(str_end - str) : (int)ImStrlen(str);
// Add zero-terminator the first time
const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
@@ -2968,19 +3139,21 @@ void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
va_end(args_copy);
}
+IM_MSVC_RUNTIME_CHECKS_OFF
void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
{
IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
if (old_size == new_size)
return;
if (EndOffset == 0 || base[EndOffset - 1] == '\n')
- LineOffsets.push_back(EndOffset);
+ Offsets.push_back(EndOffset);
const char* base_end = base + new_size;
- for (const char* p = base + old_size; (p = (const char*)memchr(p, '\n', base_end - p)) != 0; )
+ for (const char* p = base + old_size; (p = (const char*)ImMemchr(p, '\n', base_end - p)) != 0; )
if (++p < base_end) // Don't push a trailing offset on last \n
- LineOffsets.push_back((int)(intptr_t)(p - base));
+ Offsets.push_back((int)(intptr_t)(p - base));
EndOffset = ImMax(EndOffset, new_size);
}
+IM_MSVC_RUNTIME_CHECKS_RESTORE
//-----------------------------------------------------------------------------
// [SECTION] ImGuiListClipper
@@ -3018,7 +3191,7 @@ static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>&
}
}
-static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
+static void ImGuiListClipper_SeekCursorAndSetupPrevLine(ImGuiListClipper* clipper, 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.
@@ -3036,10 +3209,13 @@ static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_
{
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;
+ if (row_increase > 0 && (clipper->Flags & ImGuiListClipperFlags_NoSetTableRowCounters) == 0) // If your clipper item height is != from actual table row height, consider using ImGuiListClipperFlags_NoSetTableRowCounters. See #8886.
+ {
+ table->CurrentRow += row_increase;
+ table->RowBgColorCounter += row_increase;
+ }
+ table->RowPosY2 = window->DC.CursorPos.y;
}
}
@@ -3122,7 +3298,7 @@ void ImGuiListClipper::SeekCursorForItem(int item_n)
// - StartPosY starts from ItemsFrozen, by adding SeekOffsetY we generally cancel that out (SeekOffsetY == LossynessOffset - ItemsFrozen * ItemsHeight).
// - The reason we store SeekOffsetY instead of inferring it, is because we want to allow user to perform Seek after the last step, where ImGuiListClipperData is already done.
float pos_y = (float)((double)StartPosY + StartSeekOffsetY + (double)item_n * ItemsHeight);
- ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, ItemsHeight);
+ ImGuiListClipper_SeekCursorAndSetupPrevLine(this, pos_y, ItemsHeight);
}
static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
@@ -3175,10 +3351,17 @@ static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
if (table)
IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
- clipper->ItemsHeight = (window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
- bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);
+ bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision((float)clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);
if (affected_by_floating_point_precision)
+ {
+ // Mitigation/hack for very large range: assume last time height constitute line height.
clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
+ window->DC.CursorPos.y = (float)(clipper->StartPosY + clipper->ItemsHeight);
+ }
+ else
+ {
+ clipper->ItemsHeight = (float)(window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
+ }
if (clipper->ItemsHeight == 0.0f && clipper->ItemsCount == INT_MAX) // Accept that no item have been submitted if in indeterminate mode.
return false;
IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
@@ -3202,7 +3385,10 @@ static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
// Add range selected to be included for navigation
const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
if (is_nav_request)
+ {
+ data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringRect.Min.y, g.NavScoringRect.Max.y, 0, 0));
data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0));
+ }
if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && g.NavTabbingDir == -1)
data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount));
@@ -3211,7 +3397,6 @@ static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0));
- // Add visible range
float min_y = window->ClipRect.Min.y;
float max_y = window->ClipRect.Max.y;
@@ -3230,6 +3415,7 @@ static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
data->Ranges.push_back(ImGuiListClipperRange::FromPositions(bs->UnclipRect.Min.y, bs->UnclipRect.Max.y, 0, 0));
}
+ // Add main visible range
const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
data->Ranges.push_back(ImGuiListClipperRange::FromPositions(min_y, max_y, off_min, off_max));
@@ -3256,11 +3442,11 @@ static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
{
clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted);
clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount);
- if (clipper->DisplayStart > already_submitted) //-V1051
- clipper->SeekCursorForItem(clipper->DisplayStart);
data->StepNo++;
- if (clipper->DisplayStart == clipper->DisplayEnd && data->StepNo < data->Ranges.Size)
+ if (clipper->DisplayStart >= clipper->DisplayEnd)
continue;
+ if (clipper->DisplayStart > already_submitted)
+ clipper->SeekCursorForItem(clipper->DisplayStart);
return true;
}
@@ -3277,7 +3463,7 @@ bool ImGuiListClipper::Step()
ImGuiContext& g = *Ctx;
bool need_items_height = (ItemsHeight <= 0.0f);
bool ret = ImGuiListClipper_StepInternal(this);
- if (ret && (DisplayStart == DisplayEnd))
+ if (ret && (DisplayStart >= DisplayEnd))
ret = false;
if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
@@ -3295,6 +3481,13 @@ bool ImGuiListClipper::Step()
return ret;
}
+// Generic helper, equivalent to old ImGui::CalcListClipping() but statelesss
+void ImGui::CalcClipRectVisibleItemsY(const ImRect& clip_rect, const ImVec2& pos, float items_height, int* out_visible_start, int* out_visible_end)
+{
+ *out_visible_start = ImMax((int)((clip_rect.Min.y - pos.y) / items_height), 0);
+ *out_visible_end = ImMax((int)ImCeil((clip_rect.Max.y - pos.y) / items_height), *out_visible_start);
+}
+
//-----------------------------------------------------------------------------
// [SECTION] STYLING
//-----------------------------------------------------------------------------
@@ -3383,56 +3576,62 @@ static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] =
ImGuiCol_Text, ImGuiCol_TabHovered, ImGuiCol_Tab, ImGuiCol_TabSelected, ImGuiCol_TabSelectedOverline, ImGuiCol_TabDimmed, ImGuiCol_TabDimmedSelected, ImGuiCol_TabDimmedSelectedOverline,
};
-static const ImGuiDataVarInfo GStyleVarInfo[] =
-{
- { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
- { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, DisabledAlpha) }, // ImGuiStyleVar_DisabledAlpha
- { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
- { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
- { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
- { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
- { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
- { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
- { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
- { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
- { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
- { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
- { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
- { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
- { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
- { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
- { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
- { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, CellPadding) }, // ImGuiStyleVar_CellPadding
- { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
- { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
- { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
- { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
- { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding
- { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBorderSize) }, // ImGuiStyleVar_TabBorderSize
- { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBarBorderSize) }, // ImGuiStyleVar_TabBarBorderSize
- { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBarOverlineSize) }, // ImGuiStyleVar_TabBarOverlineSize
- { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersAngle)}, // ImGuiStyleVar_TableAngledHeadersAngle
- { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersTextAlign)},// ImGuiStyleVar_TableAngledHeadersTextAlign
- { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
- { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
- { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize)}, // ImGuiStyleVar_SeparatorTextBorderSize
- { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextAlign) }, // ImGuiStyleVar_SeparatorTextAlign
- { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextPadding) }, // ImGuiStyleVar_SeparatorTextPadding
- { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, DockingSeparatorSize) }, // ImGuiStyleVar_DockingSeparatorSize
+static const ImGuiStyleVarInfo GStyleVarsInfo[] =
+{
+ { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
+ { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, DisabledAlpha) }, // ImGuiStyleVar_DisabledAlpha
+ { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
+ { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
+ { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
+ { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
+ { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
+ { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
+ { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
+ { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
+ { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
+ { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
+ { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
+ { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
+ { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
+ { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
+ { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
+ { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, CellPadding) }, // ImGuiStyleVar_CellPadding
+ { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
+ { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
+ { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ScrollbarPadding) }, // ImGuiStyleVar_ScrollbarPadding
+ { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
+ { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
+ { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ImageBorderSize) }, // ImGuiStyleVar_ImageBorderSize
+ { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding
+ { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabBorderSize) }, // ImGuiStyleVar_TabBorderSize
+ { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabMinWidthBase) }, // ImGuiStyleVar_TabMinWidthBase
+ { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabMinWidthShrink) }, // ImGuiStyleVar_TabMinWidthShrink
+ { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabBarBorderSize) }, // ImGuiStyleVar_TabBarBorderSize
+ { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabBarOverlineSize) }, // ImGuiStyleVar_TabBarOverlineSize
+ { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersAngle)}, // ImGuiStyleVar_TableAngledHeadersAngle
+ { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersTextAlign)},// ImGuiStyleVar_TableAngledHeadersTextAlign
+ { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TreeLinesSize)}, // ImGuiStyleVar_TreeLinesSize
+ { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TreeLinesRounding)}, // ImGuiStyleVar_TreeLinesRounding
+ { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
+ { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
+ { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize)}, // ImGuiStyleVar_SeparatorTextBorderSize
+ { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SeparatorTextAlign) }, // ImGuiStyleVar_SeparatorTextAlign
+ { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SeparatorTextPadding) }, // ImGuiStyleVar_SeparatorTextPadding
+ { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, DockingSeparatorSize) }, // ImGuiStyleVar_DockingSeparatorSize
};
-const ImGuiDataVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx)
+const ImGuiStyleVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx)
{
IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
- IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
- return &GStyleVarInfo[idx];
+ IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarsInfo) == ImGuiStyleVar_COUNT);
+ return &GStyleVarsInfo[idx];
}
void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
{
ImGuiContext& g = *GImGui;
- const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
- if (var_info->Type != ImGuiDataType_Float || var_info->Count != 1)
+ const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
+ if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 1)
{
IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
return;
@@ -3445,8 +3644,8 @@ void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
void ImGui::PushStyleVarX(ImGuiStyleVar idx, float val_x)
{
ImGuiContext& g = *GImGui;
- const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
- if (var_info->Type != ImGuiDataType_Float || var_info->Count != 2)
+ const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
+ if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 2)
{
IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
return;
@@ -3459,8 +3658,8 @@ void ImGui::PushStyleVarX(ImGuiStyleVar idx, float val_x)
void ImGui::PushStyleVarY(ImGuiStyleVar idx, float val_y)
{
ImGuiContext& g = *GImGui;
- const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
- if (var_info->Type != ImGuiDataType_Float || var_info->Count != 2)
+ const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
+ if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 2)
{
IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
return;
@@ -3473,8 +3672,8 @@ void ImGui::PushStyleVarY(ImGuiStyleVar idx, float val_y)
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
{
ImGuiContext& g = *GImGui;
- const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
- if (var_info->Type != ImGuiDataType_Float || var_info->Count != 2)
+ const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
+ if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 2)
{
IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
return;
@@ -3496,10 +3695,10 @@ void ImGui::PopStyleVar(int count)
{
// 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 ImGuiDataVarInfo* 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]; }
+ const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(backup.VarIdx);
+ void* data = var_info->GetVarPtr(&g.Style);
+ if (var_info->DataType == ImGuiDataType_Float && var_info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; }
+ else if (var_info->DataType == ImGuiDataType_Float && var_info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
g.StyleVarStack.pop_back();
count--;
}
@@ -3543,6 +3742,7 @@ const char* ImGui::GetStyleColorName(ImGuiCol idx)
case ImGuiCol_ResizeGrip: return "ResizeGrip";
case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
+ case ImGuiCol_InputTextCursor: return "InputTextCursor";
case ImGuiCol_TabHovered: return "TabHovered";
case ImGuiCol_Tab: return "Tab";
case ImGuiCol_TabSelected: return "TabSelected";
@@ -3563,6 +3763,7 @@ const char* ImGui::GetStyleColorName(ImGuiCol idx)
case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
case ImGuiCol_TextLink: return "TextLink";
case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
+ case ImGuiCol_TreeLines: return "TreeLines";
case ImGuiCol_DragDropTarget: return "DragDropTarget";
case ImGuiCol_NavCursor: return "NavCursor";
case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
@@ -3573,7 +3774,6 @@ const char* ImGui::GetStyleColorName(ImGuiCol idx)
return "Unknown";
}
-
//-----------------------------------------------------------------------------
// [SECTION] RENDER HELPERS
// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
@@ -3608,7 +3808,7 @@ void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool
else
{
if (!text_end)
- text_end = text + strlen(text); // FIXME-OPT
+ text_end = text + ImStrlen(text); // FIXME-OPT
text_display_end = text_end;
}
@@ -3626,7 +3826,7 @@ void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end
ImGuiWindow* window = g.CurrentWindow;
if (!text_end)
- text_end = text + strlen(text); // FIXME-OPT
+ text_end = text + ImStrlen(text); // FIXME-OPT
if (text != text_end)
{
@@ -3638,7 +3838,7 @@ void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end
// Default clip_rect uses (pos_min,pos_max)
// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
-// FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especally for text above draw_list->DrawList.
+// FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especially for text above draw_list->DrawList.
// Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take
// better advantage of the render function taking size into account for coarse clipping.
void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
@@ -3685,18 +3885,19 @@ void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, cons
}
// Another overly complex function until we reorganize everything into a nice all-in-one helper.
-// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
+// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) from 'ellipsis_max_x' which may be beyond it.
// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
-void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
+// (BREAKING) On 2025/04/16 we removed the 'float clip_max_x' parameters which was preceeding 'float ellipsis_max' and was the same value for 99% of users.
+void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
{
ImGuiContext& g = *GImGui;
if (text_end_full == NULL)
text_end_full = FindRenderedTextEnd(text);
const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
- //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
- //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
- //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
+ //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 6), IM_COL32(0, 0, 255, 255));
+ //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y - 2), ImVec2(ellipsis_max_x, pos_max.y + 3), IM_COL32(0, 255, 0, 255));
+
// FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
if (text_size.x > pos_max.x - pos_min.x)
{
@@ -3705,21 +3906,16 @@ void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, con
// min max ellipsis_max
// <-> this is generally some padding value
- const ImFont* font = draw_list->_Data->Font;
+ ImFont* font = draw_list->_Data->Font;
const float font_size = draw_list->_Data->FontSize;
const float font_scale = draw_list->_Data->FontScale;
const char* text_end_ellipsis = NULL;
- const float ellipsis_width = font->EllipsisWidth * font_scale;
+ ImFontBaked* baked = font->GetFontBaked(font_size);
+ const float ellipsis_width = baked->GetCharAdvance(font->EllipsisChar) * font_scale;
// We can now claim the space between pos_max.x and ellipsis_max.x
const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_width) - pos_min.x, 1.0f);
float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
- if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
- {
- // Always display at least 1 character if there's no room for character + ellipsis
- text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
- text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
- }
while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
{
// Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
@@ -3728,15 +3924,14 @@ void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, con
}
// Render text, render ellipsis
- RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
+ RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
+ ImVec4 cpu_fine_clip_rect(pos_min.x, pos_min.y, pos_max.x, pos_max.y);
ImVec2 ellipsis_pos = ImTrunc(ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
- if (ellipsis_pos.x + ellipsis_width <= ellipsis_max_x)
- for (int i = 0; i < font->EllipsisCharCount; i++, ellipsis_pos.x += font->EllipsisCharStep * font_scale)
- font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar);
+ font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar, &cpu_fine_clip_rect);
}
else
{
- RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
+ RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
}
if (g.LogEnabled)
@@ -3808,25 +4003,32 @@ void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCurso
ImGuiContext& g = *GImGui;
if (mouse_cursor <= ImGuiMouseCursor_None || mouse_cursor >= ImGuiMouseCursor_COUNT) // We intentionally accept out of bound values.
mouse_cursor = ImGuiMouseCursor_Arrow;
- ImFontAtlas* font_atlas = g.DrawListSharedData.Font->ContainerAtlas;
+ ImFontAtlas* font_atlas = g.DrawListSharedData.FontAtlas;
for (ImGuiViewportP* viewport : g.Viewports)
{
// We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
ImVec2 offset, size, uv[4];
- if (!font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2]))
+ if (!ImFontAtlasGetMouseCursorTexData(font_atlas, mouse_cursor, &offset, &size, &uv[0], &uv[2]))
continue;
const ImVec2 pos = base_pos - offset;
const float scale = base_scale * viewport->DpiScale;
if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
continue;
ImDrawList* draw_list = GetForegroundDrawList(viewport);
- 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) + 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();
+ ImTextureRef tex_ref = font_atlas->TexRef;
+ draw_list->PushTexture(tex_ref);
+ draw_list->AddImage(tex_ref, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow);
+ draw_list->AddImage(tex_ref, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow);
+ draw_list->AddImage(tex_ref, pos, pos + size * scale, uv[2], uv[3], col_border);
+ draw_list->AddImage(tex_ref, pos, pos + size * scale, uv[0], uv[1], col_fill);
+ if (mouse_cursor == ImGuiMouseCursor_Wait || mouse_cursor == ImGuiMouseCursor_Progress)
+ {
+ float a_min = ImFmod((float)g.Time * 5.0f, 2.0f * IM_PI);
+ float a_max = a_min + IM_PI * 1.65f;
+ draw_list->PathArcTo(pos + ImVec2(14, -1) * scale, 6.0f * scale, a_min, a_max);
+ draw_list->PathStroke(col_fill, ImDrawFlags_None, 3.0f * scale);
+ }
+ draw_list->PopTexture();
}
}
@@ -3912,14 +4114,19 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas)
Initialized = false;
ConfigFlagsCurrFrame = ConfigFlagsLastFrame = ImGuiConfigFlags_None;
- FontAtlasOwnedByContext = shared_font_atlas ? false : true;
+
Font = NULL;
- FontSize = FontBaseSize = FontScale = CurrentDpiScale = 0.0f;
+ FontBaked = NULL;
+ FontSize = FontSizeBase = FontBakedScale = CurrentDpiScale = 0.0f;
+ FontRasterizerDensity = 1.0f;
IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)();
+ if (shared_font_atlas == NULL)
+ IO.Fonts->OwnerContext = this;
Time = 0.0f;
FrameCount = 0;
FrameCountEnded = FrameCountPlatformEnded = FrameCountRendered = -1;
- WithinFrameScope = WithinFrameScopeWithImplicitWindow = WithinEndChild = false;
+ WithinEndChildID = 0;
+ WithinFrameScope = WithinFrameScopeWithImplicitWindow = false;
GcCompactAll = false;
TestEngineHookItems = false;
TestEngine = NULL;
@@ -3929,6 +4136,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas)
InputEventsNextEventId = 1;
WindowsActiveCount = 0;
+ WindowsBorderHoverPadding = 0.0f;
CurrentWindow = NULL;
HoveredWindow = NULL;
HoveredWindowUnderMovingWindow = NULL;
@@ -3938,8 +4146,8 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas)
WheelingWindowStartFrame = WheelingWindowScrolledFrame = -1;
WheelingWindowReleaseTimer = 0.0f;
- DebugDrawIdConflicts = 0;
- DebugHookIdInfo = 0;
+ DebugDrawIdConflictsId = 0;
+ DebugHookIdInfoId = 0;
HoveredId = HoveredIdPreviousFrame = 0;
HoveredIdPreviousFrameItemCount = 0;
HoveredIdAllowOverlap = false;
@@ -3959,11 +4167,11 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas)
ActiveIdClickOffset = ImVec2(-1, -1);
ActiveIdWindow = NULL;
ActiveIdSource = ImGuiInputSource_None;
+ ActiveIdDisabledId = 0;
ActiveIdMouseButton = -1;
ActiveIdPreviousFrame = 0;
- ActiveIdPreviousFrameIsAlive = false;
- ActiveIdPreviousFrameHasBeenEditedBefore = false;
- ActiveIdPreviousFrameWindow = NULL;
+ memset(&DeactivatedItemData, 0, sizeof(DeactivatedItemData));
+ memset(&ActiveIdValueOnActivation, 0, sizeof(ActiveIdValueOnActivation));
LastActiveId = 0;
LastActiveIdTimer = 0.0f;
@@ -4019,9 +4227,11 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas)
// All platforms use Ctrl+Tab but Ctrl<>Super are swapped on Mac...
// FIXME: Because this value is stored, it annoyingly interfere with toggling io.ConfigMacOSXBehaviors updating this..
+ ConfigNavWindowingWithGamepad = true;
ConfigNavWindowingKeyNext = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiKey_Tab);
ConfigNavWindowingKeyPrev = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiMod_Shift | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Tab);
NavWindowingTarget = NavWindowingTargetAnim = NavWindowingListWindow = NULL;
+ NavWindowingInputSource = ImGuiInputSource_None;
NavWindowingTimer = NavWindowingHighlightAlpha = 0.0f;
NavWindowingToggleLayer = false;
NavWindowingToggleKey = ImGuiKey_None;
@@ -4054,6 +4264,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas)
MouseCursor = ImGuiMouseCursor_Arrow;
MouseStationaryTimer = 0.0f;
+ InputTextPasswordFontBackupFlags = ImFontFlags_None;
TempInputId = 0;
memset(&DataTypeZeroValue, 0, sizeof(DataTypeZeroValue));
BeginMenuDepth = BeginComboDepth = 0;
@@ -4077,7 +4288,6 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas)
PlatformImeData.InputPos = ImVec2(0.0f, 0.0f);
PlatformImeDataPrev.InputPos = ImVec2(-1.0f, -1.0f); // Different to ensure initial submission
- PlatformImeViewport = 0;
DockNodeWindowMenuHandler = NULL;
@@ -4088,7 +4298,8 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas)
memset(LocalizationTable, 0, sizeof(LocalizationTable));
LogEnabled = false;
- LogType = ImGuiLogType_None;
+ LogFlags = ImGuiLogFlags_None;
+ LogWindow = NULL;
LogNextPrefix = LogNextSuffix = NULL;
LogFile = NULL;
LogLinePosY = FLT_MAX;
@@ -4183,6 +4394,18 @@ void ImGui::Initialize()
DockContextInitialize(&g);
#endif
+ // Print a debug message when running with debug feature IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS because it is very slow.
+ // DO NOT COMMENT OUT THIS MESSAGE. IT IS DESIGNED TO REMIND YOU THAT IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS SHOULD ONLY BE TEMPORARILY ENABLED.
+#ifdef IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS
+ DebugLog("IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS is enabled.\nMust disable after use! Otherwise Dear ImGui will run slower.\n");
+#endif
+
+ // ImDrawList/ImFontAtlas are designed to function without ImGui, and 99% of it works without an ImGui context.
+ // But this link allows us to facilitate/handle a few edge cases better.
+ ImFontAtlas* atlas = g.IO.Fonts;
+ g.DrawListSharedData.Context = &g;
+ RegisterFontAtlas(atlas);
+
g.Initialized = true;
}
@@ -4194,12 +4417,15 @@ void ImGui::Shutdown()
IM_ASSERT_USER_ERROR(g.IO.BackendRendererUserData == NULL, "Forgot to shutdown Renderer backend?");
// The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
- if (g.IO.Fonts && g.FontAtlasOwnedByContext)
+ for (ImFontAtlas* atlas : g.FontAtlases)
{
- g.IO.Fonts->Locked = false;
- IM_DELETE(g.IO.Fonts);
+ UnregisterFontAtlas(atlas);
+ if (atlas->OwnerContext == &g)
+ {
+ atlas->Locked = false;
+ IM_DELETE(atlas);
+ }
}
- g.IO.Fonts = NULL;
g.DrawListSharedData.TempBuffer.clear();
// Cleanup of other data are conditional on actually having initialized Dear ImGui.
@@ -4227,7 +4453,7 @@ void ImGui::Shutdown()
g.WindowsById.Clear();
g.NavWindow = NULL;
g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
- g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
+ g.ActiveIdWindow = NULL;
g.MovingWindow = NULL;
g.KeysRoutingTable.Clear();
@@ -4258,6 +4484,7 @@ void ImGui::Shutdown()
g.ClipboardHandlerData.clear();
g.MenusIdSubmittedThisFrame.clear();
g.InputTextState.ClearFreeMemory();
+ g.InputTextLineIndex.clear();
g.InputTextDeactivatedState.ClearFreeMemory();
g.SettingsWindows.clear();
@@ -4308,7 +4535,6 @@ void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
hook.Callback(&g, &hook);
}
-
//-----------------------------------------------------------------------------
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
//-----------------------------------------------------------------------------
@@ -4319,7 +4545,7 @@ ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NUL
memset(this, 0, sizeof(*this));
Ctx = ctx;
Name = ImStrdup(name);
- NameBufLen = (int)strlen(name) + 1;
+ NameBufLen = (int)ImStrlen(name) + 1;
ID = ImHashStr(name);
IDStack.push_back(ID);
ViewportAllowPlatformMonitorExtend = -1;
@@ -4335,12 +4561,13 @@ ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NUL
LastFrameActive = -1;
LastFrameJustFocused = -1;
LastTimeActive = -1.0f;
- FontWindowScale = FontDpiScale = 1.0f;
+ FontRefSize = 0.0f;
+ FontWindowScale = FontWindowScaleParents = 1.0f;
SettingsOffset = -1;
DockOrder = -1;
DrawList = &DrawListInst;
- DrawList->_Data = &Ctx->DrawListSharedData;
DrawList->_OwnerName = Name;
+ DrawList->_SetDrawListSharedData(&Ctx->DrawListSharedData);
NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX);
IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass();
}
@@ -4360,8 +4587,15 @@ static void SetCurrentWindow(ImGuiWindow* window)
g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
if (window)
{
- g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
- g.FontScale = g.DrawListSharedData.FontScale = g.FontSize / g.Font->FontSize;
+ bool backup_skip_items = window->SkipItems;
+ window->SkipItems = false;
+ if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures)
+ {
+ ImGuiViewport* viewport = window->Viewport;
+ g.FontRasterizerDensity = (viewport->FramebufferScale.x != 0.0f) ? viewport->FramebufferScale.x : g.IO.DisplayFramebufferScale.x; // == SetFontRasterizerDensity()
+ }
+ ImGui::UpdateCurrentFontSize(0.0f);
+ window->SkipItems = backup_skip_items;
ImGui::NavUpdateCurrentWindowIsScrollPushableX();
}
}
@@ -4371,9 +4605,12 @@ void ImGui::GcCompactTransientMiscBuffers()
ImGuiContext& g = *GImGui;
g.ItemFlagsStack.clear();
g.GroupStack.clear();
+ g.InputTextLineIndex.clear();
g.MultiSelectTempDataStacked = 0;
g.MultiSelectTempData.clear_destruct();
TableGcCompactSettings();
+ for (ImFontAtlas* atlas : g.FontAtlases)
+ atlas->CompactCache();
}
// Free up/compact internal window buffers, we can use this when a window becomes unused.
@@ -4409,20 +4646,27 @@ void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
// Clear previous active id
if (g.ActiveId != 0)
{
+ // Store deactivate data
+ ImGuiDeactivatedItemData* deactivated_data = &g.DeactivatedItemData;
+ deactivated_data->ID = g.ActiveId;
+ deactivated_data->ElapseFrame = (g.LastItemData.ID == g.ActiveId) ? g.FrameCount : g.FrameCount + 1; // FIXME: OK to use LastItemData?
+ deactivated_data->HasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
+ deactivated_data->IsAlive = (g.ActiveIdIsAlive == g.ActiveId);
+
+ // This could be written in a more general way (e.g associate a hook to ActiveId),
+ // but since this is currently quite an exception we'll leave it as is.
+ // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveID()
+ if (g.InputTextState.ID == g.ActiveId)
+ InputTextDeactivateHook(g.ActiveId);
+
// While most behaved code would make an effort to not steal active id during window move/drag operations,
// we at least need to be resilient to it. Canceling the move is rather aggressive and users of 'master' branch
// may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
{
IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
- g.MovingWindow = NULL;
+ StopMouseMovingWindow();
}
-
- // This could be written in a more general way (e.g associate a hook to ActiveId),
- // but since this is currently quite an exception we'll leave it as is.
- // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveId()
- if (g.InputTextState.ID == g.ActiveId)
- InputTextDeactivateHook(g.ActiveId);
}
// Set active id
@@ -4446,6 +4690,7 @@ void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
g.ActiveIdWindow = window;
g.ActiveIdHasBeenEditedThisFrame = false;
g.ActiveIdFromShortcut = false;
+ g.ActiveIdDisabledId = 0;
if (id)
{
g.ActiveIdIsAlive = id;
@@ -4488,8 +4733,11 @@ void ImGui::MarkItemEdited(ImGuiID id)
return;
if (g.ActiveId == id || g.ActiveId == 0)
{
+ // FIXME: Can't we fully rely on LastItemData yet?
g.ActiveIdHasBeenEditedThisFrame = true;
g.ActiveIdHasBeenEditedBefore = true;
+ if (g.DeactivatedItemData.ID == id)
+ g.DeactivatedItemData.HasBeenEditedBefore = true;
}
// We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343)
@@ -4592,8 +4840,20 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
const ImGuiID id = g.LastItemData.ID;
if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
- if (g.ActiveId != window->MoveId && g.ActiveId != window->TabId)
+ {
+ // When ActiveId == MoveId it means that either:
+ // - (1) user clicked on void _or_ an item with no id, which triggers moving window (ActiveId is set even when window has _NoMove flag)
+ // - the (id == 0) test handles it, however, IsItemHovered() will leak between id==0 items (mostly visible when using _NoMove). // FIXME: May be fixed.
+ // - (2) user clicked a disabled item. UpdateMouseMovingWindowEndFrame() uses ActiveId == MoveId to avoid interference with item logic + sets ActiveIdDisabledId.
+ bool cancel_is_hovered = true;
+ if (g.ActiveId == window->MoveId && (id == 0 || g.ActiveIdDisabledId == id))
+ cancel_is_hovered = false;
+ // When ActiveId == TabId it means user clicked docking tab for the window.
+ if (g.ActiveId == window->TabId)
+ cancel_is_hovered = false;
+ if (cancel_is_hovered)
return false;
+ }
// Test if interactions on this window are blocked by an active popup or modal.
// The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
@@ -4640,7 +4900,8 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
return true;
}
-// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
+// Internal facing ItemHoverable() used when submitting widgets. THIS IS A SUBMISSION NOT A HOVER CHECK.
+// Returns whether the item was hovered, logic differs slightly from IsItemHovered().
// (this does not rely on LastItemData it can be called from a ButtonBehavior() call not following an ItemAdd() call)
// FIXME-LEGACY: the 'ImGuiItemFlags item_flags' parameter was added on 2023-06-28.
// If you used this in your legacy/custom widgets code:
@@ -4652,11 +4913,12 @@ bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flag
ImGuiWindow* window = g.CurrentWindow;
// Detect ID conflicts
+ // (this is specifically done here by comparing on hover because it allows us a detection of duplicates that is algorithmically extra cheap, 1 u32 compare per item. No O(log N) lookup whatsoever)
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
if (id != 0 && g.HoveredIdPreviousFrame == id && (item_flags & ImGuiItemFlags_AllowDuplicateId) == 0)
{
g.HoveredIdPreviousFrameItemCount++;
- if (g.DebugDrawIdConflicts == id)
+ if (g.DebugDrawIdConflictsId == id)
window->DrawList->AddRect(bb.Min - ImVec2(1,1), bb.Max + ImVec2(1,1), IM_COL32(255, 0, 0, 255), 0.0f, ImDrawFlags_None, 2.0f);
}
#endif
@@ -4672,7 +4934,7 @@ bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flag
if (!g.ActiveIdFromShortcut)
return false;
- // Done with rectangle culling so we can perform heavier checks now.
+ // We are done with rectangle culling so we can perform heavier checks now.
if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
{
g.HoveredIdIsDisabled = true;
@@ -4750,15 +5012,30 @@ bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
// This is also inlined in ItemAdd()
// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect.
-void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
+void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags item_flags, ImGuiItemStatusFlags status_flags, const ImRect& item_rect)
{
ImGuiContext& g = *GImGui;
g.LastItemData.ID = item_id;
- g.LastItemData.ItemFlags = in_flags;
- g.LastItemData.StatusFlags = item_flags;
+ g.LastItemData.ItemFlags = item_flags;
+ g.LastItemData.StatusFlags = status_flags;
g.LastItemData.Rect = g.LastItemData.NavRect = item_rect;
}
+static void ImGui::SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect)
+{
+ ImGuiContext& g = *GImGui;
+ if (window->DockIsActive)
+ SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DC.DockTabItemStatusFlags, window->DC.DockTabItemRect);
+ else
+ SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DC.WindowItemStatusFlags, rect);
+}
+
+static void ImGui::SetLastItemDataForChildWindowItem(ImGuiWindow* window, const ImRect& rect)
+{
+ ImGuiContext& g = *GImGui;
+ SetLastItemData(window->ChildId, g.CurrentItemFlags, window->DC.ChildItemStatusFlags, rect);
+}
+
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
{
if (wrap_pos_x < 0.0f)
@@ -4819,15 +5096,15 @@ void ImGui::DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr
}
if (size != (size_t)-1)
{
+ //printf("[%05d] MemAlloc(%d) -> 0x%p\n", frame_count, (int)size, ptr);
entry->AllocCount++;
info->TotalAllocCount++;
- //printf("[%05d] MemAlloc(%d) -> 0x%p\n", frame_count, size, ptr);
}
else
{
+ //printf("[%05d] MemFree(0x%p)\n", frame_count, ptr);
entry->FreeCount++;
info->TotalFreeCount++;
- //printf("[%05d] MemFree(0x%p)\n", frame_count, ptr);
}
}
@@ -4855,12 +5132,26 @@ ImGuiIO& ImGui::GetIO()
return GImGui->IO;
}
+// This variant exists to facilitate backends experimenting with multi-threaded parallel context. (#8069, #6293, #5856)
+ImGuiIO& ImGui::GetIO(ImGuiContext* ctx)
+{
+ IM_ASSERT(ctx != NULL);
+ return ctx->IO;
+}
+
ImGuiPlatformIO& ImGui::GetPlatformIO()
{
IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext()?");
return GImGui->PlatformIO;
}
+// This variant exists to facilitate backends experimenting with multi-threaded parallel context. (#8069, #6293, #5856)
+ImGuiPlatformIO& ImGui::GetPlatformIO(ImGuiContext* ctx)
+{
+ IM_ASSERT(ctx != NULL);
+ return ctx->PlatformIO;
+}
+
// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
ImDrawData* ImGui::GetDrawData()
{
@@ -4896,7 +5187,7 @@ static ImDrawList* GetViewportBgFgDrawList(ImGuiViewportP* viewport, size_t draw
if (viewport->BgFgDrawListsLastFrame[drawlist_no] != g.FrameCount)
{
draw_list->_ResetForNewFrame();
- draw_list->PushTextureID(g.IO.Fonts->TexID);
+ draw_list->PushTexture(g.IO.Fonts->TexRef);
draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
viewport->BgFgDrawListsLastFrame[drawlist_no] = g.FrameCount;
}
@@ -4955,7 +5246,7 @@ void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* nod
{
// Can undock if:
// - part of a hierarchy with more than one visible node (if only one is visible, we'll just move the root window)
- // - part of a dockspace node hierarchy: so we can undock the last single visible node too (trivia: undocking from a fixed/central node will create a new node and copy windows)
+ // - part of a dockspace node hierarchy: so we can undock the last single visible node too. Undocking from a fixed/central node will create a new node and copy windows.
ImGuiDockNode* root_node = DockNodeGetRootNode(node);
if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL) // -V1051 PVS-Studio thinks node should be root_node and is wrong about that.
can_undock_node = true;
@@ -4969,9 +5260,38 @@ void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* nod
StartMouseMovingWindow(window);
}
+// This is not 100% symetric with StartMouseMovingWindow().
+// We do NOT clear ActiveID, because:
+// - It would lead to rather confusing recursive code paths. Caller can call ClearActiveID() if desired.
+// - Some code intentionally cancel moving but keep the ActiveID to lock inputs (e.g. code path taken when clicking a disabled item).
+void ImGui::StopMouseMovingWindow()
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.MovingWindow;
+
+ // Ref commits 6b7766817, 36055213c for some partial history on checking if viewport != NULL.
+ if (window && window->Viewport)
+ {
+ // 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(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 = window->Viewport;
+
+ // Clear the NoInputs window flag set by the Viewport system in AddUpdateViewport()
+ const bool window_can_use_inputs = ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs)) == false;
+ if (window_can_use_inputs)
+ window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs;
+ }
+ g.MovingWindow = NULL;
+}
+
// 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.
+// FIXME: We don't have strong guarantee that g.MovingWindow stay synced 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()
@@ -4986,8 +5306,8 @@ void ImGui::UpdateMouseMovingWindowNewFrame()
ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree;
// When a window stop being submitted while being dragged, it may will its viewport until next Begin()
- const bool window_disappared = (!moving_window->WasActive && !moving_window->Active);
- if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos) && !window_disappared)
+ const bool window_disappeared = (!moving_window->WasActive && !moving_window->Active);
+ if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos) && !window_disappeared)
{
ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
@@ -5003,23 +5323,7 @@ void ImGui::UpdateMouseMovingWindowNewFrame()
}
else
{
- if (!window_disappared)
- {
- // 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 (moving_window->Viewport && !IsDragDropPayloadBeingAccepted())
- g.MouseViewport = moving_window->Viewport;
-
- // Clear the NoInput window flag set by the Viewport system
- if (moving_window->Viewport)
- moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs;
- }
-
- g.MovingWindow = NULL;
+ StopMouseMovingWindow();
ClearActiveID();
}
}
@@ -5061,6 +5365,9 @@ void ImGui::UpdateMouseMovingWindowEndFrame()
{
StartMouseMovingWindow(g.HoveredWindow); //-V595
+ // FIXME: In principal we might be able to call StopMouseMovingWindow() below.
+ // Please note how StartMouseMovingWindow() and StopMouseMovingWindow() and not entirely symetrical, at the later doesn't clear ActiveId.
+
// Cancel moving if clicked outside of title bar
if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
@@ -5068,9 +5375,12 @@ void ImGui::UpdateMouseMovingWindowEndFrame()
g.MovingWindow = NULL;
// Cancel moving if clicked over an item which was disabled or inhibited by popups
- // (when g.HoveredIdIsDisabled == true && g.HoveredId == 0 we are inhibited by popups, when g.HoveredIdIsDisabled == true && g.HoveredId != 0 we are over a disabled item)0 already)
+ // (when g.HoveredIdIsDisabled == true && g.HoveredId == 0 we are inhibited by popups, when g.HoveredIdIsDisabled == true && g.HoveredId != 0 we are over a disabled item)
if (g.HoveredIdIsDisabled)
+ {
g.MovingWindow = NULL;
+ g.ActiveIdDisabledId = g.HoveredId;
+ }
}
else if (root_window == NULL && g.NavWindow != NULL)
{
@@ -5121,21 +5431,21 @@ static bool IsWindowActiveAndVisible(ImGuiWindow* window)
}
// 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()
+void ImGui::UpdateHoveredWindowAndCaptureFlags(const ImVec2& mouse_pos)
{
ImGuiContext& g = *GImGui;
ImGuiIO& io = g.IO;
// FIXME-DPI: This storage was added on 2021/03/31 for test engine, but if we want to multiply WINDOWS_HOVER_PADDING
// by DpiScale, we need to make this window-agnostic anyhow, maybe need storing inside ImGuiWindow.
- g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
+ g.WindowsBorderHoverPadding = ImMax(ImMax(g.Style.TouchExtraPadding.x, g.Style.TouchExtraPadding.y), g.Style.WindowBorderHoverPadding);
// Find the window hovered by mouse:
// - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
// - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point 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;
- FindHoveredWindowEx(g.IO.MousePos, false, &g.HoveredWindow, &g.HoveredWindowUnderMovingWindow);
+ FindHoveredWindowEx(mouse_pos, false, &g.HoveredWindow, &g.HoveredWindowUnderMovingWindow);
IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
g.HoveredWindowBeforeClear = g.HoveredWindow;
@@ -5206,7 +5516,8 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags()
io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
}
-// Calling SetupDrawListSharedData() is followed by SetCurrentFont() which sets up the remaining data.
+// Called once a frame. Followed by SetCurrentFont() which sets up the remaining data.
+// FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
static void SetupDrawListSharedData()
{
ImGuiContext& g = *GImGui;
@@ -5225,6 +5536,7 @@ static void SetupDrawListSharedData()
g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
+ g.DrawListSharedData.InitialFringeScale = 1.0f; // FIXME-DPI: Change this for some DPI scaling experiments.
}
void ImGui::NewFrame()
@@ -5249,7 +5561,6 @@ void ImGui::NewFrame()
UpdateSettings();
g.Time += g.IO.DeltaTime;
- g.WithinFrameScope = true;
g.FrameCount += 1;
g.TooltipOverrideCount = 0;
g.WindowsActiveCount = 0;
@@ -5269,12 +5580,14 @@ void ImGui::NewFrame()
// Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
UpdateViewportsNewFrame();
+ // Update texture list (collect destroyed textures, etc.)
+ UpdateTexturesNewFrame();
+
// Setup current font and draw list shared data
- // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
- g.IO.Fonts->Locked = true;
SetupDrawListSharedData();
- SetCurrentFont(GetDefaultFont());
- IM_ASSERT(g.Font->IsLoaded());
+ UpdateFontsNewFrame();
+
+ g.WithinFrameScope = true;
// Mark rendering data as invalid to prevent user who may have a handle on it to use it.
for (ImGuiViewportP* viewport : g.Viewports)
@@ -5289,9 +5602,9 @@ void ImGui::NewFrame()
// [DEBUG]
if (!g.IO.ConfigDebugHighlightIdConflicts || !g.IO.KeyCtrl) // Count is locked while holding CTRL
- g.DebugDrawIdConflicts = 0;
+ g.DebugDrawIdConflictsId = 0;
if (g.IO.ConfigDebugHighlightIdConflicts && g.HoveredIdPreviousFrameItemCount > 1)
- g.DebugDrawIdConflicts = g.HoveredIdPreviousFrame;
+ g.DebugDrawIdConflictsId = g.HoveredIdPreviousFrame;
// Update HoveredId data
if (!g.HoveredIdPreviousFrame)
@@ -5322,11 +5635,8 @@ void ImGui::NewFrame()
g.ActiveIdTimer += g.IO.DeltaTime;
g.LastActiveIdTimer += g.IO.DeltaTime;
g.ActiveIdPreviousFrame = g.ActiveId;
- g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
- g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
g.ActiveIdIsAlive = 0;
g.ActiveIdHasBeenEditedThisFrame = false;
- g.ActiveIdPreviousFrameIsAlive = false;
g.ActiveIdIsJustActivated = false;
if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
g.TempInputId = 0;
@@ -5335,6 +5645,9 @@ void ImGui::NewFrame()
g.ActiveIdUsingNavDirMask = 0x00;
g.ActiveIdUsingAllKeyboardKeys = false;
}
+ if (g.DeactivatedItemData.ElapseFrame < g.FrameCount)
+ g.DeactivatedItemData.ID = 0;
+ g.DeactivatedItemData.IsAlive = false;
// Record when we have been stationary as this state is preserved while over same item.
// FIXME: The way this is expressed means user cannot alter HoverStationaryDelay during the frame to use varying values.
@@ -5415,7 +5728,7 @@ void ImGui::NewFrame()
// Find hovered window
// (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
// (currently needs to be done after the WasActive=Active loop and FindHoveredWindowEx uses ->Active)
- UpdateHoveredWindowAndCaptureFlags();
+ UpdateHoveredWindowAndCaptureFlags(g.IO.MousePos);
// Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
UpdateMouseMovingWindowNewFrame();
@@ -5431,7 +5744,7 @@ void ImGui::NewFrame()
// Platform IME data: reset for the frame
g.PlatformImeDataPrev = g.PlatformImeData;
- g.PlatformImeData.WantVisible = false;
+ g.PlatformImeData.WantVisible = g.PlatformImeData.WantTextInput = false;
// Mouse wheel scrolling, scale
UpdateMouseWheel();
@@ -5599,8 +5912,9 @@ static void InitViewportDrawData(ImGuiViewportP* viewport)
draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
draw_data->DisplayPos = viewport->Pos;
draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size;
- draw_data->FramebufferScale = io.DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis?
+ draw_data->FramebufferScale = (viewport->FramebufferScale.x != 0.0f) ? viewport->FramebufferScale : io.DisplayFramebufferScale;
draw_data->OwnerViewport = viewport;
+ draw_data->Textures = &ImGui::GetPlatformIO().Textures;
}
// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
@@ -5609,7 +5923,7 @@ static void InitViewportDrawData(ImGuiViewportP* viewport)
// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
// some frequently called functions which to modify both channels and clipping simultaneously tend to use the
// more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
-// - This is analoguous to PushFont()/PopFont() in the sense that are a mixing a global stack and a window stack,
+// - This is analogous to PushFont()/PopFont() in the sense that are a mixing a global stack and a window stack,
// which in the case of ClipRect is not so problematic but tends to be more restrictive for fonts.
void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
{
@@ -5731,7 +6045,7 @@ static void ImGui::RenderDimmedBackgrounds()
if (window->DrawList->CmdBuffer.Size == 0)
window->DrawList->AddDrawCmd();
window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size);
- window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f);
+ window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f); // FIXME-DPI
window->DrawList->PopClipRect();
}
@@ -5757,7 +6071,11 @@ void ImGui::EndFrame()
// Don't process EndFrame() multiple times.
if (g.FrameCountEnded == g.FrameCount)
return;
- IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
+ if (!g.WithinFrameScope)
+ {
+ IM_ASSERT_USER_ERROR(g.WithinFrameScope, "Forgot to call ImGui::NewFrame()?");
+ return;
+ }
CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
@@ -5771,12 +6089,13 @@ void ImGui::EndFrame()
ImGuiPlatformImeData* ime_data = &g.PlatformImeData;
if (g.PlatformIO.Platform_SetImeDataFn != NULL && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0)
{
- ImGuiViewport* viewport = FindViewportByID(g.PlatformImeViewport);
+ ImGuiViewport* viewport = FindViewportByID(ime_data->ViewportId);
IMGUI_DEBUG_LOG_IO("[io] Calling Platform_SetImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y);
if (viewport == NULL)
viewport = GetMainViewport();
g.PlatformIO.Platform_SetImeDataFn(&g, viewport, ime_data);
}
+ g.WantTextInputNextFrame = ime_data->WantTextInput ? 1 : 0;
// Hide implicit/fallback "Debug" window if it hasn't been used
g.WithinFrameScopeWithImplicitWindow = false;
@@ -5816,6 +6135,7 @@ void ImGui::EndFrame()
// End frame
g.WithinFrameScope = false;
g.FrameCountEnded = g.FrameCount;
+ UpdateFontsEndFrame();
// Initiate moving window + handle left-click and right-click focus
UpdateMouseMovingWindowEndFrame();
@@ -5839,8 +6159,11 @@ void ImGui::EndFrame()
g.Windows.swap(g.WindowsTempSortBuffer);
g.IO.MetricsActiveWindows = g.WindowsActiveCount;
+ UpdateTexturesEndFrame();
+
// Unlock font atlas
- g.IO.Fonts->Locked = false;
+ for (ImFontAtlas* atlas : g.FontAtlases)
+ atlas->Locked = false;
// Clear Input data for next frame
g.IO.MousePosPrev = g.IO.MousePos;
@@ -5852,7 +6175,7 @@ void ImGui::EndFrame()
}
// Prepare the data for rendering so you can call GetDrawData()
-// (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all:
+// (As with anything within the ImGui:: namespace this doesn't touch your GPU or graphics API at all:
// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
void ImGui::Render()
{
@@ -5917,6 +6240,12 @@ void ImGui::Render()
g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
}
+#ifndef IMGUI_DISABLE_DEBUG_TOOLS
+ if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures)
+ for (ImFontAtlas* atlas : g.FontAtlases)
+ ImFontAtlasDebugLogTextureRequests(atlas);
+#endif
+
CallContextHooks(&g, ImGuiContextHookType_RenderPost);
}
@@ -5971,7 +6300,7 @@ void ImGui::FindHoveredWindowEx(const ImVec2& pos, bool find_first_and_in_any_vi
}
ImVec2 padding_regular = g.Style.TouchExtraPadding;
- ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;
+ ImVec2 padding_for_resize = ImMax(g.Style.TouchExtraPadding, ImVec2(g.Style.WindowBorderHoverPadding, g.Style.WindowBorderHoverPadding));
for (int i = g.Windows.Size - 1; i >= 0; i--)
{
ImGuiWindow* window = g.Windows[i];
@@ -6045,16 +6374,16 @@ bool ImGui::IsItemDeactivated()
ImGuiContext& g = *GImGui;
if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
- return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID);
+ return (g.DeactivatedItemData.ID == g.LastItemData.ID && g.LastItemData.ID != 0 && g.DeactivatedItemData.ElapseFrame >= g.FrameCount);
}
bool ImGui::IsItemDeactivatedAfterEdit()
{
ImGuiContext& g = *GImGui;
- return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
+ return IsItemDeactivated() && g.DeactivatedItemData.HasBeenEditedBefore;
}
-// == GetItemID() == GetFocusID()
+// == (GetItemID() == GetFocusID() && GetFocusID() != 0)
bool ImGui::IsItemFocused()
{
ImGuiContext& g = *GImGui;
@@ -6255,7 +6584,7 @@ bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, I
// A SetNextWindowSize() call always has priority (#8020)
// (since the code in Begin() never supported SizeVal==0.0f aka auto-resize via SetNextWindowSize() call, we don't support it here for now)
// FIXME: We only support ImGuiCond_Always in this path. Supporting other paths would requires to obtain window pointer.
- if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) != 0 && (g.NextWindowData.SizeCond & ImGuiCond_Always) != 0)
+ if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) != 0 && (g.NextWindowData.SizeCond & ImGuiCond_Always) != 0)
{
if (g.NextWindowData.SizeVal.x > 0.0f)
{
@@ -6270,9 +6599,12 @@ bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, I
}
SetNextWindowSize(size);
- // Forward child flags
- g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasChildFlags;
- g.NextWindowData.ChildFlags = child_flags;
+ // Forward child flags (we allow prior settings to merge but it'll only work for adding flags)
+ if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasChildFlags)
+ g.NextWindowData.ChildFlags |= child_flags;
+ else
+ g.NextWindowData.ChildFlags = child_flags;
+ g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasChildFlags;
// 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.
// FIXME: 2023/11/14: commented out shorted version. We had an issue with multiple ### in child window path names, which the trailing hash helped workaround.
@@ -6330,10 +6662,10 @@ void ImGui::EndChild()
ImGuiContext& g = *GImGui;
ImGuiWindow* child_window = g.CurrentWindow;
- IM_ASSERT(g.WithinEndChild == false);
+ const ImGuiID backup_within_end_child_id = g.WithinEndChildID;
IM_ASSERT(child_window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() calls
- g.WithinEndChild = true;
+ g.WithinEndChildID = child_window->ID;
ImVec2 child_size = child_window->Size;
End();
if (child_window->BeginCount == 1)
@@ -6364,8 +6696,15 @@ void ImGui::EndChild()
}
if (g.HoveredWindow == child_window)
g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
+ child_window->DC.ChildItemStatusFlags = g.LastItemData.StatusFlags;
+ //SetLastItemDataForChildWindowItem(child_window, child_window->Rect()); // Not needed, effectively done by ItemAdd()
+ }
+ else
+ {
+ SetLastItemDataForChildWindowItem(child_window, child_window->Rect());
}
- g.WithinEndChild = false;
+
+ g.WithinEndChildID = backup_within_end_child_id;
g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
}
@@ -6406,29 +6745,6 @@ static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settin
window->DockOrder = settings->DockOrder;
}
-static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
-{
- ImGuiContext& g = *GImGui;
-
- const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
- const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
- if ((just_created || child_flag_changed) && !new_is_explicit_child)
- {
- IM_ASSERT(!g.WindowsFocusOrder.contains(window));
- g.WindowsFocusOrder.push_back(window);
- window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
- }
- else if (!just_created && child_flag_changed && new_is_explicit_child)
- {
- IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
- for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
- g.WindowsFocusOrder[n]->FocusOrder--;
- g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder);
- window->FocusOrder = -1;
- }
- window->IsExplicitChild = new_is_explicit_child;
-}
-
static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
{
// Initial window state with e.g. default/arbitrary window position
@@ -6523,7 +6839,7 @@ static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& s
{
ImGuiContext& g = *GImGui;
ImVec2 new_size = size_desired;
- if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
+ if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSizeConstraint)
{
// See comments in SetNextWindowSizeConstraints() for details about setting size_min an size_max.
ImRect cr = g.NextWindowData.SizeConstraintRect;
@@ -6562,10 +6878,10 @@ static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_cur
return;
}
- content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
- content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
- content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(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_TRUNC(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
+ content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : ImTrunc64(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
+ content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : ImTrunc64(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
+ content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : ImTrunc64(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 : ImTrunc64(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
}
static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
@@ -6576,35 +6892,35 @@ static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_cont
const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y;
ImVec2 size_pad = window->WindowPadding * 2.0f;
ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars);
+
+ // Determine maximum window size
+ // Child windows are layed within their parent (unless they are also popups/menus) and thus have no restriction
+ ImVec2 size_max = ImVec2(FLT_MAX, FLT_MAX);
+ if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || (window->Flags & ImGuiWindowFlags_Popup) != 0)
+ {
+ if (!window->ViewportOwned)
+ size_max = ImGui::GetMainViewport()->WorkSize - style.DisplaySafeAreaPadding * 2.0f;
+ const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
+ if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
+ size_max = g.PlatformIO.Monitors[monitor_idx].WorkSize - style.DisplaySafeAreaPadding * 2.0f;
+ }
+
if (window->Flags & ImGuiWindowFlags_Tooltip)
{
- // Tooltip always resize
- return size_desired;
+ // Tooltip always resize (up to maximum size)
+ return ImMin(size_desired, size_max);
}
else
{
- // Maximum window size is determined by the viewport size or monitor size
ImVec2 size_min = CalcWindowMinSize(window);
- ImVec2 size_max = ImVec2(FLT_MAX, FLT_MAX);
-
- // Child windows are layed within their parent (unless they are also popups/menus) and thus have no restriction
- if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || (window->Flags & ImGuiWindowFlags_Popup) != 0)
- {
- if (!window->ViewportOwned)
- size_max = ImGui::GetMainViewport()->WorkSize - style.DisplaySafeAreaPadding * 2.0f;
- const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
- if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
- size_max = g.PlatformIO.Monitors[monitor_idx].WorkSize - style.DisplaySafeAreaPadding * 2.0f;
- }
-
- ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, size_max));
+ ImVec2 size_auto_fit = ImClamp(size_desired, ImMin(size_min, size_max), size_max);
// FIXME: CalcWindowAutoFitSize() doesn't take into account that only one axis may be auto-fit when calculating scrollbars,
// we may need to compute/store three variants of size_auto_fit, for x/y/xy.
// Here we implement a workaround for child windows only, but a full solution would apply to normal windows as well:
- if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && !(window->ChildFlags & ImGuiChildFlags_ResizeY))
+ if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && !(window->ChildFlags & (ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeY)))
size_auto_fit.y = window->SizeFull.y;
- else if (!(window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->ChildFlags & ImGuiChildFlags_ResizeY))
+ else if ((window->ChildFlags & ImGuiChildFlags_ResizeY) && !(window->ChildFlags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_AutoResizeX)))
size_auto_fit.x = window->SizeFull.x;
// When the window cannot fit all contents (either because of constraints, either because screen is too small),
@@ -6724,7 +7040,9 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& si
ImGuiContext& g = *GImGui;
ImGuiWindowFlags flags = window->Flags;
- if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
+ if ((flags & ImGuiWindowFlags_NoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
+ return false;
+ if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && (window->ChildFlags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0)
return false;
if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
return false;
@@ -6732,7 +7050,7 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& si
int ret_auto_fit_mask = 0x00;
const float grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
const float grip_hover_inner_size = (resize_grip_count > 0) ? IM_TRUNC(grip_draw_size * 0.75f) : 0.0f;
- const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;
+ const float grip_hover_outer_size = g.WindowsBorderHoverPadding;
ImRect clamp_rect = visibility_rect;
const bool window_move_from_title_bar = g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar);
@@ -6778,7 +7096,7 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& si
{
// Auto-fit when double-clicking
size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
- ret_auto_fit_mask = 0x03; // Both axises
+ ret_auto_fit_mask = 0x03; // Both axes
ClearActiveID();
}
else if (held)
@@ -6810,7 +7128,7 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& si
const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
bool hovered, held;
- ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
+ ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, g.WindowsBorderHoverPadding);
ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
ItemAdd(border_rect, border_id, NULL, ImGuiItemFlags_NoNav);
ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
@@ -6848,7 +7166,7 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& si
const ImVec2 border_curr = (window->Pos + ImMin(def.SegmentN1, def.SegmentN2) * window->Size);
const float border_target_rel_mode_for_axis = border_curr[axis] + g.IO.MouseDelta[axis];
- const float border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING; // Match ButtonBehavior() padding above.
+ const float border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + g.WindowsBorderHoverPadding; // Match ButtonBehavior() padding above.
// Use absolute mode position
ImVec2 border_target = window->Pos;
@@ -6937,7 +7255,7 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& si
// Recalculate next expected border expected coordinates
if (*border_held != -1)
- g.WindowResizeBorderExpectedRect = GetResizeBorderRect(window, *border_held, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
+ g.WindowResizeBorderExpectedRect = GetResizeBorderRect(window, *border_held, grip_hover_inner_size, g.WindowsBorderHoverPadding);
return ret_auto_fit_mask;
}
@@ -6986,7 +7304,7 @@ static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
{
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), border_col, g.Style.FrameBorderSize);
+ window->DrawList->AddLine(ImVec2(window->Pos.x + border_size * 0.5f, y), ImVec2(window->Pos.x + window->Size.x - border_size * 0.5f, y), border_col, g.Style.FrameBorderSize);
}
}
@@ -6998,9 +7316,10 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar
ImGuiStyle& style = g.Style;
ImGuiWindowFlags flags = window->Flags;
- // Ensure that ScrollBar doesn't read last frame's SkipItems
+ // Ensure that Scrollbar() doesn't read last frame's SkipItems
IM_ASSERT(window->BeginCount == 0);
window->SkipItems = false;
+ window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
// Draw window + handle manual resize
// As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
@@ -7039,7 +7358,7 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar
// Adjust alpha. For docking
bool override_alpha = false;
float alpha = 1.0f;
- if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
+ if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasBgAlpha)
{
alpha = g.NextWindowData.BgAlphaVal;
override_alpha = true;
@@ -7082,9 +7401,9 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar
{
ImRect menu_bar_rect = window->MenuBarRect();
menu_bar_rect.ClipWith(window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
- window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop);
+ window->DrawList->AddRectFilled(menu_bar_rect.Min, menu_bar_rect.Max, GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop);
if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
- window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
+ window->DrawList->AddLine(menu_bar_rect.GetBL() + ImVec2(window_border_size * 0.5f, 0.0f), menu_bar_rect.GetBR() - ImVec2(window_border_size * 0.5f, 0.0f), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
}
// Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock
@@ -7124,9 +7443,10 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar
continue;
const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
- window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
- window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
- window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
+ const float border_inner = IM_ROUND(window_border_size * 0.5f);
+ window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(border_inner, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, border_inner)));
+ window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, border_inner) : ImVec2(border_inner, resize_grip_draw_size)));
+ window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + border_inner), corner.y + grip.InnerDir.y * (window_rounding + border_inner)), window_rounding, grip.AngleMin12, grip.AngleMax12);
window->DrawList->PathFillConvex(col);
}
}
@@ -7135,6 +7455,7 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar
if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
RenderWindowOuterBorders(window);
}
+ window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
}
// When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead.
@@ -7184,8 +7505,13 @@ void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& titl
// Close button
if (has_close_button)
+ {
+ ImGuiItemFlags backup_item_flags = g.CurrentItemFlags;
+ g.CurrentItemFlags |= ImGuiItemFlags_NoFocus;
if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
*p_open = false;
+ g.CurrentItemFlags = backup_item_flags;
+ }
window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
g.CurrentItemFlags = item_flags_backup;
@@ -7254,7 +7580,7 @@ void ImGui::UpdateWindowSkipRefresh(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
window->SkipRefresh = false;
- if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasRefreshPolicy) == 0)
+ if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasRefreshPolicy) == 0)
return;
if (g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_TryToAvoidRefresh)
{
@@ -7285,42 +7611,6 @@ static void SetWindowActiveForSkipRefresh(ImGuiWindow* window)
}
}
-// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
-// should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
-// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
-// - WindowA // FindBlockingModal() returns Modal1
-// - WindowB // .. returns Modal1
-// - Modal1 // .. returns Modal2
-// - WindowC // .. returns Modal2
-// - WindowD // .. returns Modal2
-// - Modal2 // .. returns Modal2
-// - WindowE // .. returns NULL
-// Notes:
-// - FindBlockingModal(NULL) == NULL is generally equivalent to GetTopMostPopupModal() == NULL.
-// Only difference is here we check for ->Active/WasActive but it may be unnecessary.
-ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
-{
- ImGuiContext& g = *GImGui;
- if (g.OpenPopupStack.Size <= 0)
- return NULL;
-
- // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
- for (ImGuiPopupData& popup_data : g.OpenPopupStack)
- {
- ImGuiWindow* popup_window = popup_data.Window;
- if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
- continue;
- if (!popup_window->Active && !popup_window->WasActive) // Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows.
- continue;
- if (window == NULL) // FindBlockingModal(NULL) test for if FocusWindow(NULL) is naturally possible via a mouse click.
- return popup_window;
- if (IsWindowWithinBeginStackOf(window, popup_window)) // Window may be over modal
- continue;
- return popup_window; // Place window right below first block modal
- }
- return NULL;
-}
-
// Push a new Dear ImGui window to add widgets to.
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
// - Begin/End can be called multiple times during the frame with the same window name to append content.
@@ -7373,7 +7663,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
window->FlagsPreviousFrame = window->Flags;
window->Flags = (ImGuiWindowFlags)flags;
- window->ChildFlags = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasChildFlags) ? g.NextWindowData.ChildFlags : 0;
+ window->ChildFlags = (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasChildFlags) ? g.NextWindowData.ChildFlags : 0;
window->LastFrameActive = current_frame;
window->LastTimeActive = (float)g.Time;
window->BeginOrderWithinParent = 0;
@@ -7387,7 +7677,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags 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)
+ if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasDock)
SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond);
if (first_begin_of_the_frame)
{
@@ -7402,7 +7692,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
if (window->DockIsActive)
{
IM_ASSERT(window->DockNode != NULL);
- g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints
+ g.NextWindowData.HasFlags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints
}
// Amend the Appearing flag
@@ -7434,6 +7724,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
window_stack_data.Window = window;
window_stack_data.ParentLastItemDataBackup = g.LastItemData;
window_stack_data.DisabledOverrideReenable = (flags & ImGuiWindowFlags_Tooltip) && (g.CurrentItemFlags & ImGuiItemFlags_Disabled);
+ window_stack_data.DisabledOverrideReenableAlphaBackup = 0.0f;
ErrorRecoveryStoreState(&window_stack_data.StackSizesInBegin);
g.StackSizesInBeginForCurrentWindow = &window_stack_data.StackSizesInBegin;
if (flags & ImGuiWindowFlags_ChildMenu)
@@ -7459,6 +7750,9 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
window->ParentWindowForFocusRoute = FindWindowByID(window->WindowClass.FocusRouteParentWindowId);
IM_ASSERT(window->ParentWindowForFocusRoute != 0); // Invalid value for FocusRouteParentWindowId.
}
+
+ // Inherit SetWindowFontScale() from parent until we fix this system...
+ window->FontWindowScaleParents = parent_window ? parent_window->FontWindowScaleParents * parent_window->FontWindowScale : 1.0f;
}
// Add to focus scope stack
@@ -7476,10 +7770,10 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
}
// Process SetNextWindow***() calls
- // (FIXME: Consider splitting the HasXXX flags into X/Y components
+ // (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)
+ if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos)
{
window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
@@ -7495,7 +7789,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
}
}
- if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
+ if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize)
{
window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
@@ -7505,7 +7799,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
g.NextWindowData.SizeVal.y = window->SizeFull.y;
SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
}
- if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
+ if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasScroll)
{
if (g.NextWindowData.ScrollVal.x >= 0.0f)
{
@@ -7518,15 +7812,15 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
window->ScrollTargetCenterRatio.y = 0.0f;
}
}
- if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
+ if (g.NextWindowData.HasFlags & 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)
+ if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasWindowClass)
window->WindowClass = g.NextWindowData.WindowClass;
- if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
+ if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasCollapsed)
SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
- if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
+ if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasFocus)
FocusWindow(window);
if (window->Appearing)
SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
@@ -7568,7 +7862,9 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
bool window_title_visible_elsewhere = false;
if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
window_title_visible_elsewhere = true;
- else if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB
+ else if (g.NavWindowingListWindow != NULL && (flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB
+ window_title_visible_elsewhere = true;
+ else if (flags & ImGuiWindowFlags_ChildMenu)
window_title_visible_elsewhere = true;
if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
{
@@ -7616,7 +7912,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
WindowSelectViewport(window);
SetCurrentViewport(window, window->Viewport);
- window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
SetCurrentWindow(window);
flags = window->Flags;
@@ -7636,6 +7931,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
window->TitleBarHeight = (flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : g.FontSize + g.Style.FramePadding.y * 2.0f;
window->MenuBarHeight = (flags & ImGuiWindowFlags_MenuBar) ? window->DC.MenuBarOffset.y + g.FontSize + g.Style.FramePadding.y * 2.0f : 0.0f;
+ window->FontRefSize = g.FontSize; // Lock this to discourage calling window->CalcFontSize() outside of current window.
// Depending on condition we use previous or current window size to compare against contents size to decide if a scrollbar should be visible.
// Those flags will be altered further down in the function depending on more conditions.
@@ -7760,7 +8056,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
// 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);
}
@@ -7830,14 +8125,21 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
{
IM_ASSERT(window->IDStack.Size == 1);
window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
+ window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
IMGUI_TEST_ENGINE_ITEM_ADD(window->ID, window->Rect(), NULL);
IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
window->IDStack.Size = 1;
+ window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
+
}
#endif
// Decide if we are going to handle borders and resize grips
- const bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
+ // 'window->SkipItems' is not updated yet so for child windows we rely on ParentWindow to avoid submitting decorations. (#8815)
+ // Whenever we add support for full decorated child windows we will likely make this logic more general.
+ bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
+ if ((flags & ImGuiWindowFlags_ChildWindow) && window->ParentWindow->SkipItems)
+ handle_borders_and_resize_grips = false;
// Handle manual resize: Resize Grips, Borders, Gamepad
int border_hovered = -1, border_held = -1;
@@ -7882,9 +8184,23 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
+ bool scrollbar_x_prev = window->ScrollbarX;
//bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
+
+ // Track when ScrollbarX visibility keeps toggling, which is a sign of a feedback loop, and stabilize by enforcing visibility (#3285, #8488)
+ // (Feedback loops of this sort can manifest in various situations, but combining horizontal + vertical scrollbar + using a clipper with varying width items is one frequent cause.
+ // The better solution is to, either (1) enforce visibility by using ImGuiWindowFlags_AlwaysHorizontalScrollbar or (2) declare stable contents width with SetNextWindowContentSize(), if you can compute it)
+ window->ScrollbarXStabilizeToggledHistory <<= 1;
+ window->ScrollbarXStabilizeToggledHistory |= (scrollbar_x_prev != window->ScrollbarX) ? 0x01 : 0x00;
+ const bool scrollbar_x_stabilize = (window->ScrollbarXStabilizeToggledHistory != 0) && ImCountSetBits(window->ScrollbarXStabilizeToggledHistory) >= 4; // 4 == half of bits in our U8 history.
+ if (scrollbar_x_stabilize)
+ window->ScrollbarX = true;
+ //if (scrollbar_x_stabilize && !window->ScrollbarXStabilizeEnabled)
+ // IMGUI_DEBUG_LOG("[scroll] Stabilize ScrollbarX for Window '%s'\n", window->Name);
+ window->ScrollbarXStabilizeEnabled = scrollbar_x_stabilize;
+
if (window->ScrollbarX && !window->ScrollbarY)
window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars - style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar);
window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
@@ -7942,12 +8258,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
window->InnerClipRect.Max.y = ImFloor(window->InnerRect.Max.y - window->WindowBorderSize * 0.5f);
window->InnerClipRect.ClipWithFull(host_rect);
- // Default item width. Make it proportional to window size if window manually resizes
- if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
- window->ItemWidthDefault = ImTrunc(window->Size.x * 0.65f);
- else
- window->ItemWidthDefault = ImTrunc(g.FontSize * 16.0f);
-
// SCROLLING
// Lock down maximum scrolling
@@ -7965,7 +8275,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
// Setup draw list and outer clipping rectangle
IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
- window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
+ window->DrawList->PushTexture(g.Font->ContainerAtlas->TexRef);
PushClipRect(host_rect.Min, host_rect.Max, false);
// Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
@@ -8054,17 +8364,22 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
window->DC.MenuBarAppending = false;
window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user);
window->DC.TreeDepth = 0;
- window->DC.TreeHasStackDataDepthMask = 0x00;
+ window->DC.TreeHasStackDataDepthMask = window->DC.TreeRecordsClippedNodesY2Mask = 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.ItemWidth = window->ItemWidthDefault;
- window->DC.TextWrapPos = -1.0f; // disabled
- window->DC.ItemWidthStack.resize(0);
- window->DC.TextWrapPosStack.resize(0);
+ // Default item width. Make it proportional to window size if window manually resizes
+ if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
+ window->ItemWidthDefault = ImTrunc(window->Size.x * 0.65f);
+ else
+ window->ItemWidthDefault = ImTrunc(g.FontSize * 16.0f);
+ window->DC.ItemWidth = window->ItemWidthDefault;
+ window->DC.TextWrapPos = -1.0f; // disabled
+ window->DC.ItemWidthStack.resize(0);
+ window->DC.TextWrapPosStack.resize(0);
if (flags & ImGuiWindowFlags_Modal)
window->DC.ModalDimBgColor = ColorConvertFloat4ToU32(GetStyleColorVec4(ImGuiCol_ModalWindowDimBg));
@@ -8086,16 +8401,27 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
// Close requested by platform window (apply to all windows in this viewport)
+ // FIXME: Investigate removing the 'window->Viewport != GetMainViewport()' test, which seems superfluous.
if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
- {
- IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' closed by PlatformRequestClose\n", window->Name);
- *p_open = false;
- g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue. // FIXME-NAV: Try removing.
- }
+ if (window->DockNode == NULL || (window->DockNode->MergedFlags & ImGuiDockNodeFlags_DockSpace) == 0)
+ {
+ IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' closed by PlatformRequestClose\n", window->Name);
+ *p_open = false;
+ g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue. // FIXME-NAV: Try removing.
+ }
+
+ // Pressing CTRL+C copy window content into the clipboard
+ // [EXPERIMENTAL] Breaks on nested Begin/End pairs. We need to work that out and add better logging scope.
+ // [EXPERIMENTAL] Text outputs has many issues.
+ if (g.IO.ConfigWindowsCopyContentsWithCtrlC)
+ if (g.NavWindow && g.NavWindow->RootWindow == window && g.ActiveId == 0 && Shortcut(ImGuiMod_Ctrl | ImGuiKey_C))
+ LogToClipboard(0);
// Title bar
if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
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);
+ else if (!(flags & ImGuiWindowFlags_NoTitleBar) && window->DockIsActive)
+ LogText("%.*s\n", (int)(FindRenderedTextEnd(window->Name) - window->Name), window->Name);
// Clear hit test shape every frame
window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
@@ -8103,16 +8429,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
if (flags & ImGuiWindowFlags_Tooltip)
g.TooltipPreviousWindow = window;
- // Pressing CTRL+C while holding on a window copy its content to the clipboard
- // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
- // Maybe we can support CTRL+C on every element?
- /*
- //if (g.NavWindow == window && g.ActiveId == 0)
- if (g.ActiveId == window->MoveId)
- if (g.IO.KeyCtrl && IsKeyPressed(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.
@@ -8129,6 +8445,8 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
// We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
// This is useful to allow creating context menus on title bar only, etc.
+ window->DC.WindowItemStatusFlags = ImGuiItemStatusFlags_None;
+ window->DC.WindowItemStatusFlags |= IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0;
SetLastItemDataForWindow(window, title_bar_rect);
// [DEBUG]
@@ -8140,7 +8458,11 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
// [Test Engine] Register title bar / tab with MoveId.
#ifdef IMGUI_ENABLE_TEST_ENGINE
if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
+ {
+ window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.ID, g.LastItemData.Rect, &g.LastItemData);
+ window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
+ }
#endif
}
else
@@ -8196,7 +8518,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
// 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))
+ if (parent_window && parent_window->HiddenFramesCannotSkipItems > 0)
window->HiddenFramesCannotSkipItems = 1;
}
@@ -8253,15 +8575,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
return !window->SkipItems;
}
-static void ImGui::SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect)
-{
- ImGuiContext& g = *GImGui;
- if (window->DockIsActive)
- SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DockTabItemStatusFlags, window->DockTabItemRect);
- else
- SetLastItemData(window->MoveId, g.CurrentItemFlags, IsMouseHoveringRect(rect.Min, rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, rect);
-}
-
void ImGui::End()
{
ImGuiContext& g = *GImGui;
@@ -8277,7 +8590,7 @@ void ImGui::End()
// Error checking: verify that user doesn't directly call End() on a child window.
if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive)
- IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
+ IM_ASSERT_USER_ERROR(g.WithinEndChildID == window->ID, "Must call EndChild() and not End()!");
// Close anything that is open
if (window->DC.CurrentColumns)
@@ -8295,7 +8608,7 @@ void ImGui::End()
}
// Stop logging
- if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging
+ if (g.LogWindow == window) // FIXME: add more options for scope of logging
LogFinish();
if (window->DC.IsSetPos)
@@ -8323,241 +8636,6 @@ void ImGui::End()
SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport);
}
-void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
-{
- ImGuiContext& g = *GImGui;
- IM_ASSERT(window == window->RootWindow);
-
- const int cur_order = window->FocusOrder;
- IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
- if (g.WindowsFocusOrder.back() == window)
- return;
-
- const int new_order = g.WindowsFocusOrder.Size - 1;
- for (int n = cur_order; n < new_order; n++)
- {
- g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
- g.WindowsFocusOrder[n]->FocusOrder--;
- IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
- }
- g.WindowsFocusOrder[new_order] = window;
- window->FocusOrder = (short)new_order;
-}
-
-void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
-{
- ImGuiContext& g = *GImGui;
- ImGuiWindow* current_front_window = g.Windows.back();
- if (current_front_window == window || current_front_window->RootWindowDockTree == 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)
- {
- memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
- g.Windows[g.Windows.Size - 1] = window;
- break;
- }
-}
-
-void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
-{
- ImGuiContext& g = *GImGui;
- if (g.Windows[0] == window)
- return;
- for (int i = 0; i < g.Windows.Size; i++)
- if (g.Windows[i] == window)
- {
- memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
- g.Windows[0] = window;
- break;
- }
-}
-
-void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
-{
- IM_ASSERT(window != NULL && behind_window != NULL);
- ImGuiContext& g = *GImGui;
- window = window->RootWindow;
- behind_window = behind_window->RootWindow;
- int pos_wnd = FindWindowDisplayIndex(window);
- int pos_beh = FindWindowDisplayIndex(behind_window);
- if (pos_wnd < pos_beh)
- {
- size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
- memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes);
- g.Windows[pos_beh - 1] = window;
- }
- else
- {
- size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
- memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes);
- g.Windows[pos_beh] = window;
- }
-}
-
-int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
-{
- ImGuiContext& g = *GImGui;
- return g.Windows.index_from_ptr(g.Windows.find(window));
-}
-
-// Moving window to front of display and set focus (which happens to be back of our sorted list)
-void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags)
-{
- ImGuiContext& g = *GImGui;
-
- // Modal check?
- if ((flags & ImGuiFocusRequestFlags_UnlessBelowModal) && (g.NavWindow != window)) // Early out in common case.
- if (ImGuiWindow* blocking_modal = FindBlockingModal(window))
- {
- // This block would typically be reached in two situations:
- // - API call to FocusWindow() with a window under a modal and ImGuiFocusRequestFlags_UnlessBelowModal flag.
- // - User clicking on void or anything behind a modal while a modal is open (window == NULL)
- IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".\n", window ? window->Name : "<NULL>", blocking_modal->Name);
- if (window && window == window->RootWindow && (window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
- BringWindowToDisplayBehind(window, blocking_modal); // Still bring right under modal. (FIXME: Could move in focus list too?)
- ClosePopupsOverWindow(GetTopMostPopupModal(), false); // Note how we need to use GetTopMostPopupModal() aad NOT blocking_modal, to handle nested modals
- return;
- }
-
- // Find last focused child (if any) and focus it instead.
- if ((flags & ImGuiFocusRequestFlags_RestoreFocusedChild) && window != NULL)
- window = NavRestoreLastChildNavWindow(window);
-
- // Apply focus
- if (g.NavWindow != window)
- {
- SetNavWindow(window);
- if (window && g.NavHighlightItemUnderNav)
- g.NavMousePosDirty = true;
- g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
- g.NavLayer = ImGuiNavLayer_Main;
- SetNavFocusScope(window ? window->NavRootFocusScopeId : 0);
- g.NavIdIsAlive = false;
- g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
-
- // Close popups if any
- ClosePopupsOverWindow(window, false);
- }
-
- // Move the root window to the top of the pile
- IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL);
- ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL;
- ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL;
- ImGuiDockNode* dock_node = window ? window->DockNode : NULL;
- bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow);
-
- // 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)
- // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window.
- if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
- if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host)
- ClearActiveID();
-
- // Passing NULL allow to disable keyboard focus
- if (!window)
- return;
- window->LastFrameJustFocused = g.FrameCount;
-
- // Select in dock node
- // For #2304 we avoid applying focus immediately before the tabbar is visible.
- //if (dock_node && dock_node->TabBar)
- // dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId;
-
- // Bring to front
- BringWindowToFocusFront(focus_front_window);
- if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
- BringWindowToDisplayFront(display_front_window);
-}
-
-void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags)
-{
- ImGuiContext& g = *GImGui;
- int start_idx = g.WindowsFocusOrder.Size - 1;
- if (under_this_window != NULL)
- {
- // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
- int offset = -1;
- while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
- {
- under_this_window = under_this_window->ParentWindow;
- offset = 0;
- }
- start_idx = FindWindowFocusIndex(under_this_window) + offset;
- }
- for (int i = start_idx; i >= 0; i--)
- {
- // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
- ImGuiWindow* window = g.WindowsFocusOrder[i];
- if (window == ignore_window || !window->WasActive)
- continue;
- if (filter_viewport != NULL && window->Viewport != filter_viewport)
- continue;
- if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
- {
- // FIXME-DOCK: When ImGuiFocusRequestFlags_RestoreFocusedChild is set...
- // 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?
- FocusWindow(window, flags);
- return;
- }
- }
- FocusWindow(NULL, flags);
-}
-
-// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.
-void ImGui::SetCurrentFont(ImFont* font)
-{
- ImGuiContext& g = *GImGui;
- IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
- IM_ASSERT(font->Scale > 0.0f);
- g.Font = font;
- g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
- g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
- g.FontScale = g.FontSize / g.Font->FontSize;
-
- 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;
- g.DrawListSharedData.FontScale = g.FontScale;
-}
-
-// Use ImDrawList::_SetTextureID(), making our shared g.FontStack[] authorative against window-local ImDrawList.
-// - Whereas ImDrawList::PushTextureID()/PopTextureID() is not to be used across Begin() calls.
-// - Note that we don't propagate current texture id when e.g. Begin()-ing into a new window, we never really did...
-// - Some code paths never really fully worked with multiple atlas textures.
-// - The right-ish solution may be to remove _SetTextureID() and make AddText/RenderText lazily call PushTextureID()/PopTextureID()
-// the same way AddImage() does, but then all other primitives would also need to? I don't think we should tackle this problem
-// because we have a concrete need and a test bed for multiple atlas textures.
-void ImGui::PushFont(ImFont* font)
-{
- ImGuiContext& g = *GImGui;
- if (font == NULL)
- font = GetDefaultFont();
- g.FontStack.push_back(font);
- SetCurrentFont(font);
- g.CurrentWindow->DrawList->_SetTextureID(font->ContainerAtlas->TexID);
-}
-
-void ImGui::PopFont()
-{
- ImGuiContext& g = *GImGui;
- if (g.FontStack.Size <= 0)
- {
- IM_ASSERT_USER_ERROR(0, "Calling PopFont() too many times!");
- return;
- }
- g.FontStack.pop_back();
- ImFont* font = g.FontStack.Size == 0 ? GetDefaultFont() : g.FontStack.back();
- SetCurrentFont(font);
- g.CurrentWindow->DrawList->_SetTextureID(font->ContainerAtlas->TexID);
-}
-
void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
{
ImGuiContext& g = *GImGui;
@@ -8629,6 +8707,7 @@ void ImGui::BeginDisabledOverrideReenable()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.CurrentItemFlags & ImGuiItemFlags_Disabled);
+ g.CurrentWindowStack.back().DisabledOverrideReenableAlphaBackup = g.Style.Alpha;
g.Style.Alpha = g.DisabledAlphaBackup;
g.CurrentItemFlags &= ~ImGuiItemFlags_Disabled;
g.ItemFlagsStack.push_back(g.CurrentItemFlags);
@@ -8642,7 +8721,7 @@ void ImGui::EndDisabledOverrideReenable()
IM_ASSERT(g.DisabledStackSize > 0);
g.ItemFlagsStack.pop_back();
g.CurrentItemFlags = g.ItemFlagsStack.back();
- g.Style.Alpha = g.DisabledAlphaBackup * g.Style.DisabledAlpha;
+ g.Style.Alpha = g.CurrentWindowStack.back().DisabledOverrideReenableAlphaBackup;
}
void ImGui::PushTextWrapPos(float wrap_pos_x)
@@ -8780,29 +8859,6 @@ bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
return true;
}
-bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
-{
- ImGuiContext& g = *GImGui;
- ImGuiWindow* ref_window = g.NavWindow;
- ImGuiWindow* cur_window = g.CurrentWindow;
-
- if (ref_window == NULL)
- return false;
- if (flags & ImGuiFocusedFlags_AnyWindow)
- return true;
-
- IM_ASSERT(cur_window); // Not inside a Begin()/End()
- const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
- const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0;
- if (flags & ImGuiHoveredFlags_RootWindow)
- cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
-
- if (flags & ImGuiHoveredFlags_ChildWindows)
- return IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
- else
- return (ref_window == cur_window);
-}
-
ImGuiID ImGui::GetWindowDockID()
{
ImGuiContext& g = *GImGui;
@@ -8815,14 +8871,6 @@ bool ImGui::IsWindowDocked()
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 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->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
-}
-
float ImGui::GetWindowWidth()
{
ImGuiWindow* window = GImGui->CurrentWindow;
@@ -8931,8 +8979,10 @@ void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond co
return;
window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
- // Set
- window->Collapsed = collapsed;
+ // Queue applying in Begin()
+ if (window->WantCollapseToggle)
+ window->Collapsed ^= 1;
+ window->WantCollapseToggle = (window->Collapsed != collapsed);
}
void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
@@ -8971,29 +9021,11 @@ void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
SetWindowCollapsed(window, collapsed, cond);
}
-void ImGui::SetWindowFocus()
-{
- FocusWindow(GImGui->CurrentWindow);
-}
-
-void ImGui::SetWindowFocus(const char* name)
-{
- if (name)
- {
- if (ImGuiWindow* window = FindWindowByName(name))
- FocusWindow(window);
- }
- else
- {
- FocusWindow(NULL);
- }
-}
-
void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
- g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
+ g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasPos;
g.NextWindowData.PosVal = pos;
g.NextWindowData.PosPivotVal = pivot;
g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
@@ -9004,7 +9036,7 @@ void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
- g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
+ g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasSize;
g.NextWindowData.SizeVal = size;
g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
}
@@ -9016,25 +9048,25 @@ void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
{
ImGuiContext& g = *GImGui;
- g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
+ g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
g.NextWindowData.SizeCallback = custom_callback;
g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
}
// Content size = inner scrollable rectangle, padded with WindowPadding.
-// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
+// SetNextWindowContentSize(ImVec2(100,100)) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
void ImGui::SetNextWindowContentSize(const ImVec2& size)
{
ImGuiContext& g = *GImGui;
- g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
+ g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasContentSize;
g.NextWindowData.ContentSizeVal = ImTrunc(size);
}
void ImGui::SetNextWindowScroll(const ImVec2& scroll)
{
ImGuiContext& g = *GImGui;
- g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
+ g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasScroll;
g.NextWindowData.ScrollVal = scroll;
}
@@ -9042,35 +9074,29 @@ void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
- g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
+ g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasCollapsed;
g.NextWindowData.CollapsedVal = collapsed;
g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
}
-void ImGui::SetNextWindowFocus()
-{
- ImGuiContext& g = *GImGui;
- g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
-}
-
void ImGui::SetNextWindowBgAlpha(float alpha)
{
ImGuiContext& g = *GImGui;
- g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
+ g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasBgAlpha;
g.NextWindowData.BgAlphaVal = alpha;
}
void ImGui::SetNextWindowViewport(ImGuiID id)
{
ImGuiContext& g = *GImGui;
- g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasViewport;
+ g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasViewport;
g.NextWindowData.ViewportId = id;
}
void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
- g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasDock;
+ g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasDock;
g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
g.NextWindowData.DockId = id;
}
@@ -9079,7 +9105,7 @@ 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.HasFlags |= ImGuiNextWindowDataFlags_HasWindowClass;
g.NextWindowData.WindowClass = *window_class;
}
@@ -9087,7 +9113,7 @@ void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
void ImGui::SetNextWindowRefreshPolicy(ImGuiWindowRefreshFlags flags)
{
ImGuiContext& g = *GImGui;
- g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasRefreshPolicy;
+ g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasRefreshPolicy;
g.NextWindowData.RefreshFlagsVal = flags;
}
@@ -9115,6 +9141,14 @@ ImFont* ImGui::GetFont()
return GImGui->Font;
}
+ImFontBaked* ImGui::GetFontBaked()
+{
+ return GImGui->FontBaked;
+}
+
+// Get current font size (= height in pixels) of current font, with global scale factors applied.
+// - Use style.FontSizeBase to get value before global scale factors.
+// - recap: ImGui::GetFontSize() == style.FontSizeBase * (style.FontScaleMain * style.FontScaleDpi * other_scaling_factors)
float ImGui::GetFontSize()
{
return GImGui->FontSize;
@@ -9125,15 +9159,16 @@ ImVec2 ImGui::GetFontTexUvWhitePixel()
return GImGui->DrawListSharedData.TexUvWhitePixel;
}
+// Prefer using PushFont(NULL, style.FontSizeBase * factor), or use style.FontScaleMain to scale all windows.
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
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();
- g.FontScale = g.DrawListSharedData.FontScale = g.FontSize / g.Font->FontSize;
+ UpdateCurrentFontSize(0.0f);
}
+#endif
void ImGui::PushFocusScope(ImGuiID id)
{
@@ -9288,6 +9323,268 @@ bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
}
//-----------------------------------------------------------------------------
+// [SECTION] FONTS, TEXTURES
+//-----------------------------------------------------------------------------
+// Most of the relevant font logic is in imgui_draw.cpp.
+// Those are high-level support functions.
+//-----------------------------------------------------------------------------
+// - UpdateTexturesNewFrame() [Internal]
+// - UpdateTexturesEndFrame() [Internal]
+// - UpdateFontsNewFrame() [Internal]
+// - UpdateFontsEndFrame() [Internal]
+// - GetDefaultFont() [Internal]
+// - RegisterUserTexture() [Internal]
+// - UnregisterUserTexture() [Internal]
+// - RegisterFontAtlas() [Internal]
+// - UnregisterFontAtlas() [Internal]
+// - SetCurrentFont() [Internal]
+// - UpdateCurrentFontSize() [Internal]
+// - SetFontRasterizerDensity() [Internal]
+// - PushFont()
+// - PopFont()
+//-----------------------------------------------------------------------------
+
+static void ImGui::UpdateTexturesNewFrame()
+{
+ // Cannot update every atlases based on atlas's FrameCount < g.FrameCount, because an atlas may be shared by multiple contexts with different frame count.
+ ImGuiContext& g = *GImGui;
+ const bool has_textures = (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) != 0;
+ for (ImFontAtlas* atlas : g.FontAtlases)
+ {
+ if (atlas->OwnerContext == &g)
+ {
+ ImFontAtlasUpdateNewFrame(atlas, g.FrameCount, has_textures);
+ }
+ else
+ {
+ // (1) If you manage font atlases yourself, e.g. create a ImFontAtlas yourself you need to call ImFontAtlasUpdateNewFrame() on it.
+ // Otherwise, calling ImGui::CreateContext() without parameter will create an atlas owned by the context.
+ // (2) If you have multiple font atlases, make sure the 'atlas->RendererHasTextures' as specified in the ImFontAtlasUpdateNewFrame() call matches for that.
+ // (3) If you have multiple imgui contexts, they also need to have a matching value for ImGuiBackendFlags_RendererHasTextures.
+ IM_ASSERT(atlas->Builder != NULL && atlas->Builder->FrameCount != -1);
+ IM_ASSERT(atlas->RendererHasTextures == has_textures);
+ }
+ }
+}
+
+// Build a single texture list
+static void ImGui::UpdateTexturesEndFrame()
+{
+ ImGuiContext& g = *GImGui;
+ g.PlatformIO.Textures.resize(0);
+ for (ImFontAtlas* atlas : g.FontAtlases)
+ for (ImTextureData* tex : atlas->TexList)
+ {
+ // We provide this information so backends can decide whether to destroy textures.
+ // This means in practice that if N imgui contexts are created with a shared atlas, we assume all of them have a backend initialized.
+ tex->RefCount = (unsigned short)atlas->RefCount;
+ g.PlatformIO.Textures.push_back(tex);
+ }
+ for (ImTextureData* tex : g.UserTextures)
+ g.PlatformIO.Textures.push_back(tex);
+}
+
+void ImGui::UpdateFontsNewFrame()
+{
+ ImGuiContext& g = *GImGui;
+ if ((g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0)
+ for (ImFontAtlas* atlas : g.FontAtlases)
+ atlas->Locked = true;
+
+ if (g.Style._NextFrameFontSizeBase != 0.0f)
+ {
+ g.Style.FontSizeBase = g.Style._NextFrameFontSizeBase;
+ g.Style._NextFrameFontSizeBase = 0.0f;
+ }
+
+ // Apply default font size the first time
+ ImFont* font = ImGui::GetDefaultFont();
+ if (g.Style.FontSizeBase <= 0.0f)
+ g.Style.FontSizeBase = (font->LegacySize > 0.0f ? font->LegacySize : FONT_DEFAULT_SIZE);
+
+ // Set initial font
+ g.Font = font;
+ g.FontSizeBase = g.Style.FontSizeBase;
+ g.FontSize = 0.0f;
+ ImFontStackData font_stack_data = { font, g.Style.FontSizeBase, g.Style.FontSizeBase }; // <--- Will restore FontSize
+ SetCurrentFont(font_stack_data.Font, font_stack_data.FontSizeBeforeScaling, 0.0f); // <--- but use 0.0f to enable scale
+ g.FontStack.push_back(font_stack_data);
+ IM_ASSERT(g.Font->IsLoaded());
+}
+
+void ImGui::UpdateFontsEndFrame()
+{
+ PopFont();
+}
+
+ImFont* ImGui::GetDefaultFont()
+{
+ ImGuiContext& g = *GImGui;
+ ImFontAtlas* atlas = g.IO.Fonts;
+ if (atlas->Builder == NULL || atlas->Fonts.Size == 0)
+ ImFontAtlasBuildMain(atlas);
+ return g.IO.FontDefault ? g.IO.FontDefault : atlas->Fonts[0];
+}
+
+// EXPERIMENTAL: DO NOT USE YET.
+void ImGui::RegisterUserTexture(ImTextureData* tex)
+{
+ ImGuiContext& g = *GImGui;
+ tex->RefCount++;
+ g.UserTextures.push_back(tex);
+}
+
+void ImGui::UnregisterUserTexture(ImTextureData* tex)
+{
+ ImGuiContext& g = *GImGui;
+ IM_ASSERT(tex->RefCount > 0);
+ tex->RefCount--;
+ g.UserTextures.find_erase(tex);
+}
+
+void ImGui::RegisterFontAtlas(ImFontAtlas* atlas)
+{
+ ImGuiContext& g = *GImGui;
+ if (g.FontAtlases.Size == 0)
+ IM_ASSERT(atlas == g.IO.Fonts);
+ atlas->RefCount++;
+ g.FontAtlases.push_back(atlas);
+ ImFontAtlasAddDrawListSharedData(atlas, &g.DrawListSharedData);
+}
+
+void ImGui::UnregisterFontAtlas(ImFontAtlas* atlas)
+{
+ ImGuiContext& g = *GImGui;
+ IM_ASSERT(atlas->RefCount > 0);
+ ImFontAtlasRemoveDrawListSharedData(atlas, &g.DrawListSharedData);
+ g.FontAtlases.find_erase(atlas);
+ atlas->RefCount--;
+}
+
+// Use ImDrawList::_SetTexture(), making our shared g.FontStack[] authoritative against window-local ImDrawList.
+// - Whereas ImDrawList::PushTexture()/PopTexture() is not to be used across Begin() calls.
+// - Note that we don't propagate current texture id when e.g. Begin()-ing into a new window, we never really did...
+// - Some code paths never really fully worked with multiple atlas textures.
+// - The right-ish solution may be to remove _SetTexture() and make AddText/RenderText lazily call PushTexture()/PopTexture()
+// the same way AddImage() does, but then all other primitives would also need to? I don't think we should tackle this problem
+// because we have a concrete need and a test bed for multiple atlas textures.
+// FIXME-NEWATLAS-V2: perhaps we can now leverage ImFontAtlasUpdateDrawListsTextures() ?
+void ImGui::SetCurrentFont(ImFont* font, float font_size_before_scaling, float font_size_after_scaling)
+{
+ ImGuiContext& g = *GImGui;
+ g.Font = font;
+ g.FontSizeBase = font_size_before_scaling;
+ UpdateCurrentFontSize(font_size_after_scaling);
+
+ if (font != NULL)
+ {
+ IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ IM_ASSERT(font->Scale > 0.0f);
+#endif
+ ImFontAtlas* atlas = font->ContainerAtlas;
+ g.DrawListSharedData.FontAtlas = atlas;
+ g.DrawListSharedData.Font = font;
+ ImFontAtlasUpdateDrawListsSharedData(atlas);
+ if (g.CurrentWindow != NULL)
+ g.CurrentWindow->DrawList->_SetTexture(atlas->TexRef);
+ }
+}
+
+void ImGui::UpdateCurrentFontSize(float restore_font_size_after_scaling)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+
+ g.Style.FontSizeBase = g.FontSizeBase;
+
+ // Early out to avoid hidden window keeping bakes referenced and out of GC reach.
+ // However this would leave a pretty subtle and damning error surface area if g.FontBaked was mismatching.
+ // FIXME: perhaps g.FontSize should be updated?
+ if (window != NULL && window->SkipItems)
+ {
+ ImGuiTable* table = g.CurrentTable;
+ if (table == NULL || (table->CurrentColumn != -1 && table->Columns[table->CurrentColumn].IsSkipItems == false)) // See 8465#issuecomment-2951509561 and #8865. Ideally the SkipItems=true in tables would be amended with extra data.
+ return;
+ }
+
+ // Restoring is pretty much only used by PopFont()
+ float final_size = (restore_font_size_after_scaling > 0.0f) ? restore_font_size_after_scaling : 0.0f;
+ if (final_size == 0.0f)
+ {
+ final_size = g.FontSizeBase;
+
+ // Global scale factors
+ final_size *= g.Style.FontScaleMain; // Main global scale factor
+ final_size *= g.Style.FontScaleDpi; // Per-monitor/viewport DPI scale factor, automatically updated when io.ConfigDpiScaleFonts is enabled.
+
+ // Window scale (mostly obsolete now)
+ if (window != NULL)
+ final_size *= window->FontWindowScale;
+
+ // Legacy scale factors
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ final_size *= g.IO.FontGlobalScale; // Use style.FontScaleMain instead!
+ if (g.Font != NULL)
+ final_size *= g.Font->Scale; // Was never really useful.
+#endif
+ }
+
+ // Round font size
+ // - We started rounding in 1.90 WIP (18991) as our layout system currently doesn't support non-rounded font size well yet.
+ // - We may support it better later and remove this rounding.
+ final_size = GetRoundedFontSize(final_size);
+ final_size = ImClamp(final_size, 1.0f, IMGUI_FONT_SIZE_MAX);
+ if (g.Font != NULL && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures))
+ g.Font->CurrentRasterizerDensity = g.FontRasterizerDensity;
+ g.FontSize = final_size;
+ g.FontBaked = (g.Font != NULL && window != NULL) ? g.Font->GetFontBaked(final_size) : NULL;
+ g.FontBakedScale = (g.Font != NULL && window != NULL) ? (g.FontSize / g.FontBaked->Size) : 0.0f;
+ g.DrawListSharedData.FontSize = g.FontSize;
+ g.DrawListSharedData.FontScale = g.FontBakedScale;
+}
+
+// Exposed in case user may want to override setting density.
+// IMPORTANT: Begin()/End() is overriding density. Be considerate of this you change it.
+void ImGui::SetFontRasterizerDensity(float rasterizer_density)
+{
+ ImGuiContext& g = *GImGui;
+ IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures);
+ if (g.FontRasterizerDensity == rasterizer_density)
+ return;
+ g.FontRasterizerDensity = rasterizer_density;
+ UpdateCurrentFontSize(0.0f);
+}
+
+// If you want to scale an existing font size! Read comments in imgui.h!
+void ImGui::PushFont(ImFont* font, float font_size_base)
+{
+ ImGuiContext& g = *GImGui;
+ if (font == NULL) // Before 1.92 (June 2025), PushFont(NULL) == PushFont(GetDefaultFont())
+ font = g.Font;
+ IM_ASSERT(font != NULL);
+ IM_ASSERT(font_size_base >= 0.0f);
+
+ g.FontStack.push_back({ g.Font, g.FontSizeBase, g.FontSize });
+ if (font_size_base == 0.0f)
+ font_size_base = g.FontSizeBase; // Keep current font size
+ SetCurrentFont(font, font_size_base, 0.0f);
+}
+
+void ImGui::PopFont()
+{
+ ImGuiContext& g = *GImGui;
+ if (g.FontStack.Size <= 0)
+ {
+ IM_ASSERT_USER_ERROR(0, "Calling PopFont() too many times!");
+ return;
+ }
+ ImFontStackData* font_stack_data = &g.FontStack.back();
+ SetCurrentFont(font_stack_data->Font, font_stack_data->FontSizeBeforeScaling, font_stack_data->FontSizeAfterScaling);
+ g.FontStack.pop_back();
+}
+
+//-----------------------------------------------------------------------------
// [SECTION] ID STACK
//-----------------------------------------------------------------------------
@@ -9300,7 +9597,7 @@ ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
ImGuiContext& g = *Ctx;
- if (g.DebugHookIdInfo == id)
+ if (g.DebugHookIdInfoId == id)
ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
#endif
return id;
@@ -9312,7 +9609,7 @@ ImGuiID ImGuiWindow::GetID(const void* ptr)
ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
ImGuiContext& g = *Ctx;
- if (g.DebugHookIdInfo == id)
+ if (g.DebugHookIdInfoId == id)
ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
#endif
return id;
@@ -9324,7 +9621,7 @@ ImGuiID ImGuiWindow::GetID(int n)
ImGuiID id = ImHashData(&n, sizeof(n), seed);
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
ImGuiContext& g = *Ctx;
- if (g.DebugHookIdInfo == id)
+ if (g.DebugHookIdInfoId == id)
ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
#endif
return id;
@@ -9387,7 +9684,7 @@ void ImGui::PushOverrideID(ImGuiID id)
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
- if (g.DebugHookIdInfo == id)
+ if (g.DebugHookIdInfoId == id)
DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL);
#endif
window->IDStack.push_back(id);
@@ -9401,7 +9698,7 @@ ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
ImGuiContext& g = *GImGui;
- if (g.DebugHookIdInfo == id)
+ if (g.DebugHookIdInfoId == id)
DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
#endif
return id;
@@ -9412,7 +9709,7 @@ ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed)
ImGuiID id = ImHashData(&n, sizeof(n), seed);
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
ImGuiContext& g = *GImGui;
- if (g.DebugHookIdInfo == id)
+ if (g.DebugHookIdInfoId == id)
DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
#endif
return id;
@@ -9550,28 +9847,11 @@ ImGuiKeyData* ImGui::GetKeyData(ImGuiContext* ctx, ImGuiKey key)
if (key & ImGuiMod_Mask_)
key = ConvertSingleModFlagToKey(key);
-#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
- IM_ASSERT(key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_NamedKey_END);
- if (IsLegacyKey(key) && g.IO.KeyMap[key] != -1)
- key = (ImGuiKey)g.IO.KeyMap[key]; // Remap native->imgui or imgui->native
-#else
IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
-#endif
- return &g.IO.KeysData[key - ImGuiKey_KeysData_OFFSET];
-}
-
-#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
-// Formally moved to obsolete section in 1.90.5 in spite of documented as obsolete since 1.87
-ImGuiKey ImGui::GetKeyIndex(ImGuiKey key)
-{
- ImGuiContext& g = *GImGui;
- IM_ASSERT(IsNamedKey(key));
- const ImGuiKeyData* key_data = GetKeyData(key);
- return (ImGuiKey)(key_data - g.IO.KeysData);
+ return &g.IO.KeysData[key - ImGuiKey_NamedKey_BEGIN];
}
-#endif
-// Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
+// Those names are provided for debugging purpose and are not meant to be saved persistently nor compared.
static const char* const GKeyNames[] =
{
"Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
@@ -9586,7 +9866,7 @@ static const char* const GKeyNames[] =
"Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
"Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
"KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
- "AppBack", "AppForward",
+ "AppBack", "AppForward", "Oem102",
"GamepadStart", "GamepadBack",
"GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
"GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
@@ -9602,18 +9882,7 @@ const char* ImGui::GetKeyName(ImGuiKey key)
{
if (key == ImGuiKey_None)
return "None";
-#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
IM_ASSERT(IsNamedKeyOrMod(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
-#else
- ImGuiContext& g = *GImGui;
- if (IsLegacyKey(key))
- {
- if (g.IO.KeyMap[key] == -1)
- return "N/A";
- IM_ASSERT(IsNamedKey((ImGuiKey)g.IO.KeyMap[key]));
- key = (ImGuiKey)g.IO.KeyMap[key];
- }
-#endif
if (key & ImGuiMod_Mask_)
key = ConvertSingleModFlagToKey(key);
if (!IsNamedKey(key))
@@ -9639,7 +9908,7 @@ const char* ImGui::GetKeyChordName(ImGuiKeyChord key_chord)
(key != ImGuiKey_None || key_chord == ImGuiKey_None) ? GetKeyName(key) : "");
size_t len;
if (key == ImGuiKey_None && key_chord != 0)
- if ((len = strlen(g.TempKeychordName)) != 0) // Remove trailing '+'
+ if ((len = ImStrlen(g.TempKeychordName)) != 0) // Remove trailing '+'
g.TempKeychordName[len - 1] = 0;
return g.TempKeychordName;
}
@@ -10081,6 +10350,17 @@ bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id)
return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id)
}
+// Use if you absolutely need to distinguish single-click from double-click by introducing a delay.
+// Generally use with 'delay >= io.MouseDoubleClickTime' + combined with a 'io.MouseClickedLastCount == 1' test.
+// This is a very rarely used UI idiom, but some apps use this: e.g. MS Explorer single click on an icon to rename.
+bool ImGui::IsMouseReleasedWithDelay(ImGuiMouseButton button, float delay)
+{
+ ImGuiContext& g = *GImGui;
+ IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
+ const float time_since_release = (float)(g.Time - g.IO.MouseReleasedTime[button]);
+ return !IsMouseDown(button) && (time_since_release - g.IO.DeltaTime < delay) && (time_since_release >= delay);
+}
+
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
{
ImGuiContext& g = *GImGui;
@@ -10259,74 +10539,6 @@ static void ImGui::UpdateKeyboardInputs()
if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
io.ClearInputKeys();
- // Import legacy keys or verify they are not used
-#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
- if (io.BackendUsingLegacyKeyArrays == 0)
- {
- // Backend used new io.AddKeyEvent() API: Good! Verify that old arrays are never written to externally.
- for (int n = 0; n < ImGuiKey_LegacyNativeKey_END; n++)
- IM_ASSERT((io.KeysDown[n] == false || IsKeyDown((ImGuiKey)n)) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
- }
- else
- {
- if (g.FrameCount == 0)
- for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
- IM_ASSERT(g.IO.KeyMap[n] == -1 && "Backend is not allowed to write to io.KeyMap[0..511]!");
-
- // Build reverse KeyMap (Named -> Legacy)
- for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
- if (io.KeyMap[n] != -1)
- {
- IM_ASSERT(IsLegacyKey((ImGuiKey)io.KeyMap[n]));
- io.KeyMap[io.KeyMap[n]] = n;
- }
-
- // Import legacy keys into new ones
- for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
- if (io.KeysDown[n] || io.BackendUsingLegacyKeyArrays == 1)
- {
- const ImGuiKey key = (ImGuiKey)(io.KeyMap[n] != -1 ? io.KeyMap[n] : n);
- IM_ASSERT(io.KeyMap[n] == -1 || IsNamedKey(key));
- io.KeysData[key].Down = io.KeysDown[n];
- if (key != n)
- io.KeysDown[key] = io.KeysDown[n]; // Allow legacy code using io.KeysDown[GetKeyIndex()] with old backends
- io.BackendUsingLegacyKeyArrays = 1;
- }
- if (io.BackendUsingLegacyKeyArrays == 1)
- {
- GetKeyData(ImGuiMod_Ctrl)->Down = io.KeyCtrl;
- GetKeyData(ImGuiMod_Shift)->Down = io.KeyShift;
- GetKeyData(ImGuiMod_Alt)->Down = io.KeyAlt;
- GetKeyData(ImGuiMod_Super)->Down = io.KeySuper;
- }
- }
-#endif
-
- // Import legacy ImGuiNavInput_ io inputs and convert to gamepad keys
-#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
- const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
- if (io.BackendUsingLegacyNavInputArray && nav_gamepad_active)
- {
- #define MAP_LEGACY_NAV_INPUT_TO_KEY1(_KEY, _NAV1) do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f); io.KeysData[_KEY].AnalogValue = io.NavInputs[_NAV1]; } while (0)
- #define MAP_LEGACY_NAV_INPUT_TO_KEY2(_KEY, _NAV1, _NAV2) do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f) || (io.NavInputs[_NAV2] > 0.0f); io.KeysData[_KEY].AnalogValue = ImMax(io.NavInputs[_NAV1], io.NavInputs[_NAV2]); } while (0)
- MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceDown, ImGuiNavInput_Activate);
- MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceRight, ImGuiNavInput_Cancel);
- MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceLeft, ImGuiNavInput_Menu);
- MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceUp, ImGuiNavInput_Input);
- MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadLeft, ImGuiNavInput_DpadLeft);
- MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadRight, ImGuiNavInput_DpadRight);
- MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadUp, ImGuiNavInput_DpadUp);
- MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadDown, ImGuiNavInput_DpadDown);
- MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadL1, ImGuiNavInput_FocusPrev, ImGuiNavInput_TweakSlow);
- MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadR1, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakFast);
- MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickLeft, ImGuiNavInput_LStickLeft);
- MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickRight, ImGuiNavInput_LStickRight);
- MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickUp, ImGuiNavInput_LStickUp);
- MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickDown, ImGuiNavInput_LStickDown);
- #undef NAV_MAP_KEY
- }
-#endif
-
// Update aliases
for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
UpdateAliasKey(MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] ? 1.0f : 0.0f);
@@ -10350,22 +10562,21 @@ static void ImGui::UpdateKeyboardInputs()
// Clear gamepad data if disabled
if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
- for (int i = ImGuiKey_Gamepad_BEGIN; i < ImGuiKey_Gamepad_END; i++)
+ for (int key = ImGuiKey_Gamepad_BEGIN; key < ImGuiKey_Gamepad_END; key++)
{
- io.KeysData[i - ImGuiKey_KeysData_OFFSET].Down = false;
- io.KeysData[i - ImGuiKey_KeysData_OFFSET].AnalogValue = 0.0f;
+ io.KeysData[key - ImGuiKey_NamedKey_BEGIN].Down = false;
+ io.KeysData[key - ImGuiKey_NamedKey_BEGIN].AnalogValue = 0.0f;
}
// Update keys
- for (int i = 0; i < ImGuiKey_KeysData_SIZE; i++)
+ for (int key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key++)
{
- ImGuiKeyData* key_data = &io.KeysData[i];
+ ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_NamedKey_BEGIN];
key_data->DownDurationPrev = key_data->DownDuration;
key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
if (key_data->DownDuration == 0.0f)
{
- ImGuiKey key = (ImGuiKey)(ImGuiKey_KeysData_OFFSET + i);
- if (IsKeyboardKey(key))
+ if (IsKeyboardKey((ImGuiKey)key))
g.LastKeyboardKeyPressTime = g.Time;
else if (key == ImGuiKey_ReservedForModCtrl || key == ImGuiKey_ReservedForModShift || key == ImGuiKey_ReservedForModAlt || key == ImGuiKey_ReservedForModSuper)
g.LastKeyboardKeyPressTime = g.Time;
@@ -10375,7 +10586,7 @@ static void ImGui::UpdateKeyboardInputs()
// Update keys/input owner (named keys only): one entry per key
for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
{
- ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_KeysData_OFFSET];
+ ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_NamedKey_BEGIN];
ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
owner_data->OwnerCurr = owner_data->OwnerNext;
if (!key_data->Down) // Important: ownership is released on the frame after a release. Ensure a 'MouseDown -> CloseWindow -> MouseUp' chain doesn't lead to someone else seeing the MouseUp.
@@ -10425,6 +10636,8 @@ static void ImGui::UpdateMouseInputs()
io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
io.MouseClickedCount[i] = 0; // Will be filled below
io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
+ if (io.MouseReleased[i])
+ io.MouseReleasedTime[i] = g.Time;
io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
if (io.MouseClicked[i])
@@ -10572,7 +10785,7 @@ void ImGui::UpdateMouseWheel()
if (g.IO.MouseWheelRequestAxisSwap)
wheel = ImVec2(wheel.y, 0.0f);
- // Maintain a rough average of moving magnitude on both axises
+ // Maintain a rough average of moving magnitude on both axes
// FIXME: should by based on wall clock time rather than frame-counter
g.WheelingAxisAvg.x = ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30);
g.WheelingAxisAvg.y = ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30);
@@ -10585,7 +10798,7 @@ void ImGui::UpdateMouseWheel()
// Mouse wheel scrolling: find target and apply
// - don't renew lock if axis doesn't apply on the window.
- // - select a main axis when both axises are being moved.
+ // - select a main axis when both axes are being moved.
if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel)))
if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
{
@@ -10596,7 +10809,7 @@ void ImGui::UpdateMouseWheel()
{
LockWheelingWindow(window, wheel.x);
float max_step = window->InnerRect.GetWidth() * 0.67f;
- float scroll_step = ImTrunc(ImMin(2 * window->CalcFontSize(), max_step));
+ float scroll_step = ImTrunc(ImMin(2 * window->FontRefSize, max_step));
SetScrollX(window, window->Scroll.x - wheel.x * scroll_step);
g.WheelingWindowScrolledFrame = g.FrameCount;
}
@@ -10604,7 +10817,7 @@ void ImGui::UpdateMouseWheel()
{
LockWheelingWindow(window, wheel.y);
float max_step = window->InnerRect.GetHeight() * 0.67f;
- float scroll_step = ImTrunc(ImMin(5 * window->CalcFontSize(), max_step));
+ float scroll_step = ImTrunc(ImMin(5 * window->FontRefSize, max_step));
SetScrollY(window, window->Scroll.y - wheel.y * scroll_step);
g.WheelingWindowScrolledFrame = g.FrameCount;
}
@@ -10627,13 +10840,17 @@ void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
static const char* GetInputSourceName(ImGuiInputSource source)
{
const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad" };
- IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT && source >= 0 && source < ImGuiInputSource_COUNT);
+ IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT);
+ if (source < 0 || source >= ImGuiInputSource_COUNT)
+ return "Unknown";
return input_source_names[source];
}
static const char* GetMouseSourceName(ImGuiMouseSource source)
{
const char* mouse_source_names[] = { "Mouse", "TouchScreen", "Pen" };
- IM_ASSERT(IM_ARRAYSIZE(mouse_source_names) == ImGuiMouseSource_COUNT && source >= 0 && source < ImGuiMouseSource_COUNT);
+ IM_ASSERT(IM_ARRAYSIZE(mouse_source_names) == ImGuiMouseSource_COUNT);
+ if (source < 0 || source >= ImGuiMouseSource_COUNT)
+ return "Unknown";
return mouse_source_names[source];
}
static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
@@ -10665,7 +10882,7 @@ void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
bool mouse_moved = false, mouse_wheeled = false, key_changed = false, key_changed_nonchar = false, text_inputted = false;
int mouse_button_changed = 0x00;
- ImBitArray<ImGuiKey_KeysData_SIZE> key_changed_mask;
+ ImBitArray<ImGuiKey_NamedKey_COUNT> key_changed_mask;
int event_n = 0;
for (; event_n < g.InputEventsQueue.Size; event_n++)
@@ -10726,19 +10943,16 @@ void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
if (trickle_interleaved_nonchar_keys_and_text && (text_inputted && !key_is_potentially_for_char_input))
break;
+ if (key_data->Down != e->Key.Down) // Analog change only do not trigger this, so it won't block e.g. further mouse pos events testing key_changed.
+ {
+ key_changed = true;
+ key_changed_mask.SetBit(key_data_index);
+ if (trickle_interleaved_nonchar_keys_and_text && !key_is_potentially_for_char_input)
+ key_changed_nonchar = true;
+ }
+
key_data->Down = e->Key.Down;
key_data->AnalogValue = e->Key.AnalogValue;
- key_changed = true;
- key_changed_mask.SetBit(key_data_index);
- if (trickle_interleaved_nonchar_keys_and_text && !key_is_potentially_for_char_input)
- key_changed_nonchar = true;
-
- // Allow legacy code using io.KeysDown[GetKeyIndex()] with new backends
-#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
- io.KeysDown[key_data_index] = key_data->Down;
- if (io.KeyMap[key_data_index] != -1)
- io.KeysDown[io.KeyMap[key_data_index]] = key_data->Down;
-#endif
}
else if (e->Type == ImGuiInputEventType_Text)
{
@@ -10999,7 +11213,6 @@ bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID own
return true;
}
-
//-----------------------------------------------------------------------------
// [SECTION] ERROR CHECKING, STATE RECOVERY
//-----------------------------------------------------------------------------
@@ -11036,36 +11249,44 @@ bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, si
return !error;
}
-// Until 1.89 (IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos() to extend the boundary of a parent (e.g. window or table cell)
-// This is causing issues and ambiguity and we need to retire that.
-// See https://github.com/ocornut/imgui/issues/5548 for more details.
-// [Scenario 1]
+// Until 1.89 (August 2022, IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos()/SetCursorScreenPos()
+// to extend contents size of our parent container (e.g. window contents size, which is used for auto-resizing
+// windows, table column contents size used for auto-resizing columns, group size).
+// This was causing issues and ambiguities and we needed to retire that.
+// From 1.89, extending contents size boundaries REQUIRES AN ITEM TO BE SUBMITTED.
+//
// Previously this would make the window content size ~200x200:
-// Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End(); // NOT OK
+// Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End(); // NOT OK ANYMORE
// Instead, please submit an item:
// Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
// Alternative:
// Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
-// [Scenario 2]
-// For reference this is one of the issue what we aim to fix with this change:
-// BeginGroup() + SomeItem("foobar") + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup()
-// The previous logic made SetCursorScreenPos(GetCursorScreenPos()) have a side-effect! It would erroneously incorporate ItemSpacing.y after the item into content size, making the group taller!
-// While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect. Using vertical alignment patterns could trigger this issue.
+//
+// The assert below detects when the _last_ call in a window was a SetCursorPos() not followed by an Item,
+// and with a position that would grow the parent contents size.
+//
+// Advanced:
+// - For reference, old logic was causing issues because it meant that SetCursorScreenPos(GetCursorScreenPos())
+// had a side-effect on layout! In particular this caused problem to compute group boundaries.
+// e.g. BeginGroup() + SomeItem() + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup() would cause the
+// group to be taller because auto-sizing generally adds padding on bottom and right side.
+// - While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect.
+// Using vertical alignment patterns would frequently trigger this sorts of issue.
+// - See https://github.com/ocornut/imgui/issues/5548 for more details.
void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(window->DC.IsSetPos);
window->DC.IsSetPos = false;
-#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
return;
if (window->SkipItems)
return;
- IM_ASSERT(0 && "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries. Please submit an item e.g. Dummy() to validate extent.");
-#else
- window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
-#endif
+ IM_ASSERT_USER_ERROR(0, "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries.\nPlease submit an item e.g. Dummy() afterwards in order to grow window/parent boundaries.");
+
+ // For reference, the old behavior was essentially:
+ //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
}
static void ImGui::ErrorCheckNewFrameSanityChecks()
@@ -11093,27 +11314,23 @@ static void ImGui::ErrorCheckNewFrameSanityChecks()
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->IsBuilt() && "Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()");
IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!");
IM_ASSERT(g.Style.CircleTessellationMaxError > 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.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting!");
+ IM_ASSERT(g.Style.WindowBorderHoverPadding > 0.0f && "Invalid style setting!"); // Required otherwise cannot resize from borders.
IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
-#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
- for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_COUNT; n++)
- IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < ImGuiKey_LegacyNativeKey_END && "io.KeyMap[] contains an out of bound value (need to be 0..511, 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) && g.IO.BackendUsingLegacyKeyArrays == 1)
- IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
-#endif
+ IM_ASSERT(g.Style.TreeLinesFlags == ImGuiTreeNodeFlags_DrawLinesNone || g.Style.TreeLinesFlags == ImGuiTreeNodeFlags_DrawLinesFull || g.Style.TreeLinesFlags == ImGuiTreeNodeFlags_DrawLinesToNodes);
// Error handling: we do not accept 100% silent recovery! Please contact me if you feel this is getting in your way.
if (g.IO.ConfigErrorRecovery)
IM_ASSERT(g.IO.ConfigErrorRecoveryEnableAssert || g.IO.ConfigErrorRecoveryEnableDebugLog || g.IO.ConfigErrorRecoveryEnableTooltip || g.ErrorCallback != NULL);
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ if (g.IO.FontGlobalScale > 1.0f)
+ IM_ASSERT(g.Style.FontScaleMain == 1.0f && "Since 1.92: use style.FontScaleMain instead of g.IO.FontGlobalScale!");
+
// Remap legacy names
if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos)
{
@@ -11125,6 +11342,16 @@ static void ImGui::ErrorCheckNewFrameSanityChecks()
g.IO.ConfigNavCaptureKeyboard = false;
g.IO.ConfigFlags &= ~ImGuiConfigFlags_NavNoCaptureKeyboard;
}
+ if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts)
+ {
+ g.IO.ConfigDpiScaleFonts = true;
+ g.IO.ConfigFlags &= ~ImGuiConfigFlags_DpiEnableScaleFonts;
+ }
+ if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
+ {
+ g.IO.ConfigDpiScaleViewports = true;
+ g.IO.ConfigFlags &= ~ImGuiConfigFlags_DpiEnableScaleViewports;
+ }
// Remap legacy clipboard handlers (OBSOLETED in 1.91.1, August 2024)
if (g.IO.GetClipboardTextFn != NULL && (g.PlatformIO.Platform_GetClipboardTextFn == NULL || g.PlatformIO.Platform_GetClipboardTextFn == Platform_GetClipboardTextFn_DefaultImpl))
@@ -11168,7 +11395,7 @@ static void ImGui::ErrorCheckNewFrameSanityChecks()
IM_UNUSED(mon);
IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly.");
IM_ASSERT(ImRect(mon.MainPos, mon.MainPos + mon.MainSize).Contains(ImRect(mon.WorkPos, mon.WorkPos + mon.WorkSize)) && "Monitor work bounds not setup properly. If you don't have work area information, just copy MainPos/MainSize into them.");
- IM_ASSERT(mon.DpiScale != 0.0f);
+ IM_ASSERT(mon.DpiScale > 0.0f && mon.DpiScale < 99.0f && "Monitor DpiScale is invalid."); // Typical correct values would be between 1.0f and 4.0f
}
}
}
@@ -11226,8 +11453,16 @@ void ImGui::ErrorRecoveryTryToRecoverState(const ImGuiErrorRecoveryState* state_
ImGuiWindow* window = g.CurrentWindow;
if (window->Flags & ImGuiWindowFlags_ChildWindow)
{
- IM_ASSERT_USER_ERROR(0, "Missing EndChild()");
- EndChild();
+ if (g.CurrentTable != NULL && g.CurrentTable->InnerWindow == g.CurrentWindow)
+ {
+ IM_ASSERT_USER_ERROR(0, "Missing EndTable()");
+ EndTable();
+ }
+ else
+ {
+ IM_ASSERT_USER_ERROR(0, "Missing EndChild()");
+ EndChild();
+ }
}
else
{
@@ -11265,6 +11500,11 @@ void ImGui::ErrorRecoveryTryToRecoverWindowState(const ImGuiErrorRecoveryStat
IM_ASSERT_USER_ERROR(0, "Missing EndMultiSelect()");
EndMultiSelect();
}
+ if (window->DC.MenuBarAppending) //-V1044
+ {
+ IM_ASSERT_USER_ERROR(0, "Missing EndMenuBar()");
+ EndMenuBar();
+ }
while (window->DC.TreeDepth > state_in->SizeOfTreeStack) //-V1044
{
IM_ASSERT_USER_ERROR(0, "Missing TreePop()");
@@ -11341,7 +11581,7 @@ bool ImGui::ErrorLog(const char* msg)
// Output to tooltip
if (g.IO.ConfigErrorRecoveryEnableTooltip)
{
- if (BeginErrorTooltip())
+ if (g.WithinFrameScope && BeginErrorTooltip())
{
if (g.ErrorCountCurrentFrame < 20)
{
@@ -11370,25 +11610,34 @@ void ImGui::ErrorCheckEndFrameFinalizeErrorTooltip()
{
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
ImGuiContext& g = *GImGui;
- if (g.DebugDrawIdConflicts != 0 && g.IO.KeyCtrl == false)
+ if (g.DebugDrawIdConflictsId != 0 && g.IO.KeyCtrl == false)
g.DebugDrawIdConflictsCount = g.HoveredIdPreviousFrameItemCount;
- if (g.DebugDrawIdConflicts != 0 && g.DebugItemPickerActive == false && BeginErrorTooltip())
+ if (g.DebugDrawIdConflictsId != 0 && g.DebugItemPickerActive == false && BeginErrorTooltip())
{
Text("Programmer error: %d visible items with conflicting ID!", g.DebugDrawIdConflictsCount);
BulletText("Code should use PushID()/PopID() in loops, or append \"##xx\" to same-label identifiers!");
BulletText("Empty label e.g. Button(\"\") == same ID as parent widget/node. Use Button(\"##xx\") instead!");
//BulletText("Code intending to use duplicate ID may use e.g. PushItemFlag(ImGuiItemFlags_AllowDuplicateId, true); ... PopItemFlag()"); // Not making this too visible for fear of it being abused.
- BulletText("Set io.ConfigDebugDetectIdConflicts=false to disable this warning in non-programmers builds.");
+ BulletText("Set io.ConfigDebugHighlightIdConflicts=false to disable this warning in non-programmers builds.");
Separator();
- Text("(Hold CTRL to: use");
- SameLine();
- if (SmallButton("Item Picker"))
- DebugStartItemPicker();
- SameLine();
- Text("to break in item call-stack, or");
- SameLine();
+ if (g.IO.ConfigDebugHighlightIdConflictsShowItemPicker)
+ {
+ Text("(Hold CTRL to: use ");
+ SameLine(0.0f, 0.0f);
+ if (SmallButton("Item Picker"))
+ DebugStartItemPicker();
+ SameLine(0.0f, 0.0f);
+ Text(" to break in item call-stack, or ");
+ }
+ else
+ {
+ Text("(Hold CTRL to ");
+ }
+ SameLine(0.0f, 0.0f);
if (SmallButton("Open FAQ->About ID Stack System") && g.PlatformIO.Platform_OpenInShellFn != NULL)
g.PlatformIO.Platform_OpenInShellFn(&g, "https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#qa-usage");
+ SameLine(0.0f, 0.0f);
+ Text(")");
EndErrorTooltip();
}
@@ -11452,8 +11701,8 @@ void ImGui::KeepAliveID(ImGuiID id)
ImGuiContext& g = *GImGui;
if (g.ActiveId == id)
g.ActiveIdIsAlive = id;
- if (g.ActiveIdPreviousFrame == id)
- g.ActiveIdPreviousFrameIsAlive = true;
+ if (g.DeactivatedItemData.ID == id)
+ g.DeactivatedItemData.IsAlive = true;
}
// Declare item bounding box for clipping and interaction.
@@ -11532,12 +11781,30 @@ bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGu
// Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
// READ THE FAQ: https://dearimgui.com/faq
IM_ASSERT(id != window->ID && "Cannot have an empty ID at the root of a window. If you need an empty label, use ## and read the FAQ about how the ID Stack works!");
+
+ // [DEBUG] Highlight all conflicts WITHOUT needing to hover. THIS WILL SLOW DOWN DEAR IMGUI. DON'T KEEP ACTIVATED.
+ // This will only work for items submitted with ItemAdd(). Some very rare/odd/unrecommended code patterns are calling ButtonBehavior() without ItemAdd().
+#ifdef IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS
+ if ((g.LastItemData.ItemFlags & ImGuiItemFlags_AllowDuplicateId) == 0)
+ {
+ int* p_alive = g.DebugDrawIdConflictsAliveCount.GetIntRef(id, -1); // Could halve lookups if we knew ImGuiStorage can store 64-bit, or by storing FrameCount as 30-bits + highlight as 2-bits. But the point is that we should not pretend that this is fast.
+ int* p_highlight = g.DebugDrawIdConflictsHighlightSet.GetIntRef(id, -1);
+ if (*p_alive == g.FrameCount)
+ *p_highlight = g.FrameCount;
+ *p_alive = g.FrameCount;
+ if (*p_highlight >= g.FrameCount - 1)
+ window->DrawList->AddRect(bb.Min - ImVec2(1, 1), bb.Max + ImVec2(1, 1), IM_COL32(255, 0, 0, 255), 0.0f, ImDrawFlags_None, 2.0f);
+ }
+#endif
}
//if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
//if ((g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav) == 0)
// window->DrawList->AddRect(g.LastItemData.NavRect.Min, g.LastItemData.NavRect.Max, IM_COL32(255,255,0,255)); // [DEBUG]
#endif
+ if (id != 0 && g.DeactivatedItemData.ID == id)
+ g.DeactivatedItemData.ElapseFrame = g.FrameCount;
+
// We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
if (is_rect_visible)
g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
@@ -11897,7 +12164,7 @@ void ImGui::BeginGroup()
group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
group_data.BackupIsSameLine = window->DC.IsSameLine;
- group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
+ group_data.BackupDeactivatedIdIsAlive = g.DeactivatedItemData.IsAlive;
group_data.EmitItem = true;
window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
@@ -11948,11 +12215,11 @@ void ImGui::EndGroup()
// Also if you grep for LastItemId you'll notice it is only used in that context.
// (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 == false) && (g.ActiveIdPreviousFrameIsAlive == true);
+ const bool group_contains_deactivated_id = (group_data.BackupDeactivatedIdIsAlive == false) && (g.DeactivatedItemData.IsAlive == true);
if (group_contains_curr_active_id)
g.LastItemData.ID = g.ActiveId;
- else if (group_contains_prev_active_id)
- g.LastItemData.ID = g.ActiveIdPreviousFrame;
+ else if (group_contains_deactivated_id)
+ g.LastItemData.ID = g.DeactivatedItemData.ID;
g.LastItemData.Rect = group_bb;
// Forward Hovered flag
@@ -11966,7 +12233,7 @@ void ImGui::EndGroup()
// Forward Deactivated flag
g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
- if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
+ if (group_contains_deactivated_id)
g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
g.GroupStack.pop_back();
@@ -12010,7 +12277,7 @@ static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
}
scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]);
}
- scroll[axis] = IM_ROUND(ImMax(scroll[axis], 0.0f));
+ scroll[axis] = ImRound64(ImMax(scroll[axis], 0.0f));
if (!window->Collapsed && !window->SkipItems)
scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]);
}
@@ -12243,10 +12510,10 @@ bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags ext
// - offset visibility to increase visibility around mouse.
// - never clamp within outer viewport boundary.
// We call SetNextWindowPos() to enforce position and disable clamping.
- // See FindBestWindowPosForPopup() for positionning logic of other tooltips (not drag and drop ones).
+ // See FindBestWindowPosForPopup() for positioning logic of other tooltips (not drag and drop ones).
//ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
const bool is_touchscreen = (g.IO.MouseSource == ImGuiMouseSource_TouchScreen);
- if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
+ if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos) == 0)
{
ImVec2 tooltip_pos = is_touchscreen ? (g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET_TOUCH * g.Style.MouseCursorScale) : (g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET_MOUSE * g.Style.MouseCursorScale);
ImVec2 tooltip_pivot = is_touchscreen ? TOOLTIP_DEFAULT_PIVOT_TOUCH : ImVec2(0.0f, 0.0f);
@@ -12386,13 +12653,50 @@ ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
return NULL;
}
-void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
+
+// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
+// should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
+// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
+// - WindowA // FindBlockingModal() returns Modal1
+// - WindowB // .. returns Modal1
+// - Modal1 // .. returns Modal2
+// - WindowC // .. returns Modal2
+// - WindowD // .. returns Modal2
+// - Modal2 // .. returns Modal2
+// - WindowE // .. returns NULL
+// Notes:
+// - FindBlockingModal(NULL) == NULL is generally equivalent to GetTopMostPopupModal() == NULL.
+// Only difference is here we check for ->Active/WasActive but it may be unnecessary.
+ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
- ImGuiID id = g.CurrentWindow->GetID(str_id);
- IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X)\n", str_id, id);
- OpenPopupEx(id, popup_flags);
-}
+ if (g.OpenPopupStack.Size <= 0)
+ return NULL;
+
+ // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
+ for (ImGuiPopupData& popup_data : g.OpenPopupStack)
+ {
+ ImGuiWindow* popup_window = popup_data.Window;
+ if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
+ continue;
+ if (!popup_window->Active && !popup_window->WasActive) // Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows.
+ continue;
+ if (window == NULL) // FindBlockingModal(NULL) test for if FocusWindow(NULL) is naturally possible via a mouse click.
+ return popup_window;
+ if (IsWindowWithinBeginStackOf(window, popup_window)) // Window may be over modal
+ continue;
+ return popup_window; // Place window right below first block modal
+ }
+ return NULL;
+}
+
+void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiID id = g.CurrentWindow->GetID(str_id);
+ IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X)\n", str_id, id);
+ OpenPopupEx(id, popup_flags);
+}
void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
{
@@ -12587,17 +12891,32 @@ bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_window_flags)
}
char name[20];
- if (extra_window_flags & ImGuiWindowFlags_ChildMenu)
- ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginMenuDepth); // Recycle windows based on depth
- else
- ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
+ IM_ASSERT((extra_window_flags & ImGuiWindowFlags_ChildMenu) == 0); // Use BeginPopupMenuEx()
+ ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // No recycling, so we can close/open during the same frame
bool is_open = Begin(name, NULL, extra_window_flags | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking);
if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
EndPopup();
-
//g.CurrentWindow->FocusRouteParentWindow = g.CurrentWindow->ParentWindowInBeginStack;
+ return is_open;
+}
+
+bool ImGui::BeginPopupMenuEx(ImGuiID id, const char* label, ImGuiWindowFlags extra_window_flags)
+{
+ ImGuiContext& g = *GImGui;
+ if (!IsPopupOpen(id, ImGuiPopupFlags_None))
+ {
+ g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
+ return false;
+ }
+ char name[128];
+ IM_ASSERT(extra_window_flags & ImGuiWindowFlags_ChildMenu);
+ ImFormatString(name, IM_ARRAYSIZE(name), "%s###Menu_%02d", label, g.BeginMenuDepth); // Recycle windows based on depth
+ bool is_open = Begin(name, NULL, extra_window_flags | ImGuiWindowFlags_Popup);
+ if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
+ EndPopup();
+ //g.CurrentWindow->FocusRouteParentWindow = g.CurrentWindow->ParentWindowInBeginStack;
return is_open;
}
@@ -12634,7 +12953,7 @@ bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags fla
// 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)
+ if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos) == 0)
{
const ImGuiViewport* viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport?
SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
@@ -12656,19 +12975,22 @@ void ImGui::EndPopup()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
- IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
- IM_ASSERT(g.BeginPopupStack.Size > 0);
+ if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || g.BeginPopupStack.Size == 0)
+ {
+ IM_ASSERT_USER_ERROR(0, "Calling EndPopup() too many times or in wrong window!");
+ return;
+ }
// Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests)
if (g.NavWindow == window)
NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
// Child-popups don't need to be laid out
- IM_ASSERT(g.WithinEndChild == false);
+ const ImGuiID backup_within_end_child_id = g.WithinEndChildID;
if (window->Flags & ImGuiWindowFlags_ChildWindow)
- g.WithinEndChild = true;
+ g.WithinEndChildID = window->ID;
End();
- g.WithinEndChild = false;
+ g.WithinEndChildID = backup_within_end_child_id;
}
// Helper to open a popup if mouse button is released over the item
@@ -12800,104 +13122,387 @@ ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& s
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);
+ // 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 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);
+ return pos;
+}
+
+// Note that this is used for popups, which can overlap the non work-area of individual viewports.
+ImRect ImGui::GetPopupAllowedExtentRect(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
+ {
+ // Use the full viewport area (not work area) for popups
+ r_screen = window->Viewport->GetMainRect();
+ }
+ ImVec2 padding = g.Style.DisplaySafeAreaPadding;
+ r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
+ return r_screen;
+}
+
+ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
+{
+ ImGuiContext& g = *GImGui;
+
+ ImRect r_outer = GetPopupAllowedExtentRect(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;
+ float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
+ ImRect r_avoid;
+ if (parent_window->DC.MenuBarAppending)
+ r_avoid = ImRect(-FLT_MAX, parent_window->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, ImGuiPopupPositionPolicy_Default);
+ }
+ if (window->Flags & ImGuiWindowFlags_Popup)
+ {
+ return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
+ }
+ if (window->Flags & ImGuiWindowFlags_Tooltip)
+ {
+ // Position tooltip (always follows mouse + clamp within outer boundaries)
+ // FIXME:
+ // - Too many paths. One problem is that FindBestWindowPosForPopupEx() doesn't allow passing a suggested position (so touch screen path doesn't use it by default).
+ // - Drag and drop tooltips are not using this path either: BeginTooltipEx() manually sets their position.
+ // - Require some tidying up. In theory we could handle both cases in same location, but requires a bit of shuffling
+ // as drag and drop tooltips are calling SetNextWindowPos() leading to 'window_pos_set_by_api' being set in Begin().
+ IM_ASSERT(g.CurrentWindow == window);
+ const float scale = g.Style.MouseCursorScale;
+ const ImVec2 ref_pos = NavCalcPreferredRefPos();
+
+ if (g.IO.MouseSource == ImGuiMouseSource_TouchScreen && NavCalcPreferredRefPosSource() == ImGuiInputSource_Mouse)
+ {
+ ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET_TOUCH * scale - (TOOLTIP_DEFAULT_PIVOT_TOUCH * window->Size);
+ if (r_outer.Contains(ImRect(tooltip_pos, tooltip_pos + window->Size)))
+ return tooltip_pos;
+ }
+
+ ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET_MOUSE * scale;
+ ImRect r_avoid;
+ if (g.NavCursorVisible && g.NavHighlightItemUnderNav && !g.IO.ConfigNavMoveSetMousePos)
+ 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 * scale, ref_pos.y + 24 * scale); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
+ //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255, 0, 255, 255));
+
+ return FindBestWindowPosForPopupEx(tooltip_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
+ }
+ IM_ASSERT(0);
+ return window->Pos;
+}
+
+//-----------------------------------------------------------------------------
+// [SECTION] WINDOW FOCUS
+//----------------------------------------------------------------------------
+// - SetWindowFocus()
+// - SetNextWindowFocus()
+// - IsWindowFocused()
+// - UpdateWindowInFocusOrderList() [Internal]
+// - BringWindowToFocusFront() [Internal]
+// - BringWindowToDisplayFront() [Internal]
+// - BringWindowToDisplayBack() [Internal]
+// - BringWindowToDisplayBehind() [Internal]
+// - FindWindowDisplayIndex() [Internal]
+// - FocusWindow() [Internal]
+// - FocusTopMostWindowUnderOne() [Internal]
+//-----------------------------------------------------------------------------
+
+void ImGui::SetWindowFocus()
+{
+ FocusWindow(GImGui->CurrentWindow);
+}
+
+void ImGui::SetWindowFocus(const char* name)
+{
+ if (name)
+ {
+ if (ImGuiWindow* window = FindWindowByName(name))
+ FocusWindow(window);
+ }
+ else
+ {
+ FocusWindow(NULL);
+ }
+}
+
+void ImGui::SetNextWindowFocus()
+{
+ ImGuiContext& g = *GImGui;
+ g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasFocus;
+}
+
+// Similar to IsWindowHovered()
+bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* ref_window = g.NavWindow;
+ ImGuiWindow* cur_window = g.CurrentWindow;
+
+ if (ref_window == NULL)
+ return false;
+ if (flags & ImGuiFocusedFlags_AnyWindow)
+ return true;
+
+ IM_ASSERT(cur_window); // Not inside a Begin()/End()
+ const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
+ const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0;
+ if (flags & ImGuiFocusedFlags_RootWindow)
+ cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
+
+ if (flags & ImGuiFocusedFlags_ChildWindows)
+ return IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
+ else
+ return (ref_window == cur_window);
+}
+
+static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
+{
+ ImGuiContext& g = *GImGui;
+ IM_UNUSED(g);
+ int order = window->FocusOrder;
+ IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
+ IM_ASSERT(g.WindowsFocusOrder[order] == window);
+ return order;
+}
+
+static void ImGui::UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
+{
+ ImGuiContext& g = *GImGui;
+
+ const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
+ const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
+ if ((just_created || child_flag_changed) && !new_is_explicit_child)
+ {
+ IM_ASSERT(!g.WindowsFocusOrder.contains(window));
+ g.WindowsFocusOrder.push_back(window);
+ window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
+ }
+ else if (!just_created && child_flag_changed && new_is_explicit_child)
+ {
+ IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
+ for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
+ g.WindowsFocusOrder[n]->FocusOrder--;
+ g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder);
+ window->FocusOrder = -1;
+ }
+ window->IsExplicitChild = new_is_explicit_child;
+}
+
+void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
+{
+ ImGuiContext& g = *GImGui;
+ IM_ASSERT(window == window->RootWindow);
+
+ const int cur_order = window->FocusOrder;
+ IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
+ if (g.WindowsFocusOrder.back() == window)
+ return;
+
+ const int new_order = g.WindowsFocusOrder.Size - 1;
+ for (int n = cur_order; n < new_order; n++)
+ {
+ g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
+ g.WindowsFocusOrder[n]->FocusOrder--;
+ IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
+ }
+ g.WindowsFocusOrder[new_order] = window;
+ window->FocusOrder = (short)new_order;
+}
+
+// Note technically focus related but rather adjacent and close to BringWindowToFocusFront()
+void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* current_front_window = g.Windows.back();
+ if (current_front_window == window || current_front_window->RootWindowDockTree == 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)
+ {
+ memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
+ g.Windows[g.Windows.Size - 1] = window;
+ break;
+ }
+}
+
+void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
+{
+ ImGuiContext& g = *GImGui;
+ if (g.Windows[0] == window)
+ return;
+ for (int i = 0; i < g.Windows.Size; i++)
+ if (g.Windows[i] == window)
+ {
+ memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
+ g.Windows[0] = window;
+ break;
+ }
+}
+
+void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
+{
+ IM_ASSERT(window != NULL && behind_window != NULL);
+ ImGuiContext& g = *GImGui;
+ window = window->RootWindow;
+ behind_window = behind_window->RootWindow;
+ int pos_wnd = FindWindowDisplayIndex(window);
+ int pos_beh = FindWindowDisplayIndex(behind_window);
+ if (pos_wnd < pos_beh)
+ {
+ size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
+ memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes);
+ g.Windows[pos_beh - 1] = window;
+ }
+ else
+ {
+ size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
+ memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes);
+ g.Windows[pos_beh] = window;
+ }
+}
+
+int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
+{
+ ImGuiContext& g = *GImGui;
+ return g.Windows.index_from_ptr(g.Windows.find(window));
+}
+
+// Moving window to front of display and set focus (which happens to be back of our sorted list)
+void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags)
+{
+ ImGuiContext& g = *GImGui;
+
+ // Modal check?
+ if ((flags & ImGuiFocusRequestFlags_UnlessBelowModal) && (g.NavWindow != window)) // Early out in common case.
+ if (ImGuiWindow* blocking_modal = FindBlockingModal(window))
+ {
+ // This block would typically be reached in two situations:
+ // - API call to FocusWindow() with a window under a modal and ImGuiFocusRequestFlags_UnlessBelowModal flag.
+ // - User clicking on void or anything behind a modal while a modal is open (window == NULL)
+ IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".\n", window ? window->Name : "<NULL>", blocking_modal->Name);
+ if (window && window == window->RootWindow && (window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
+ BringWindowToDisplayBehind(window, blocking_modal); // Still bring right under modal. (FIXME: Could move in focus list too?)
+ ClosePopupsOverWindow(GetTopMostPopupModal(), false); // Note how we need to use GetTopMostPopupModal() aad NOT blocking_modal, to handle nested modals
+ return;
+ }
+
+ // Find last focused child (if any) and focus it instead.
+ if ((flags & ImGuiFocusRequestFlags_RestoreFocusedChild) && window != NULL)
+ window = NavRestoreLastChildNavWindow(window);
+
+ // Apply focus
+ if (g.NavWindow != window)
+ {
+ SetNavWindow(window);
+ if (window && g.NavHighlightItemUnderNav)
+ g.NavMousePosDirty = true;
+ g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
+ g.NavLayer = ImGuiNavLayer_Main;
+ SetNavFocusScope(window ? window->NavRootFocusScopeId : 0);
+ g.NavIdIsAlive = false;
+ g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
- *last_dir = dir;
- return pos;
- }
+ // Close popups if any
+ ClosePopupsOverWindow(window, false);
}
- // Fallback when not enough room:
- *last_dir = ImGuiDir_None;
+ // Move the root window to the top of the pile
+ IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL);
+ ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL;
+ ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL;
+ ImGuiDockNode* dock_node = window ? window->DockNode : NULL;
+ bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow);
- // 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);
+ // 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)
+ // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window.
+ if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
+ if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host)
+ ClearActiveID();
- // 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);
- return pos;
-}
+ // Passing NULL allow to disable keyboard focus
+ if (!window)
+ return;
+ window->LastFrameJustFocused = g.FrameCount;
-// Note that this is used for popups, which can overlap the non work-area of individual viewports.
-ImRect ImGui::GetPopupAllowedExtentRect(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
- {
- // Use the full viewport area (not work area) for popups
- r_screen = window->Viewport->GetMainRect();
- }
- ImVec2 padding = g.Style.DisplaySafeAreaPadding;
- 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;
+ // Select in dock node
+ // For #2304 we avoid applying focus immediately before the tabbar is visible.
+ //if (dock_node && dock_node->TabBar)
+ // dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId;
+
+ // Bring to front
+ BringWindowToFocusFront(focus_front_window);
+ if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
+ BringWindowToDisplayFront(display_front_window);
}
-ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
+void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags)
{
ImGuiContext& g = *GImGui;
-
- ImRect r_outer = GetPopupAllowedExtentRect(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;
- float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
- ImRect r_avoid;
- if (parent_window->DC.MenuBarAppending)
- r_avoid = ImRect(-FLT_MAX, parent_window->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, ImGuiPopupPositionPolicy_Default);
- }
- if (window->Flags & ImGuiWindowFlags_Popup)
+ int start_idx = g.WindowsFocusOrder.Size - 1;
+ if (under_this_window != NULL)
{
- return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
+ // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
+ int offset = -1;
+ while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
+ {
+ under_this_window = under_this_window->ParentWindow;
+ offset = 0;
+ }
+ start_idx = FindWindowFocusIndex(under_this_window) + offset;
}
- if (window->Flags & ImGuiWindowFlags_Tooltip)
+ for (int i = start_idx; i >= 0; i--)
{
- // Position tooltip (always follows mouse + clamp within outer boundaries)
- // FIXME:
- // - Too many paths. One problem is that FindBestWindowPosForPopupEx() doesn't allow passing a suggested position (so touch screen path doesn't use it by default).
- // - Drag and drop tooltips are not using this path either: BeginTooltipEx() manually sets their position.
- // - Require some tidying up. In theory we could handle both cases in same location, but requires a bit of shuffling
- // as drag and drop tooltips are calling SetNextWindowPos() leading to 'window_pos_set_by_api' being set in Begin().
- IM_ASSERT(g.CurrentWindow == window);
- const float scale = g.Style.MouseCursorScale;
- const ImVec2 ref_pos = NavCalcPreferredRefPos();
-
- if (g.IO.MouseSource == ImGuiMouseSource_TouchScreen && NavCalcPreferredRefPosSource() == ImGuiInputSource_Mouse)
+ // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
+ ImGuiWindow* window = g.WindowsFocusOrder[i];
+ if (window == ignore_window || !window->WasActive)
+ continue;
+ if (filter_viewport != NULL && window->Viewport != filter_viewport)
+ continue;
+ if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
{
- ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET_TOUCH * scale - (TOOLTIP_DEFAULT_PIVOT_TOUCH * window->Size);
- if (r_outer.Contains(ImRect(tooltip_pos, tooltip_pos + window->Size)))
- return tooltip_pos;
+ // FIXME-DOCK: When ImGuiFocusRequestFlags_RestoreFocusedChild is set...
+ // 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?
+ FocusWindow(window, flags);
+ return;
}
-
- ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET_MOUSE * scale;
- ImRect r_avoid;
- if (g.NavCursorVisible && g.NavHighlightItemUnderNav && !g.IO.ConfigNavMoveSetMousePos)
- 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 * scale, ref_pos.y + 24 * scale); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
- //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255, 0, 255, 255));
-
- return FindBestWindowPosForPopupEx(tooltip_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
}
- IM_ASSERT(0);
- return window->Pos;
+ FocusWindow(NULL, flags);
}
//-----------------------------------------------------------------------------
@@ -13012,7 +13617,7 @@ static float inline NavScoreItemDistInterval(float cand_min, float cand_max, flo
}
// Scoring function for keyboard/gamepad directional navigation. Based on https://gist.github.com/rygorous/6981057
-static bool ImGui::NavScoreItem(ImGuiNavItemData* result)
+static bool ImGui::NavScoreItem(ImGuiNavItemData* result, const ImRect& nav_bb)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
@@ -13020,7 +13625,7 @@ static bool ImGui::NavScoreItem(ImGuiNavItemData* result)
return false;
// FIXME: Those are not good variables names
- ImRect cand = g.LastItemData.NavRect; // Current item nav rectangle
+ ImRect cand = nav_bb; // Current item nav rectangle
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.NavScoringDebugCount++;
@@ -13187,13 +13792,13 @@ static void ImGui::NavProcessItem()
const ImGuiID id = g.LastItemData.ID;
const ImGuiItemFlags item_flags = g.LastItemData.ItemFlags;
- // When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221)
+ // When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221, #8816)
+ ImRect nav_bb = g.LastItemData.NavRect;
if (window->DC.NavIsScrollPushableX == false)
{
- g.LastItemData.NavRect.Min.x = ImClamp(g.LastItemData.NavRect.Min.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
- g.LastItemData.NavRect.Max.x = ImClamp(g.LastItemData.NavRect.Max.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
+ nav_bb.Min.x = ImClamp(nav_bb.Min.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
+ nav_bb.Max.x = ImClamp(nav_bb.Max.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
}
- const ImRect nav_bb = g.LastItemData.NavRect;
// Process Init Request
if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
@@ -13225,14 +13830,14 @@ static void ImGui::NavProcessItem()
else if (g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId))
{
ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
- if (NavScoreItem(result))
+ if (NavScoreItem(result, nav_bb))
NavApplyItemToResult(result);
// Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
const float VISIBLE_RATIO = 0.70f;
if ((g.NavMoveFlags & 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.NavMoveResultLocalVisible))
+ if (NavScoreItem(&g.NavMoveResultLocalVisible, nav_bb))
NavApplyItemToResult(&g.NavMoveResultLocalVisible);
}
}
@@ -13362,8 +13967,8 @@ void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
NavUpdateAnyRequestFlag();
}
-// Called by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsBackHere
-void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, ImGuiTreeNodeStackData* tree_node_data)
+// Called by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsToParent
+void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, const ImGuiTreeNodeStackData* tree_node_data)
{
ImGuiContext& g = *GImGui;
g.NavMoveScoringItems = false;
@@ -13516,6 +14121,9 @@ static ImVec2 ImGui::NavCalcPreferredRefPos()
const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID;
+ if (source != ImGuiInputSource_Mouse && !activated_shortcut && window == NULL)
+ source = ImGuiInputSource_Mouse;
+
// Testing for !activated_shortcut here could in theory be removed if we decided that activating a remote shortcut altered one of the g.NavDisableXXX flag.
if (source == ImGuiInputSource_Mouse)
{
@@ -13531,11 +14139,11 @@ static ImVec2 ImGui::NavCalcPreferredRefPos()
ImRect ref_rect;
if (activated_shortcut)
ref_rect = g.LastItemData.NavRect;
- else
+ else if (window != NULL)
ref_rect = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]);
// Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
- if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
+ if (window != NULL && window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
{
ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
ref_rect.Translate(window->Scroll - next_scroll);
@@ -13695,7 +14303,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 = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
+ const float scroll_speed = IM_ROUND(window->FontRefSize * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
const ImGuiDir move_dir = g.NavMoveDir;
if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY && move_dir != ImGuiDir_None)
{
@@ -13885,8 +14493,8 @@ void ImGui::NavUpdateCreateMoveRequest()
if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
{
IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
- float pad_x = ImMin(inner_rect_rel.GetWidth(), window->CalcFontSize() * 0.5f);
- float pad_y = ImMin(inner_rect_rel.GetHeight(), window->CalcFontSize() * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item
+ float pad_x = ImMin(inner_rect_rel.GetWidth(), window->FontRefSize * 0.5f);
+ float pad_y = ImMin(inner_rect_rel.GetHeight(), window->FontRefSize * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item
inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
@@ -13896,6 +14504,7 @@ void ImGui::NavUpdateCreateMoveRequest()
}
}
+ // Prepare scoring rectangle.
// 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 scoring_rect;
if (window != NULL)
@@ -13910,7 +14519,7 @@ void ImGui::NavUpdateCreateMoveRequest()
//if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
}
g.NavScoringRect = scoring_rect;
- g.NavScoringNoClipRect.Add(scoring_rect);
+ //g.NavScoringNoClipRect.Add(scoring_rect);
}
void ImGui::NavUpdateCreateTabbingRequest()
@@ -14045,6 +14654,8 @@ void ImGui::NavMoveRequestApplyResult()
{
g.NavNextActivateId = result->ID;
g.NavNextActivateFlags = ImGuiActivateFlags_None;
+ if (g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi)
+ g.NavNextActivateFlags |= ImGuiActivateFlags_FromFocusApi;
if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
g.NavNextActivateFlags |= ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState | ImGuiActivateFlags_FromTabbing;
}
@@ -14129,7 +14740,7 @@ static float ImGui::NavUpdatePageUpPageDown()
if (g.NavLayer != ImGuiNavLayer_Main)
NavRestoreLayer(ImGuiNavLayer_Main);
- if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY)
+ if ((window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Main)) == 0 && window->DC.NavWindowHasScrollY)
{
// Fallback manual-scroll when window has no navigable item
if (IsKeyPressed(ImGuiKey_PageUp, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner))
@@ -14144,7 +14755,7 @@ static float ImGui::NavUpdatePageUpPageDown()
else
{
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());
+ const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->FontRefSize * 1.0f + nav_rect_rel.GetHeight());
float nav_scoring_rect_offset_y = 0.0f;
if (IsKeyPressed(ImGuiKey_PageUp, true))
{
@@ -14260,14 +14871,12 @@ static void ImGui::NavUpdateCreateWrappingRequest()
NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags);
}
-static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
+// 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 programmatically.
+// If you want a window to never be focused, you may use the e.g. NoInputs flag.
+bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
{
- ImGuiContext& g = *GImGui;
- IM_UNUSED(g);
- int order = window->FocusOrder;
- IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
- IM_ASSERT(g.WindowsFocusOrder[order] == window);
- return order;
+ return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
}
static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
@@ -14298,6 +14907,41 @@ static void NavUpdateWindowingTarget(int focus_change_dir)
g.NavWindowingToggleLayer = false;
}
+// Apply focus and close overlay
+static void ImGui::NavUpdateWindowingApplyFocus(ImGuiWindow* apply_focus_window)
+{
+ // FIXME: Many actions here could be part of a higher-level/reused function. Why aren't they in FocusWindow() ?
+ // Investigate for each of them: ClearActiveID(), NavRestoreHighlightAfterMove(), NavRestoreLastChildNavWindow(), ClosePopupsOverWindow(), NavInitWindow()
+ ImGuiContext& g = *GImGui;
+ if (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow)
+ {
+ ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
+ ClearActiveID();
+ SetNavCursorVisibleAfterMove();
+ ClosePopupsOverWindow(apply_focus_window, false);
+ FocusWindow(apply_focus_window, ImGuiFocusRequestFlags_RestoreFocusedChild);
+ IM_ASSERT(g.NavWindow != NULL);
+ apply_focus_window = g.NavWindow;
+ if (apply_focus_window->NavLastIds[0] == 0)
+ NavInitWindow(apply_focus_window, false);
+
+ // If the window has ONLY a menu layer (no main layer), select it directly
+ // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
+ // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
+ // the target window as already been previewed once.
+ // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
+ // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
+ // won't be valid.
+ if (apply_focus_window->DC.NavLayersActiveMaskNext == (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);
+ }
+ g.NavWindowingTarget = NULL;
+}
+
// Windowing management mode
// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
// Gamepad: Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
@@ -14324,22 +14968,29 @@ static void ImGui::NavUpdateWindowing()
// Start CTRL+Tab or Square+L/R window selection
// (g.ConfigNavWindowingKeyNext/g.ConfigNavWindowingKeyPrev defaults are ImGuiMod_Ctrl|ImGuiKey_Tab and ImGuiMod_Ctrl|ImGuiMod_Shift|ImGuiKey_Tab)
- const ImGuiID owner_id = ImHashStr("###NavUpdateWindowing");
+ const ImGuiID owner_id = ImHashStr("##NavUpdateWindowing");
const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id);
const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id);
- const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && IsKeyPressed(ImGuiKey_NavGamepadMenu, ImGuiInputFlags_None);
+ const bool start_toggling_with_gamepad = nav_gamepad_active && !g.NavWindowingTarget && Shortcut(ImGuiKey_NavGamepadMenu, ImGuiInputFlags_RouteAlways, owner_id);
+ const bool start_windowing_with_gamepad = allow_windowing && start_toggling_with_gamepad;
const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
bool just_started_windowing_from_null_focus = false;
+ if (start_toggling_with_gamepad)
+ {
+ g.NavWindowingToggleLayer = true; // Gamepad starts toggling layer
+ g.NavWindowingToggleKey = ImGuiKey_NavGamepadMenu;
+ g.NavWindowingInputSource = g.NavInputSource = ImGuiInputSource_Gamepad;
+ }
if (start_windowing_with_gamepad || start_windowing_with_keyboard)
- if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
+ if (ImGuiWindow* window = (g.NavWindow && IsWindowNavFocusable(g.NavWindow)) ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
{
- g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow; // Current location
+ if (start_windowing_with_keyboard || g.ConfigNavWindowingWithGamepad)
+ g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow; // Current location
g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
- g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer
- g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
+ g.NavWindowingInputSource = g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
if (g.NavWindow == NULL)
just_started_windowing_from_null_focus = true;
@@ -14349,18 +15000,22 @@ static void ImGui::NavUpdateWindowing()
}
// Gamepad update
- g.NavWindowingTimer += io.DeltaTime;
- if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)
+ if ((g.NavWindowingTarget || g.NavWindowingToggleLayer) && g.NavWindowingInputSource == ImGuiInputSource_Gamepad)
{
- // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
- g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
-
- // Select window to focus
- const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1);
- if (focus_change_dir != 0 && !just_started_windowing_from_null_focus)
+ if (g.NavWindowingTarget != NULL)
{
- NavUpdateWindowingTarget(focus_change_dir);
- g.NavWindowingHighlightAlpha = 1.0f;
+ // Highlight only appears after a brief time holding the button, so that a fast tap on ImGuiKey_NavGamepadMenu (to toggle NavLayer) doesn't add visual noise
+ // However inputs are accepted immediately, so you press ImGuiKey_NavGamepadMenu + L1/R1 fast.
+ g.NavWindowingTimer += io.DeltaTime;
+ g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
+
+ // Select window to focus
+ const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1);
+ if (focus_change_dir != 0 && !just_started_windowing_from_null_focus)
+ {
+ NavUpdateWindowingTarget(focus_change_dir);
+ g.NavWindowingHighlightAlpha = 1.0f;
+ }
}
// Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
@@ -14372,15 +15027,17 @@ static void ImGui::NavUpdateWindowing()
else if (!g.NavWindowingToggleLayer)
apply_focus_window = g.NavWindowingTarget;
g.NavWindowingTarget = NULL;
+ g.NavWindowingToggleLayer = false;
}
}
// Keyboard: Focus
- if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard)
+ if (g.NavWindowingTarget && g.NavWindowingInputSource == ImGuiInputSource_Keyboard)
{
// Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_;
IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows.
+ g.NavWindowingTimer += io.DeltaTime;
g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
if ((keyboard_next_window || keyboard_prev_window) && !just_started_windowing_from_null_focus)
NavUpdateWindowingTarget(keyboard_next_window ? -1 : +1);
@@ -14391,16 +15048,17 @@ static void ImGui::NavUpdateWindowing()
// Keyboard: Press and Release ALT to toggle menu layer
const ImGuiKey windowing_toggle_keys[] = { ImGuiKey_LeftAlt, ImGuiKey_RightAlt };
bool windowing_toggle_layer_start = false;
- for (ImGuiKey windowing_toggle_key : windowing_toggle_keys)
- if (nav_keyboard_active && IsKeyPressed(windowing_toggle_key, 0, ImGuiKeyOwner_NoOwner))
- {
- windowing_toggle_layer_start = true;
- g.NavWindowingToggleLayer = true;
- g.NavWindowingToggleKey = windowing_toggle_key;
- g.NavInputSource = ImGuiInputSource_Keyboard;
- break;
- }
- if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard)
+ if (g.NavWindow != NULL && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
+ for (ImGuiKey windowing_toggle_key : windowing_toggle_keys)
+ if (nav_keyboard_active && IsKeyPressed(windowing_toggle_key, 0, ImGuiKeyOwner_NoOwner))
+ {
+ windowing_toggle_layer_start = true;
+ g.NavWindowingToggleLayer = true;
+ g.NavWindowingToggleKey = windowing_toggle_key;
+ g.NavWindowingInputSource = g.NavInputSource = ImGuiInputSource_Keyboard;
+ break;
+ }
+ if (g.NavWindowingToggleLayer && g.NavWindowingInputSource == ImGuiInputSource_Keyboard)
{
// We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
// We cancel toggling nav layer when other modifiers are pressed. (See #4439)
@@ -14448,35 +15106,8 @@ static void ImGui::NavUpdateWindowing()
}
// Apply final focus
- if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
- {
- // FIXME: Many actions here could be part of a higher-level/reused function. Why aren't they in FocusWindow()
- // Investigate for each of them: ClearActiveID(), NavRestoreHighlightAfterMove(), NavRestoreLastChildNavWindow(), ClosePopupsOverWindow(), NavInitWindow()
- ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
- ClearActiveID();
- SetNavCursorVisibleAfterMove();
- ClosePopupsOverWindow(apply_focus_window, false);
- FocusWindow(apply_focus_window, ImGuiFocusRequestFlags_RestoreFocusedChild);
- apply_focus_window = g.NavWindow;
- if (apply_focus_window->NavLastIds[0] == 0)
- NavInitWindow(apply_focus_window, false);
-
- // If the window has ONLY a menu layer (no main layer), select it directly
- // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
- // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
- // the target window as already been previewed once.
- // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
- // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
- // won't be valid.
- if (apply_focus_window->DC.NavLayersActiveMaskNext == (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;
+ NavUpdateWindowingApplyFocus(apply_focus_window);
// Apply menu/layer toggle
if (apply_toggle_layer && g.NavWindow)
@@ -14533,12 +15164,12 @@ void ImGui::NavUpdateWindowingOverlay()
return;
if (g.NavWindowingListWindow == NULL)
- g.NavWindowingListWindow = FindWindowByName("###NavWindowingList");
+ g.NavWindowingListWindow = FindWindowByName("##NavWindowingOverlay");
const ImGuiViewport* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ GetMainViewport();
SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
SetNextWindowPos(viewport->GetCenter(), 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);
+ Begin("##NavWindowingOverlay", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
if (g.ContextName[0] != 0)
SeparatorText(g.ContextName);
for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
@@ -14556,7 +15187,6 @@ void ImGui::NavUpdateWindowingOverlay()
PopStyleVar();
}
-
//-----------------------------------------------------------------------------
// [SECTION] DRAG AND DROP
//-----------------------------------------------------------------------------
@@ -14741,7 +15371,7 @@ bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_s
cond = ImGuiCond_Always;
IM_ASSERT(type != NULL);
- IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
+ IM_ASSERT(ImStrlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
@@ -14894,7 +15524,7 @@ void ImGui::RenderDragDropTargetRect(const ImRect& bb, const ImRect& item_clip_r
bool push_clip_rect = !window->ClipRect.Contains(bb_display);
if (push_clip_rect)
window->DrawList->PushClipRectFullScreen();
- window->DrawList->AddRect(bb_display.Min, bb_display.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
+ window->DrawList->AddRect(bb_display.Min, bb_display.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f); // FIXME-DPI
if (push_clip_rect)
window->DrawList->PopClipRect();
}
@@ -14985,7 +15615,7 @@ void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char*
}
if (prefix)
- LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure "##" are included here.
+ LogRenderedText(ref_pos, prefix, prefix + ImStrlen(prefix)); // Calculate end ourself to ensure "##" are included here.
// Re-adjust padding if we have popped out of our starting depth
if (g.LogDepthRef > window->DC.TreeDepth)
@@ -15018,19 +15648,21 @@ void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char*
}
if (suffix)
- LogRenderedText(ref_pos, suffix, suffix + strlen(suffix));
+ LogRenderedText(ref_pos, suffix, suffix + ImStrlen(suffix));
}
// Start logging/capturing text output
-void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
+void ImGui::LogBegin(ImGuiLogFlags flags, int auto_open_depth)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(g.LogEnabled == false);
- IM_ASSERT(g.LogFile == NULL);
- IM_ASSERT(g.LogBuffer.empty());
+ IM_ASSERT(g.LogFile == NULL && g.LogBuffer.empty());
+ IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiLogFlags_OutputMask_)); // Check that only 1 type flag is used
+
g.LogEnabled = g.ItemUnclipByLog = true;
- g.LogType = type;
+ g.LogFlags = flags;
+ g.LogWindow = window;
g.LogNextPrefix = g.LogNextSuffix = NULL;
g.LogDepthRef = window->DC.TreeDepth;
g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
@@ -15053,7 +15685,7 @@ void ImGui::LogToTTY(int auto_open_depth)
return;
IM_UNUSED(auto_open_depth);
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
- LogBegin(ImGuiLogType_TTY, auto_open_depth);
+ LogBegin(ImGuiLogFlags_OutputTTY, auto_open_depth);
g.LogFile = stdout;
#endif
}
@@ -15079,7 +15711,7 @@ void ImGui::LogToFile(int auto_open_depth, const char* filename)
return;
}
- LogBegin(ImGuiLogType_File, auto_open_depth);
+ LogBegin(ImGuiLogFlags_OutputFile, auto_open_depth);
g.LogFile = f;
}
@@ -15089,7 +15721,7 @@ void ImGui::LogToClipboard(int auto_open_depth)
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
- LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
+ LogBegin(ImGuiLogFlags_OutputClipboard, auto_open_depth);
}
void ImGui::LogToBuffer(int auto_open_depth)
@@ -15097,7 +15729,7 @@ void ImGui::LogToBuffer(int auto_open_depth)
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
- LogBegin(ImGuiLogType_Buffer, auto_open_depth);
+ LogBegin(ImGuiLogFlags_OutputBuffer, auto_open_depth);
}
void ImGui::LogFinish()
@@ -15107,29 +15739,29 @@ void ImGui::LogFinish()
return;
LogText(IM_NEWLINE);
- switch (g.LogType)
+ switch (g.LogFlags & ImGuiLogFlags_OutputMask_)
{
- case ImGuiLogType_TTY:
+ case ImGuiLogFlags_OutputTTY:
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
fflush(g.LogFile);
#endif
break;
- case ImGuiLogType_File:
+ case ImGuiLogFlags_OutputFile:
ImFileClose(g.LogFile);
break;
- case ImGuiLogType_Buffer:
+ case ImGuiLogFlags_OutputBuffer:
break;
- case ImGuiLogType_Clipboard:
+ case ImGuiLogFlags_OutputClipboard:
if (!g.LogBuffer.empty())
SetClipboardText(g.LogBuffer.begin());
break;
- case ImGuiLogType_None:
+ default:
IM_ASSERT(0);
break;
}
g.LogEnabled = g.ItemUnclipByLog = false;
- g.LogType = ImGuiLogType_None;
+ g.LogFlags = ImGuiLogFlags_None;
g.LogFile = NULL;
g.LogBuffer.clear();
}
@@ -15163,7 +15795,6 @@ void ImGui::LogButtons()
LogToClipboard();
}
-
//-----------------------------------------------------------------------------
// [SECTION] SETTINGS
//-----------------------------------------------------------------------------
@@ -15283,7 +15914,7 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
// 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);
+ ini_size = ImStrlen(ini_data);
g.SettingsIniData.Buf.resize((int)ini_size + 1);
char* const buf = g.SettingsIniData.Buf.Data;
char* const buf_end = buf + ini_size;
@@ -15377,14 +16008,10 @@ ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
{
ImGuiContext& g = *GImGui;
+ // Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier.
if (g.IO.ConfigDebugIniSettings == false)
- {
- // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
- // Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier.
- if (const char* p = strstr(name, "###"))
- name = p;
- }
- const size_t name_len = strlen(name);
+ name = ImHashSkipUncontributingPrefix(name);
+ const size_t name_len = ImStrlen(name);
// Allocate chunk
const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
@@ -15554,7 +16181,6 @@ static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandl
}
}
-
//-----------------------------------------------------------------------------
// [SECTION] LOCALIZATION
//-----------------------------------------------------------------------------
@@ -15566,7 +16192,6 @@ void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count)
g.LocalizationTable[entries[n].Key] = entries[n].Text;
}
-
//-----------------------------------------------------------------------------
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
//-----------------------------------------------------------------------------
@@ -15631,7 +16256,10 @@ void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* view
return;
g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f;
g.CurrentViewport = viewport;
+ IM_ASSERT(g.CurrentDpiScale > 0.0f && g.CurrentDpiScale < 99.0f); // Typical correct values would be between 1.0f and 4.0f
//IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0);
+ if (g.IO.ConfigDpiScaleFonts)
+ g.Style.FontScaleDpi = g.CurrentDpiScale;
// Notify platform layer of viewport changes
// FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
@@ -15711,6 +16339,7 @@ static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window)
void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos, const ImVec2& old_size, const ImVec2& new_size)
{
ImGuiContext& g = *GImGui;
+ //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] TranslateWindowsInViewport 0x%08X\n", viewport->ID);
IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows));
// 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently
@@ -15719,7 +16348,7 @@ void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& o
// 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);
+ ImRect test_still_fit_rect(old_pos, old_pos + old_size);
ImVec2 delta_pos = new_pos - old_pos;
for (ImGuiWindow* window : g.Windows) // FIXME-OPT
if (translate_all_windows || (window->Viewport == viewport && (old_size == new_size || test_still_fit_rect.Contains(window->Rect()))))
@@ -15730,6 +16359,7 @@ void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& o
void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
{
ImGuiContext& g = *GImGui;
+ //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] ScaleWindowsInViewport 0x%08X\n", viewport->ID);
if (viewport->Window)
{
ScaleWindow(viewport->Window, scale);
@@ -15798,7 +16428,7 @@ static void ImGui::UpdateViewportsNewFrame()
// Focused viewport has changed?
if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID)
{
- IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Focused viewport changed %08X -> %08X, attempting to apply our focus.\n", g.PlatformLastFocusedViewportId, focused_viewport->ID);
+ IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Focused viewport changed %08X -> %08X '%s', attempting to apply our focus.\n", g.PlatformLastFocusedViewportId, focused_viewport->ID, focused_viewport->Window ? focused_viewport->Window->Name : "n/a");
const ImGuiViewport* prev_focused_viewport = FindViewportByID(g.PlatformLastFocusedViewportId);
const bool prev_focused_has_been_destroyed = (prev_focused_viewport == NULL) || (prev_focused_viewport->PlatformWindowCreated == false);
@@ -15814,7 +16444,7 @@ static void ImGui::UpdateViewportsNewFrame()
// - if focus didn't happen because we destroyed another window (#6462)
// FIXME: perhaps 'FocusTopMostWindowUnderOne()' can handle the 'focused_window->Window != NULL' case as well.
const bool apply_imgui_focus_on_focused_viewport = !IsAnyMouseDown() && !prev_focused_has_been_destroyed;
- if (apply_imgui_focus_on_focused_viewport)
+ if (apply_imgui_focus_on_focused_viewport && g.IO.ConfigViewportPlatformFocusSetsImGuiFocus)
{
focused_viewport->LastFocusedHadNavWindow |= (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport); // Update so a window changing viewport won't lose focus.
ImGuiFocusRequestFlags focus_request_flags = ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild;
@@ -15837,10 +16467,12 @@ static void ImGui::UpdateViewportsNewFrame()
IM_ASSERT(main_viewport->Window == NULL);
ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f);
ImVec2 main_viewport_size = g.IO.DisplaySize;
+ ImVec2 main_viewport_framebuffer_scale = g.IO.DisplayFramebufferScale;
if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_IsMinimized))
{
- main_viewport_pos = main_viewport->Pos; // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path)
+ main_viewport_pos = main_viewport->Pos; // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path)
main_viewport_size = main_viewport->Size;
+ main_viewport_framebuffer_scale = main_viewport->FramebufferScale;
}
AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows);
@@ -15872,6 +16504,8 @@ static void ImGui::UpdateViewportsNewFrame()
viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
if (viewport->PlatformRequestResize)
viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport);
+ if (g.PlatformIO.Platform_GetWindowFramebufferScale != NULL)
+ viewport->FramebufferScale = g.PlatformIO.Platform_GetWindowFramebufferScale(viewport);
}
}
@@ -15909,10 +16543,11 @@ static void ImGui::UpdateViewportsNewFrame()
new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
else
new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
+ IM_ASSERT(new_dpi_scale > 0.0f && new_dpi_scale < 99.0f); // Typical correct values would be between 1.0f and 4.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)
+ if (g.IO.ConfigDpiScaleViewports)
ScaleWindowsInViewport(viewport, scale_factor);
//if (viewport == GetMainViewport())
// g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
@@ -16031,9 +16666,10 @@ ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const
flags |= ImGuiViewportFlags_IsPlatformWindow;
if (window != NULL)
{
+ const bool window_can_use_inputs = ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs)) == false;
if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window)
flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing;
- if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs))
+ if (!window_can_use_inputs)
flags |= ImGuiViewportFlags_NoInputs;
if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing)
flags |= ImGuiViewportFlags_NoFocusOnAppearing;
@@ -16043,11 +16679,15 @@ ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const
if (viewport)
{
// Always update for main viewport as we are already pulling correct platform pos/size (see #4900)
+ ImVec2 prev_pos = viewport->Pos;
+ ImVec2 prev_size = viewport->Size;
if (!viewport->PlatformRequestMove || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
viewport->Pos = pos;
if (!viewport->PlatformRequestResize || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
viewport->Size = size;
viewport->Flags = flags | (viewport->Flags & (ImGuiViewportFlags_IsMinimized | ImGuiViewportFlags_IsFocused)); // Preserve existing flags
+ if (prev_pos != viewport->Pos || prev_size != viewport->Size)
+ UpdateViewportPlatformMonitor(viewport);
}
else
{
@@ -16072,8 +16712,7 @@ ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const
// 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->DpiScale = GetViewportPlatformMonitor(viewport)->DpiScale;
}
viewport->Window = window;
@@ -16133,7 +16772,7 @@ static void ImGui::WindowSelectViewport(ImGuiWindow* window)
window->ViewportId = 0;
}
- if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0)
+ if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasViewport) == 0)
{
// By default inherit from parent window
if (window->Viewport == NULL && window->ParentWindow && (!window->ParentWindow->IsFallbackWindow || window->ParentWindow->WasActive))
@@ -16149,7 +16788,7 @@ static void ImGui::WindowSelectViewport(ImGuiWindow* window)
}
bool lock_viewport = false;
- if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport)
+ if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasViewport)
{
// Code explicitly request a viewport
window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId);
@@ -16499,7 +17138,7 @@ static int ImGui::FindPlatformMonitorForRect(const ImRect& rect)
// 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;
+ int best_monitor_n = 0; // Default to the first monitor as fallback
float best_monitor_surface = 0.001f;
for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++)
@@ -17067,7 +17706,7 @@ static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx)
{
ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID);
- if (data->CountWindows > 1)
+ if (data == NULL || data->CountWindows > 1)
continue;
ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(data->RootId);
@@ -18012,7 +18651,7 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
node->HasCloseButton |= window->HasCloseButton;
window->DockIsActive = (node->Windows.Size > 1);
}
- if (node_flags & ImGuiDockNodeFlags_NoCloseButton)
+ if ((node_flags & ImGuiDockNodeFlags_NoCloseButton) || !g.Style.DockingNodeHasCloseButton)
node->HasCloseButton = false;
// Bind or create host window
@@ -18129,10 +18768,10 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
ImGuiDockNode* root_node = DockNodeGetRootNode(central_node);
ImRect root_rect(root_node->Pos, root_node->Pos + root_node->Size);
ImRect hole_rect(central_node->Pos, central_node->Pos + central_node->Size);
- if (hole_rect.Min.x > root_rect.Min.x) { hole_rect.Min.x += WINDOWS_HOVER_PADDING; }
- if (hole_rect.Max.x < root_rect.Max.x) { hole_rect.Max.x -= WINDOWS_HOVER_PADDING; }
- if (hole_rect.Min.y > root_rect.Min.y) { hole_rect.Min.y += WINDOWS_HOVER_PADDING; }
- if (hole_rect.Max.y < root_rect.Max.y) { hole_rect.Max.y -= WINDOWS_HOVER_PADDING; }
+ if (hole_rect.Min.x > root_rect.Min.x) { hole_rect.Min.x += g.WindowsBorderHoverPadding; }
+ if (hole_rect.Max.x < root_rect.Max.x) { hole_rect.Max.x -= g.WindowsBorderHoverPadding; }
+ if (hole_rect.Min.y > root_rect.Min.y) { hole_rect.Min.y += g.WindowsBorderHoverPadding; }
+ if (hole_rect.Max.y < root_rect.Max.y) { hole_rect.Max.y -= g.WindowsBorderHoverPadding; }
//GetForegroundDrawList()->AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255));
if (central_node_hole && !hole_rect.IsInverted())
{
@@ -18330,8 +18969,6 @@ static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_w
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;
@@ -18443,6 +19080,7 @@ static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_w
for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++)
{
ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
+ IM_UNUSED(tab);
IMGUI_DEBUG_LOG_DOCKING("[docking] - Tab 0x%08X '%s' Order %d\n", tab->ID, TabBarGetTabName(tab_bar, tab), tab->Window ? tab->Window->DockOrder : -1);
}
IMGUI_DEBUG_LOG_DOCKING("[docking] SelectedTabId = 0x%08X, NavWindow->TabId = 0x%08X\n", node->SelectedTabId, g.NavWindow ? g.NavWindow->TabId : -1);
@@ -18462,7 +19100,8 @@ static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_w
// Begin tab bar
ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons);
- tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;// | ImGuiTabBarFlags_FittingPolicyScroll;
+ tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;
+ tab_bar_flags |= ImGuiTabBarFlags_FittingPolicyMixed; // Enforce default policy. Since 1.92.2 this is now reasonable. May expose later if needed. (#8800, #3421)
tab_bar_flags |= ImGuiTabBarFlags_DrawSelectedOverline;
if (!host_window->Collapsed && is_focused)
tab_bar_flags |= ImGuiTabBarFlags_IsFocused;
@@ -18482,37 +19121,35 @@ static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_w
for (int window_n = 0; window_n < node->Windows.Size; window_n++)
{
ImGuiWindow* window = node->Windows[window_n];
- if ((closed_all || closed_one == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument))
- continue;
- if (window->LastFrameActive + 1 >= g.FrameCount || !node_was_active)
- {
- ImGuiTabItemFlags tab_item_flags = 0;
- tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet;
- if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
- tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
- if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
- tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
+ if (window->LastFrameActive + 1 < g.FrameCount && node_was_active)
+ continue; // FIXME: Not sure if that's still taken/useful.
- // Apply stored style overrides for the window
- for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
- g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(window->DockStyle.Colors[color_n]);
+ ImGuiTabItemFlags tab_item_flags = 0;
+ tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet;
+ if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
+ tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
+ if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
+ tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
- // Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so)
- bool tab_open = true;
- TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window);
- if (!tab_open)
- node->WantCloseTabId = window->TabId;
- if (tab_bar->VisibleTabId == window->TabId)
- node->VisibleWindow = window;
+ // Apply stored style overrides for the window
+ for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
+ g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(window->DockStyle.Colors[color_n]);
- // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
- window->DockTabItemStatusFlags = g.LastItemData.StatusFlags;
- window->DockTabItemRect = g.LastItemData.Rect;
+ // Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so)
+ bool tab_open = true;
+ TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window);
+ if (!tab_open)
+ node->WantCloseTabId = window->TabId;
+ if (tab_bar->VisibleTabId == window->TabId)
+ node->VisibleWindow = window;
- // Update navigation ID on menu layer
- if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0)
- host_window->NavLastIds[1] = window->TabId;
- }
+ // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
+ window->DC.DockTabItemStatusFlags = g.LastItemData.StatusFlags;
+ window->DC.DockTabItemRect = g.LastItemData.Rect;
+
+ // Update navigation ID on menu layer
+ if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0)
+ host_window->NavLastIds[1] = window->TabId;
}
// Restore style colors
@@ -19283,7 +19920,7 @@ void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node)
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];
ImU32 bg_col = GetColorU32(ImGuiCol_WindowBg);
- if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, WINDOWS_HOVER_PADDING, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER, bg_col))
+ if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, g.WindowsBorderHoverPadding, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER, bg_col))
{
if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0)
{
@@ -19426,7 +20063,9 @@ ImGuiID ImGui::DockSpace(ImGuiID dockspace_id, const ImVec2& size_arg, ImGuiDock
if ((flags & ImGuiDockNodeFlags_KeepAliveOnly) == 0)
window = GetCurrentWindow(); // call to set window->WriteAccessed = true;
- IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0);
+ IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0); // Flag is automatically set by DockSpace() as LocalFlags, not SharedFlags!
+ IM_ASSERT((flags & ImGuiDockNodeFlags_CentralNode) == 0); // Flag is automatically set by DockSpace() as LocalFlags, not SharedFlags! (#8145)
+
IM_ASSERT(dockspace_id != 0);
ImGuiDockNode* node = DockContextFindNodeByID(&g, dockspace_id);
if (node == NULL)
@@ -19535,6 +20174,11 @@ ImGuiID ImGui::DockSpaceOverViewport(ImGuiID dockspace_id, const ImGuiViewport*
if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
host_window_flags |= ImGuiWindowFlags_NoBackground;
+ // FIXME-OPT: When using ImGuiDockNodeFlags_KeepAliveOnly with DockSpaceOverViewport() we might be able to spare submitting the window,
+ // since DockSpace() with that flag doesn't need a window. We'd only need to compute the default ID accordingly.
+ if (dockspace_flags & ImGuiDockNodeFlags_KeepAliveOnly)
+ host_window_flags |= ImGuiWindowFlags_NoMouseInputs;
+
char label[32];
ImFormatString(label, IM_ARRAYSIZE(label), "WindowOverViewport_%08X", viewport->ID);
@@ -19800,8 +20444,6 @@ ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_r
return 0;
}
- IM_ASSERT(!node->IsSplitNode()); // Assert if already Split
-
ImGuiDockRequest req;
req.Type = ImGuiDockRequestType_Split;
req.DockTargetWindow = NULL;
@@ -20078,7 +20720,7 @@ void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open)
// 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;
+ want_undock |= (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock;
if (want_undock)
{
DockContextProcessUndockWindow(&g, window);
@@ -20196,7 +20838,7 @@ void ImGui::BeginDockableDragDropSource(ImGuiWindow* window)
// When ConfigDockingWithShift is set, display a tooltip to increase UI affordance.
// We cannot set for HoveredWindowUnderMovingWindow != NULL here, as it is only valid/useful when drag and drop is already active
// (because of the 'is_mouse_dragging_with_an_expected_destination' logic in UpdateViewportsNewFrame() function)
- IM_ASSERT(g.NextWindowData.Flags == 0);
+ IM_ASSERT(g.NextWindowData.HasFlags == 0);
if (g.IO.ConfigDockingWithShift && g.MouseStationaryTimer >= 1.0f && g.ActiveId >= 1.0f)
SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingHoldShiftToDock));
return;
@@ -20594,7 +21236,7 @@ static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext*, const char* t
if (!main_clipboard)
PasteboardCreate(kPasteboardClipboard, &main_clipboard);
PasteboardClear(main_clipboard);
- CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
+ CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, ImStrlen(text));
if (cf_data)
{
PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
@@ -20648,7 +21290,7 @@ static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext* ctx, const cha
{
ImGuiContext& g = *ctx;
g.ClipboardHandlerData.clear();
- const char* text_end = text + strlen(text);
+ const char* text_end = text + ImStrlen(text);
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;
@@ -20662,11 +21304,13 @@ static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext* ctx, const cha
#if defined(__APPLE__) && TARGET_OS_IPHONE
#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
#endif
-
-#if defined(_WIN32) && defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
+#if defined(__3DS__)
#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
#endif
+#if defined(_WIN32) && defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
+#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
#endif
+#endif // #ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
#ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
#ifdef _WIN32
@@ -20676,7 +21320,11 @@ static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext* ctx, const cha
#endif
static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext*, const char* path)
{
- return (INT_PTR)::ShellExecuteA(NULL, "open", path, NULL, NULL, SW_SHOWDEFAULT) > 32;
+ const int path_wsize = ::MultiByteToWideChar(CP_UTF8, 0, path, -1, NULL, 0);
+ ImVector<wchar_t> path_wbuf;
+ path_wbuf.resize(path_wsize);
+ ::MultiByteToWideChar(CP_UTF8, 0, path, -1, path_wbuf.Data, path_wsize);
+ return (INT_PTR)::ShellExecuteW(NULL, L"open", path_wbuf.Data, NULL, NULL, SW_SHOWDEFAULT) > 32;
}
#else
#include <sys/wait.h>
@@ -20751,11 +21399,16 @@ static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport*, ImG
//-----------------------------------------------------------------------------
// [SECTION] METRICS/DEBUGGER WINDOW
//-----------------------------------------------------------------------------
+// - MetricsHelpMarker() [Internal]
// - DebugRenderViewportThumbnail() [Internal]
// - RenderViewportsThumbnails() [Internal]
+// - DebugRenderKeyboardPreview() [Internal]
// - DebugTextEncoding()
-// - MetricsHelpMarker() [Internal]
-// - ShowFontAtlas() [Internal]
+// - DebugFlashStyleColorStop() [Internal]
+// - DebugFlashStyleColor()
+// - UpdateDebugToolFlashStyleColor() [Internal]
+// - ShowFontAtlas() [Internal but called by Demo!]
+// - DebugNodeTexture() [Internal]
// - ShowMetricsWindow()
// - DebugNodeColumns() [Internal]
// - DebugNodeDockNode() [Internal]
@@ -20770,8 +21423,24 @@ static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport*, ImG
// - DebugNodeWindowSettings() [Internal]
// - DebugNodeWindowsList() [Internal]
// - DebugNodeWindowsListByBeginStackParent() [Internal]
+// - ShowFontSelector()
//-----------------------------------------------------------------------------
+#if !defined(IMGUI_DISABLE_DEMO_WINDOWS) || !defined(IMGUI_DISABLE_DEBUG_TOOLS)
+// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
+static void MetricsHelpMarker(const char* desc)
+{
+ ImGui::TextDisabled("(?)");
+ if (ImGui::BeginItemTooltip())
+ {
+ ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
+ ImGui::TextUnformatted(desc);
+ ImGui::PopTextWrapPos();
+ ImGui::EndTooltip();
+ }
+}
+#endif
+
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
@@ -20917,10 +21586,12 @@ void ImGui::DebugTextEncoding(const char* str)
Text("0x%02X", (int)(unsigned char)p[byte_index]);
}
TableNextColumn();
- if (GetFont()->FindGlyphNoFallback((ImWchar)c))
- TextUnformatted(p, p + c_utf8_len);
- else
- TextUnformatted((c == IM_UNICODE_CODEPOINT_INVALID) ? "[invalid]" : "[missing]");
+ TextUnformatted(p, p + c_utf8_len);
+ if (!GetFont()->IsGlyphInFont((ImWchar)c))
+ {
+ SameLine();
+ TextUnformatted("[missing]");
+ }
TableNextColumn();
Text("U+%04X", (int)c);
p += c_utf8_len;
@@ -20957,38 +21628,214 @@ void ImGui::UpdateDebugToolFlashStyleColor()
DebugFlashStyleColorStop();
}
-// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
-static void MetricsHelpMarker(const char* desc)
+static const char* FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTextureID tex_id)
{
- ImGui::TextDisabled("(?)");
- if (ImGui::BeginItemTooltip())
- {
- ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
- ImGui::TextUnformatted(desc);
- ImGui::PopTextWrapPos();
- ImGui::EndTooltip();
- }
+ union { void* ptr; int integer; } tex_id_opaque;
+ memcpy(&tex_id_opaque, &tex_id, ImMin(sizeof(void*), sizeof(tex_id)));
+ if (sizeof(tex_id) >= sizeof(void*))
+ ImFormatString(buf, buf_size, "0x%p", tex_id_opaque.ptr);
+ else
+ ImFormatString(buf, buf_size, "0x%04X", tex_id_opaque.integer);
+ return buf;
+}
+
+static const char* FormatTextureRefForDebugDisplay(char* buf, int buf_size, ImTextureRef tex_ref)
+{
+ char* buf_end = buf + buf_size;
+ if (tex_ref._TexData != NULL)
+ buf += ImFormatString(buf, buf_end - buf, "#%03d: ", tex_ref._TexData->UniqueID);
+ return FormatTextureIDForDebugDisplay(buf, (int)(buf_end - buf), tex_ref.GetTexID()); // Calling TexRef::GetTexID() to avoid assert of cmd->GetTexID()
}
+#ifdef IMGUI_ENABLE_FREETYPE
+namespace ImGuiFreeType { IMGUI_API const ImFontLoader* GetFontLoader(); IMGUI_API bool DebugEditFontLoaderFlags(unsigned int* p_font_builder_flags); }
+#endif
+
// [DEBUG] List fonts in a font atlas and display its texture
void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
{
+ ImGuiContext& g = *GImGui;
+ ImGuiIO& io = g.IO;
+ ImGuiStyle& style = g.Style;
+
+ BeginDisabled();
+ CheckboxFlags("io.BackendFlags: RendererHasTextures", &io.BackendFlags, ImGuiBackendFlags_RendererHasTextures);
+ EndDisabled();
+ ShowFontSelector("Font");
+ //BeginDisabled((io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0);
+ if (DragFloat("FontSizeBase", &style.FontSizeBase, 0.20f, 5.0f, 100.0f, "%.0f"))
+ style._NextFrameFontSizeBase = style.FontSizeBase; // FIXME: Temporary hack until we finish remaining work.
+ SameLine(0.0f, 0.0f); Text(" (out %.2f)", GetFontSize());
+ SameLine(); MetricsHelpMarker("- This is scaling font only. General scaling will come later.");
+ DragFloat("FontScaleMain", &style.FontScaleMain, 0.02f, 0.5f, 4.0f);
+ //BeginDisabled(io.ConfigDpiScaleFonts);
+ DragFloat("FontScaleDpi", &style.FontScaleDpi, 0.02f, 0.5f, 4.0f);
+ //SetItemTooltip("When io.ConfigDpiScaleFonts is set, this value is automatically overwritten.");
+ //EndDisabled();
+ if ((io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0)
+ {
+ BulletText("Warning: Font scaling will NOT be smooth, because\nImGuiBackendFlags_RendererHasTextures is not set!");
+ BulletText("For instructions, see:");
+ SameLine();
+ TextLinkOpenURL("docs/BACKENDS.md", "https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md");
+ }
+ BulletText("Load a nice font for better results!");
+ BulletText("Please submit feedback:");
+ SameLine(); TextLinkOpenURL("#8465", "https://github.com/ocornut/imgui/issues/8465");
+ BulletText("Read FAQ for more details:");
+ SameLine(); TextLinkOpenURL("dearimgui.com/faq", "https://www.dearimgui.com/faq/");
+ //EndDisabled();
+
+ SeparatorText("Font List");
+
+ ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
+ Checkbox("Show font preview", &cfg->ShowFontPreview);
+
+ // Font loaders
+ if (TreeNode("Loader", "Loader: \'%s\'", atlas->FontLoaderName ? atlas->FontLoaderName : "NULL"))
+ {
+ const ImFontLoader* loader_current = atlas->FontLoader;
+ BeginDisabled(!atlas->RendererHasTextures);
+#ifdef IMGUI_ENABLE_STB_TRUETYPE
+ const ImFontLoader* loader_stbtruetype = ImFontAtlasGetFontLoaderForStbTruetype();
+ if (RadioButton("stb_truetype", loader_current == loader_stbtruetype))
+ atlas->SetFontLoader(loader_stbtruetype);
+#else
+ BeginDisabled();
+ RadioButton("stb_truetype", false);
+ SetItemTooltip("Requires #define IMGUI_ENABLE_STB_TRUETYPE");
+ EndDisabled();
+#endif
+ SameLine();
+#ifdef IMGUI_ENABLE_FREETYPE
+ const ImFontLoader* loader_freetype = ImGuiFreeType::GetFontLoader();
+ if (RadioButton("FreeType", loader_current == loader_freetype))
+ atlas->SetFontLoader(loader_freetype);
+ if (loader_current == loader_freetype)
+ {
+ unsigned int loader_flags = atlas->FontLoaderFlags;
+ Text("Shared FreeType Loader Flags: 0x%08X", loader_flags);
+ if (ImGuiFreeType::DebugEditFontLoaderFlags(&loader_flags))
+ {
+ for (ImFont* font : atlas->Fonts)
+ ImFontAtlasFontDestroyOutput(atlas, font);
+ atlas->FontLoaderFlags = loader_flags;
+ for (ImFont* font : atlas->Fonts)
+ ImFontAtlasFontInitOutput(atlas, font);
+ }
+ }
+#else
+ BeginDisabled();
+ RadioButton("FreeType", false);
+ SetItemTooltip("Requires #define IMGUI_ENABLE_FREETYPE + imgui_freetype.cpp.");
+ EndDisabled();
+#endif
+ EndDisabled();
+ TreePop();
+ }
+
+ // Font list
for (ImFont* font : atlas->Fonts)
{
PushID(font);
DebugNodeFont(font);
PopID();
}
- if (TreeNode("Font Atlas", "Font Atlas (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
+
+ SeparatorText("Font Atlas");
+ if (Button("Compact"))
+ atlas->CompactCache();
+ SameLine();
+ if (Button("Grow"))
+ ImFontAtlasTextureGrow(atlas);
+ SameLine();
+ if (Button("Clear All"))
+ ImFontAtlasBuildClear(atlas);
+ SetItemTooltip("Destroy cache and custom rectangles.");
+
+ for (int tex_n = 0; tex_n < atlas->TexList.Size; tex_n++)
+ {
+ ImTextureData* tex = atlas->TexList[tex_n];
+ if (tex_n > 0)
+ SameLine();
+ Text("Tex: %dx%d", tex->Width, tex->Height);
+ }
+ const int packed_surface_sqrt = (int)sqrtf((float)atlas->Builder->RectsPackedSurface);
+ const int discarded_surface_sqrt = (int)sqrtf((float)atlas->Builder->RectsDiscardedSurface);
+ Text("Packed rects: %d, area: about %d px ~%dx%d px", atlas->Builder->RectsPackedCount, atlas->Builder->RectsPackedSurface, packed_surface_sqrt, packed_surface_sqrt);
+ Text("incl. Discarded rects: %d, area: about %d px ~%dx%d px", atlas->Builder->RectsDiscardedCount, atlas->Builder->RectsDiscardedSurface, discarded_surface_sqrt, discarded_surface_sqrt);
+
+ ImFontAtlasRectId highlight_r_id = ImFontAtlasRectId_Invalid;
+ if (TreeNode("Rects Index", "Rects Index (%d)", atlas->Builder->RectsPackedCount)) // <-- Use count of used rectangles
+ {
+ PushStyleVar(ImGuiStyleVar_ImageBorderSize, 1.0f);
+ if (BeginTable("##table", 2, ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollY, ImVec2(0.0f, GetTextLineHeightWithSpacing() * 12)))
+ {
+ for (const ImFontAtlasRectEntry& entry : atlas->Builder->RectsIndex)
+ if (entry.IsUsed)
+ {
+ ImFontAtlasRectId id = ImFontAtlasRectId_Make(atlas->Builder->RectsIndex.index_from_ptr(&entry), entry.Generation);
+ ImFontAtlasRect r = {};
+ atlas->GetCustomRect(id, &r);
+ const char* buf;
+ ImFormatStringToTempBuffer(&buf, NULL, "ID:%08X, used:%d, { w:%3d, h:%3d } { x:%4d, y:%4d }", id, entry.IsUsed, r.w, r.h, r.x, r.y);
+ TableNextColumn();
+ Selectable(buf);
+ if (IsItemHovered())
+ highlight_r_id = id;
+ TableNextColumn();
+ Image(atlas->TexRef, ImVec2(r.w, r.h), r.uv0, r.uv1);
+ }
+ EndTable();
+ }
+ PopStyleVar();
+ TreePop();
+ }
+
+ // Texture list
+ // (ensure the last texture always use the same ID, so we can keep it open neatly)
+ ImFontAtlasRect highlight_r;
+ if (highlight_r_id != ImFontAtlasRectId_Invalid)
+ atlas->GetCustomRect(highlight_r_id, &highlight_r);
+ for (int tex_n = 0; tex_n < atlas->TexList.Size; tex_n++)
+ {
+ if (tex_n == atlas->TexList.Size - 1)
+ SetNextItemOpen(true, ImGuiCond_Once);
+ DebugNodeTexture(atlas->TexList[tex_n], atlas->TexList.Size - 1 - tex_n, (highlight_r_id != ImFontAtlasRectId_Invalid) ? &highlight_r : NULL);
+ }
+}
+
+void ImGui::DebugNodeTexture(ImTextureData* tex, int int_id, const ImFontAtlasRect* highlight_rect)
+{
+ ImGuiContext& g = *GImGui;
+ PushID(int_id);
+ if (TreeNode("", "Texture #%03d (%dx%d pixels)", tex->UniqueID, tex->Width, tex->Height))
{
- ImGuiContext& g = *GImGui;
ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
- Checkbox("Tint with Text Color", &cfg->ShowAtlasTintedWithTextColor); // Using text color ensure visibility of core atlas data, but will alter custom colored icons
- ImVec4 tint_col = cfg->ShowAtlasTintedWithTextColor ? GetStyleColorVec4(ImGuiCol_Text) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
- ImVec4 border_col = GetStyleColorVec4(ImGuiCol_Border);
- Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), tint_col, border_col);
+ Checkbox("Show used rect", &cfg->ShowTextureUsedRect);
+ PushStyleVar(ImGuiStyleVar_ImageBorderSize, ImMax(1.0f, g.Style.ImageBorderSize));
+ ImVec2 p = GetCursorScreenPos();
+ if (tex->WantDestroyNextFrame)
+ Dummy(ImVec2((float)tex->Width, (float)tex->Height));
+ else
+ ImageWithBg(tex->GetTexRef(), ImVec2((float)tex->Width, (float)tex->Height), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), ImVec4(0.0f, 0.0f, 0.0f, 1.0f));
+ if (cfg->ShowTextureUsedRect)
+ GetWindowDrawList()->AddRect(ImVec2(p.x + tex->UsedRect.x, p.y + tex->UsedRect.y), ImVec2(p.x + tex->UsedRect.x + tex->UsedRect.w, p.y + tex->UsedRect.y + tex->UsedRect.h), IM_COL32(255, 0, 255, 255));
+ if (highlight_rect != NULL)
+ {
+ ImRect r_outer(p.x, p.y, p.x + tex->Width, p.y + tex->Height);
+ ImRect r_inner(p.x + highlight_rect->x, p.y + highlight_rect->y, p.x + highlight_rect->x + highlight_rect->w, p.y + highlight_rect->y + highlight_rect->h);
+ RenderRectFilledWithHole(GetWindowDrawList(), r_outer, r_inner, IM_COL32(0, 0, 0, 100), 0.0f);
+ GetWindowDrawList()->AddRect(r_inner.Min - ImVec2(1, 1), r_inner.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255));
+ }
+ PopStyleVar();
+
+ char texid_desc[30];
+ Text("Status = %s (%d), Format = %s (%d), UseColors = %d", ImTextureDataGetStatusName(tex->Status), tex->Status, ImTextureDataGetFormatName(tex->Format), tex->Format, tex->UseColors);
+ Text("TexID = %s, BackendUserData = %p", FormatTextureRefForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), tex->GetTexRef()), tex->BackendUserData);
TreePop();
}
+ PopID();
}
void ImGui::ShowMetricsWindow(bool* p_open)
@@ -21071,6 +21918,10 @@ void ImGui::ShowMetricsWindow(bool* p_open)
}
};
+#ifdef IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS
+ TextColored(ImVec4(1.0f, 0.0f, 0.0f, 1.0f), "IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS is enabled.\nMust disable after use! Otherwise Dear ImGui will run slower.\n");
+#endif
+
// Tools
if (TreeNode("Tools"))
{
@@ -21274,6 +22125,14 @@ void ImGui::ShowMetricsWindow(bool* p_open)
TreePop();
}
+ // Details for Fonts
+ for (ImFontAtlas* atlas : g.FontAtlases)
+ if (TreeNode((void*)atlas, "Fonts (%d), Textures (%d)", atlas->Fonts.Size, atlas->TexList.Size))
+ {
+ ShowFontAtlas(atlas);
+ TreePop();
+ }
+
// Details for Popups
if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
{
@@ -21310,14 +22169,6 @@ void ImGui::ShowMetricsWindow(bool* p_open)
TreePop();
}
- // Details for Fonts
- ImFontAtlas* atlas = g.IO.Fonts;
- if (TreeNode("Fonts", "Fonts (%d)", atlas->Fonts.Size))
- {
- ShowFontAtlas(atlas);
- TreePop();
- }
-
// Details for InputText
if (TreeNode("InputText"))
{
@@ -21459,18 +22310,11 @@ void ImGui::ShowMetricsWindow(bool* p_open)
{
Text("KEYBOARD/GAMEPAD/MOUSE KEYS");
{
- // We iterate both legacy native range and named ImGuiKey ranges, which is a little odd but this allows displaying the data for old/new backends.
// User code should never have to go through such hoops! You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END.
Indent();
-#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
- struct funcs { static bool IsLegacyNativeDupe(ImGuiKey) { return false; } };
-#else
- struct funcs { static bool IsLegacyNativeDupe(ImGuiKey key) { return key >= 0 && key < 512 && GetIO().KeyMap[key] != -1; } }; // Hide Native<>ImGuiKey duplicates when both exists in the array
- //Text("Legacy raw:"); for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key++) { if (io.KeysDown[key]) { SameLine(); Text("\"%s\" %d", GetKeyName(key), key); } }
-#endif
- Text("Keys down:"); for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyDown(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text("(%.02f)", GetKeyData(key)->DownDuration); }
- Text("Keys pressed:"); for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyPressed(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
- Text("Keys released:"); for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyReleased(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
+ Text("Keys down:"); for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) { if (!IsKeyDown(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text("(%.02f)", GetKeyData(key)->DownDuration); }
+ Text("Keys pressed:"); for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) { if (!IsKeyPressed(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
+ Text("Keys released:"); for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) { if (!IsKeyReleased(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
Text("Chars queue:"); for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; SameLine(); 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.
DebugRenderKeyboardPreview(GetWindowDrawList());
@@ -21832,16 +22676,6 @@ void ImGui::DebugNodeDockNode(ImGuiDockNode* node, const char* label)
}
}
-static void FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTextureID tex_id)
-{
- union { void* ptr; int integer; } tex_id_opaque;
- memcpy(&tex_id_opaque, &tex_id, ImMin(sizeof(void*), sizeof(tex_id)));
- if (sizeof(tex_id) >= sizeof(void*))
- ImFormatString(buf, buf_size, "0x%p", tex_id_opaque.ptr);
- else
- ImFormatString(buf, buf_size, "0x%04X", tex_id_opaque.integer);
-}
-
// [DEBUG] Display contents of ImDrawList
// Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport.
void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
@@ -21878,8 +22712,8 @@ void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, con
continue;
}
- char texid_desc[20];
- FormatTextureIDForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), pcmd->TextureId);
+ char texid_desc[30];
+ FormatTextureRefForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), pcmd->TexRef);
char buf[300];
ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex %s, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
pcmd->ElemCount / 3, texid_desc, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
@@ -21968,98 +22802,223 @@ void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, co
out_draw_list->Flags = backup_flags;
}
+// [DEBUG] Compute mask of inputs with the same codepoint.
+static int CalcFontGlyphSrcOverlapMask(ImFontAtlas* atlas, ImFont* font, unsigned int codepoint)
+{
+ int mask = 0, count = 0;
+ for (int src_n = 0; src_n < font->Sources.Size; src_n++)
+ {
+ ImFontConfig* src = font->Sources[src_n];
+ if (!(src->FontLoader ? src->FontLoader : atlas->FontLoader)->FontSrcContainsGlyph(atlas, src, (ImWchar)codepoint))
+ continue;
+ mask |= (1 << src_n);
+ count++;
+ }
+ return count > 1 ? mask : 0;
+}
+
// [DEBUG] Display details for a single font, called by ShowStyleEditor().
void ImGui::DebugNodeFont(ImFont* font)
{
- bool opened = 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);
- SameLine();
- if (SmallButton("Set as default"))
- GetIO().FontDefault = font;
- if (!opened)
- return;
+ ImGuiContext& g = *GImGui;
+ ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
+ ImFontAtlas* atlas = font->ContainerAtlas;
+ bool opened = TreeNode(font, "Font: \"%s\": %d sources(s)", font->GetDebugName(), font->Sources.Size);
// Display preview text
- PushFont(font);
- Text("The quick brown fox jumps over the lazy dog");
- PopFont();
+ if (!opened)
+ Indent();
+ Indent();
+ if (cfg->ShowFontPreview)
+ {
+ PushFont(font, 0.0f);
+ Text("The quick brown fox jumps over the lazy dog");
+ PopFont();
+ }
+ if (!opened)
+ {
+ Unindent();
+ Unindent();
+ return;
+ }
+ if (SmallButton("Set as default"))
+ GetIO().FontDefault = font;
+ SameLine();
+ BeginDisabled(atlas->Fonts.Size <= 1 || atlas->Locked);
+ if (SmallButton("Remove"))
+ atlas->RemoveFont(font);
+ EndDisabled();
+ SameLine();
+ if (SmallButton("Clear bakes"))
+ ImFontAtlasFontDiscardBakes(atlas, font, 0);
+ SameLine();
+ if (SmallButton("Clear unused"))
+ ImFontAtlasFontDiscardBakes(atlas, font, 2);
// Display details
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
SetNextItemWidth(GetFontSize() * 8);
DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f");
- SameLine(); MetricsHelpMarker(
+ /*SameLine(); MetricsHelpMarker(
"Note that 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.)");
- Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
+ "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");*/
+#endif
+
char c_str[5];
- Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar);
- Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar);
- const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface);
- 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])
- 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);
+ ImTextCharToUtf8(c_str, font->FallbackChar);
+ Text("Fallback character: '%s' (U+%04X)", c_str, font->FallbackChar);
+ ImTextCharToUtf8(c_str, font->EllipsisChar);
+ Text("Ellipsis character: '%s' (U+%04X)", c_str, font->EllipsisChar);
+
+ for (int src_n = 0; src_n < font->Sources.Size; src_n++)
+ {
+ ImFontConfig* src = font->Sources[src_n];
+ if (TreeNode(src, "Input %d: \'%s\' [%d], Oversample: %d,%d, PixelSnapH: %d, Offset: (%.1f,%.1f)",
+ src_n, src->Name, src->FontNo, src->OversampleH, src->OversampleV, src->PixelSnapH, src->GlyphOffset.x, src->GlyphOffset.y))
+ {
+ const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader;
+ Text("Loader: '%s'", loader->Name ? loader->Name : "N/A");
+#ifdef IMGUI_ENABLE_FREETYPE
+ if (loader->Name != NULL && strcmp(loader->Name, "FreeType") == 0)
+ {
+ unsigned int loader_flags = src->FontLoaderFlags;
+ Text("FreeType Loader Flags: 0x%08X", loader_flags);
+ if (ImGuiFreeType::DebugEditFontLoaderFlags(&loader_flags))
+ {
+ ImFontAtlasFontDestroyOutput(atlas, font);
+ src->FontLoaderFlags = loader_flags;
+ ImFontAtlasFontInitOutput(atlas, font);
+ }
+ }
+#endif
+ TreePop();
+ }
+ }
+ if (font->Sources.Size > 1 && TreeNode("Input Glyphs Overlap Detection Tool"))
+ {
+ TextWrapped("- First Input that contains the glyph is used.\n"
+ "- Use ImFontConfig::GlyphExcludeRanges[] to specify ranges to ignore glyph in given Input.\n- Prefer using a small number of ranges as the list is scanned every time a new glyph is loaded,\n - e.g. GlyphExcludeRanges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 };\n- This tool doesn't cache results and is slow, don't keep it open!");
+ if (BeginTable("table", 2))
+ {
+ for (unsigned int c = 0; c < 0x10000; c++)
+ if (int overlap_mask = CalcFontGlyphSrcOverlapMask(atlas, font, c))
+ {
+ unsigned int c_end = c + 1;
+ while (c_end < 0x10000 && CalcFontGlyphSrcOverlapMask(atlas, font, c_end) == overlap_mask)
+ c_end++;
+ if (TableNextColumn() && TreeNode((void*)(intptr_t)c, "U+%04X-U+%04X: %d codepoints in %d inputs", c, c_end - 1, c_end - c, ImCountSetBits(overlap_mask)))
+ {
+ char utf8_buf[5];
+ for (unsigned int n = c; n < c_end; n++)
+ {
+ ImTextCharToUtf8(utf8_buf, n);
+ BulletText("Codepoint U+%04X (%s)", n, utf8_buf);
+ }
+ TreePop();
+ }
+ TableNextColumn();
+ for (int src_n = 0; src_n < font->Sources.Size; src_n++)
+ if (overlap_mask & (1 << src_n))
+ {
+ Text("%d ", src_n);
+ SameLine();
+ }
+ c = c_end - 1;
+ }
+ EndTable();
+ }
+ TreePop();
+ }
// Display all glyphs of the fonts in separate pages of 256 characters
- if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
- {
- ImDrawList* draw_list = GetWindowDrawList();
- const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
- const float cell_size = font->FontSize * 1;
- const float cell_spacing = GetStyle().ItemSpacing.y;
- 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))
+ for (int baked_n = 0; baked_n < atlas->Builder->BakedPool.Size; baked_n++)
+ {
+ ImFontBaked* baked = &atlas->Builder->BakedPool[baked_n];
+ if (baked->ContainerFont != font)
+ continue;
+ PushID(baked_n);
+ if (TreeNode("Glyphs", "Baked at { %.2fpx, d.%.2f }: %d glyphs%s", baked->Size, baked->RasterizerDensity, baked->Glyphs.Size, (baked->LastUsedFrame < atlas->Builder->FrameCount - 1) ? " *Unused*" : ""))
+ {
+ if (SmallButton("Load all"))
+ for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base++)
+ baked->FindGlyph((ImWchar)base);
+
+ const int surface_sqrt = (int)ImSqrt((float)baked->MetricsTotalSurface);
+ Text("Ascent: %f, Descent: %f, Ascent-Descent: %f", baked->Ascent, baked->Descent, baked->Ascent - baked->Descent);
+ Text("Texture Area: about %d px ~%dx%d px", baked->MetricsTotalSurface, surface_sqrt, surface_sqrt);
+ for (int src_n = 0; src_n < font->Sources.Size; src_n++)
{
- base += 4096 - 256;
- continue;
+ ImFontConfig* src = font->Sources[src_n];
+ int oversample_h, oversample_v;
+ ImFontAtlasBuildGetOversampleFactors(src, baked, &oversample_h, &oversample_v);
+ BulletText("Input %d: \'%s\', Oversample: (%d=>%d,%d=>%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
+ src_n, src->Name, src->OversampleH, oversample_h, src->OversampleV, oversample_v, src->PixelSnapH, src->GlyphOffset.x, src->GlyphOffset.y);
}
- int count = 0;
- for (unsigned int n = 0; n < 256; n++)
- if (font->FindGlyphNoFallback((ImWchar)(base + n)))
+ DebugNodeFontGlyphesForSrcMask(font, baked, ~0);
+ TreePop();
+ }
+ PopID();
+ }
+ TreePop();
+ Unindent();
+}
+
+void ImGui::DebugNodeFontGlyphesForSrcMask(ImFont* font, ImFontBaked* baked, int src_mask)
+{
+ ImDrawList* draw_list = GetWindowDrawList();
+ const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
+ const float cell_size = baked->Size * 1;
+ const float cell_spacing = GetStyle().ItemSpacing.y;
+ 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 & 8191) && font->IsGlyphRangeUnused(base, base + 8191))
+ {
+ base += 8192 - 256;
+ continue;
+ }
+
+ int count = 0;
+ for (unsigned int n = 0; n < 256; n++)
+ if (const ImFontGlyph* glyph = baked->IsGlyphLoaded((ImWchar)(base + n)) ? baked->FindGlyph((ImWchar)(base + n)) : NULL)
+ if (src_mask & (1 << glyph->SourceIdx))
count++;
- if (count <= 0)
- continue;
- if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
- continue;
+ if (count <= 0)
+ continue;
+ if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
+ continue;
- // Draw a 16x16 grid of glyphs
- ImVec2 base_pos = GetCursorScreenPos();
- for (unsigned int n = 0; n < 256; n++)
+ // Draw a 16x16 grid of glyphs
+ ImVec2 base_pos = GetCursorScreenPos();
+ 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 = baked->IsGlyphLoaded((ImWchar)(base + n)) ? baked->FindGlyph((ImWchar)(base + n)) : NULL;
+ draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
+ if (!glyph || (src_mask & (1 << glyph->SourceIdx)) == 0)
+ continue;
+ font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
+ if (IsMouseHoveringRect(cell_p1, cell_p2) && BeginTooltip())
{
- // 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)
- continue;
- font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
- if (IsMouseHoveringRect(cell_p1, cell_p2) && BeginTooltip())
- {
- DebugNodeFontGlyph(font, glyph);
- EndTooltip();
- }
+ DebugNodeFontGlyph(font, glyph);
+ EndTooltip();
}
- Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
- TreePop();
}
+ Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
TreePop();
}
- TreePop();
}
-void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph)
+void ImGui::DebugNodeFontGlyph(ImFont* font, const ImFontGlyph* glyph)
{
Text("Codepoint: U+%04X", glyph->Codepoint);
Separator();
@@ -22067,6 +23026,12 @@ void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph)
Text("AdvanceX: %.1f", glyph->AdvanceX);
Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
+ if (glyph->PackId >= 0)
+ {
+ ImTextureRect* r = ImFontAtlasPackGetRect(font->ContainerAtlas, glyph->PackId);
+ Text("PackId: 0x%X (%dx%d rect at %d,%d)", glyph->PackId, r->w, r->h, r->x, r->y);
+ }
+ Text("SourceIdx: %d", glyph->SourceIdx);
}
// [DEBUG] Display contents of ImGuiStorage
@@ -22133,8 +23098,9 @@ void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
if (open)
{
ImGuiWindowFlags flags = viewport->Flags;
- BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Inset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%",
+ BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nFrameBufferScale: (%.2f,%.2f)\nWorkArea Inset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%",
viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
+ viewport->FramebufferScale.x, viewport->FramebufferScale.y,
viewport->WorkInsetMin.x, viewport->WorkInsetMin.y, viewport->WorkInsetMax.x, viewport->WorkInsetMax.y,
viewport->PlatformMonitor, viewport->DpiScale * 100.0f);
if (viewport->Idx > 0) { SameLine(); if (SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200, 200); viewport->UpdateWorkRect(); if (viewport->Window) viewport->Window->Pos = viewport->Pos; } }
@@ -22212,7 +23178,7 @@ void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
{
ImRect r = window->NavRectRel[layer];
- if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)
+ if (r.Min.x >= r.Max.x && r.Min.y >= r.Max.y)
BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
else
BulletText("NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y);
@@ -22220,7 +23186,7 @@ void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
}
const ImVec2* pr = window->NavPreferredScoringPosRel;
for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
- BulletText("NavPreferredScoringPosRel[%d] = {%.1f,%.1f)", layer, (pr[layer].x == FLT_MAX ? -99999.0f : pr[layer].x), (pr[layer].y == FLT_MAX ? -99999.0f : pr[layer].y)); // Display as 99999.0f so it looks neater.
+ BulletText("NavPreferredScoringPosRel[%d] = (%.1f,%.1f)", layer, (pr[layer].x == FLT_MAX ? -99999.0f : pr[layer].x), (pr[layer].y == FLT_MAX ? -99999.0f : pr[layer].y)); // Display as 99999.0f so it looks neater.
BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
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);
@@ -22279,9 +23245,9 @@ void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int wi
ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext);
//BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
DebugNodeWindow(window, buf);
- Indent();
+ TreePush(buf);
DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window);
- Unindent();
+ TreePop();
}
}
@@ -22356,7 +23322,7 @@ static void ShowDebugLogFlag(const char* name, ImGuiDebugLogFlags flags)
void ImGui::ShowDebugLogWindow(bool* p_open)
{
ImGuiContext& g = *GImGui;
- if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) == 0)
+ if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) == 0)
SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 12.0f), ImGuiCond_FirstUseEver);
if (!Begin("Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1)
{
@@ -22374,6 +23340,7 @@ void ImGui::ShowDebugLogWindow(bool* p_open)
ShowDebugLogFlag("Docking", ImGuiDebugLogFlags_EventDocking);
ShowDebugLogFlag("Focus", ImGuiDebugLogFlags_EventFocus);
ShowDebugLogFlag("IO", ImGuiDebugLogFlags_EventIO);
+ ShowDebugLogFlag("Font", ImGuiDebugLogFlags_EventFont);
ShowDebugLogFlag("Nav", ImGuiDebugLogFlags_EventNav);
ShowDebugLogFlag("Popup", ImGuiDebugLogFlags_EventPopup);
ShowDebugLogFlag("Selection", ImGuiDebugLogFlags_EventSelection);
@@ -22427,7 +23394,7 @@ void ImGui::ShowDebugLogWindow(bool* p_open)
void ImGui::DebugTextUnformattedWithLocateItem(const char* line_begin, const char* line_end)
{
TextUnformatted(line_begin, line_end);
- if (!IsItemHovered())
+ if (!IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
return;
ImGuiContext& g = *GImGui;
ImRect text_rect = g.LastItemData.Rect;
@@ -22575,20 +23542,22 @@ void ImGui::UpdateDebugToolStackQueries()
ImGuiIDStackTool* tool = &g.DebugIDStackTool;
// Clear hook when id stack tool is not visible
- g.DebugHookIdInfo = 0;
+ g.DebugHookIdInfoId = 0;
+ tool->QueryHookActive = false;
if (g.FrameCount != tool->LastActiveFrame + 1)
return;
// Update queries. The steps are: -1: query Stack, >= 0: query each stack item
// We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
- const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
- if (tool->QueryId != query_id)
+ const ImGuiID query_main_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
+ if (tool->QueryMainId != query_main_id)
{
- tool->QueryId = query_id;
+ tool->QueryMainId = query_main_id;
tool->StackLevel = -1;
tool->Results.resize(0);
+ tool->ResultPathsBuf.resize(0);
}
- if (query_id == 0)
+ if (query_main_id == 0)
return;
// Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
@@ -22600,11 +23569,15 @@ void ImGui::UpdateDebugToolStackQueries()
// Update hook
stack_level = tool->StackLevel;
if (stack_level == -1)
- g.DebugHookIdInfo = query_id;
- if (stack_level >= 0 && stack_level < tool->Results.Size)
{
- g.DebugHookIdInfo = tool->Results[stack_level].ID;
+ g.DebugHookIdInfoId = query_main_id;
+ tool->QueryHookActive = true;
+ }
+ else if (stack_level >= 0 && stack_level < tool->Results.Size)
+ {
+ g.DebugHookIdInfoId = tool->Results[stack_level].ID;
tool->Results[stack_level].QueryFrameCount++;
+ tool->QueryHookActive = true;
}
}
@@ -22614,11 +23587,17 @@ void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* dat
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiIDStackTool* tool = &g.DebugIDStackTool;
+ if (tool->QueryHookActive == false)
+ {
+ IM_ASSERT(id == 0);
+ return;
+ }
// Step 0: stack query
// This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget.
if (tool->StackLevel == -1)
{
+ IM_ASSERT(tool->Results.Size == 0);
tool->StackLevel++;
tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo());
for (int n = 0; n < window->IDStack.Size + 1; n++)
@@ -22633,42 +23612,48 @@ void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* dat
ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
- switch (data_type)
+ if (info->DescOffset == -1)
{
- case ImGuiDataType_S32:
- ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%d", (int)(intptr_t)data_id);
- break;
- case ImGuiDataType_String:
- ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)strlen((const char*)data_id), (const char*)data_id);
- break;
- case ImGuiDataType_Pointer:
- ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "(void*)0x%p", data_id);
- break;
- case ImGuiDataType_ID:
- if (info->Desc[0] != 0) // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one.
- return;
- ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "0x%08X [override]", id);
- break;
- default:
- IM_ASSERT(0);
+ const char* result = NULL;
+ const char* result_end = NULL;
+ switch (data_type)
+ {
+ case ImGuiDataType_S32:
+ ImFormatStringToTempBuffer(&result, &result_end, "%d", (int)(intptr_t)data_id);
+ break;
+ case ImGuiDataType_String:
+ ImFormatStringToTempBuffer(&result, &result_end, "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)ImStrlen((const char*)data_id), (const char*)data_id);
+ break;
+ case ImGuiDataType_Pointer:
+ ImFormatStringToTempBuffer(&result, &result_end, "(void*)0x%p", data_id);
+ break;
+ case ImGuiDataType_ID:
+ // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one.
+ ImFormatStringToTempBuffer(&result, &result_end, "0x%08X [override]", id);
+ break;
+ default:
+ IM_ASSERT(0);
+ }
+ info->DescOffset = tool->ResultPathsBuf.size();
+ tool->ResultPathsBuf.append(result, result_end + 1); // Include zero terminator
}
info->QuerySuccess = true;
- info->DataType = data_type;
+ info->DataType = (ImS8)data_type;
}
static int StackToolFormatLevelInfo(ImGuiIDStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size)
{
ImGuiStackLevelInfo* info = &tool->Results[n];
- ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL;
+ ImGuiWindow* window = (info->DescOffset == -1 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL;
if (window) // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
- return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", window->Name);
+ return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", ImHashSkipUncontributingPrefix(window->Name));
if (info->QuerySuccess) // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
- return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", info->Desc);
+ return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", ImHashSkipUncontributingPrefix(&tool->ResultPathsBuf.Buf[info->DescOffset]));
if (tool->StackLevel < tool->Results.Size) // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
return (*buf = 0);
#ifdef IMGUI_ENABLE_TEST_ENGINE
if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID)) // Source: ImGuiTestEngine's ItemInfo()
- return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", label);
+ return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", ImHashSkipUncontributingPrefix(label));
#endif
return ImFormatString(buf, buf_size, "???");
}
@@ -22677,7 +23662,7 @@ static int StackToolFormatLevelInfo(ImGuiIDStackTool* tool, int n, bool format_f
void ImGui::ShowIDStackToolWindow(bool* p_open)
{
ImGuiContext& g = *GImGui;
- if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) == 0)
+ if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) == 0)
SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver);
if (!Begin("Dear ImGui ID Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
{
@@ -22687,42 +23672,53 @@ void ImGui::ShowIDStackToolWindow(bool* p_open)
// Display hovered/active status
ImGuiIDStackTool* tool = &g.DebugIDStackTool;
- const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
- const ImGuiID active_id = g.ActiveId;
-#ifdef IMGUI_ENABLE_TEST_ENGINE
- Text("HoveredId: 0x%08X (\"%s\"), ActiveId: 0x%08X (\"%s\")", hovered_id, hovered_id ? ImGuiTestEngine_FindItemDebugLabel(&g, hovered_id) : "", active_id, active_id ? ImGuiTestEngine_FindItemDebugLabel(&g, active_id) : "");
-#else
- Text("HoveredId: 0x%08X, ActiveId: 0x%08X", hovered_id, active_id);
-#endif
+
+ // Build and display path
+ tool->ResultTempBuf.resize(0);
+ for (int stack_n = 0; stack_n < tool->Results.Size; stack_n++)
+ {
+ char level_desc[256];
+ StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc));
+ tool->ResultTempBuf.append(stack_n == 0 ? "//" : "/");
+ for (const char* p = level_desc; *p != 0; )
+ {
+ unsigned int c;
+ const char* p_next = p + ImTextCharFromUtf8(&c, p, NULL);
+ if (c == '/')
+ tool->ResultTempBuf.append("\\");
+ if (c < 256 || !tool->OptHexEncodeNonAsciiChars)
+ tool->ResultTempBuf.append(p, p_next);
+ else for (; p < p_next; p++)
+ tool->ResultTempBuf.appendf("\\x%02x", (unsigned char)*p);
+ p = p_next;
+ }
+ }
+ Text("0x%08X", tool->QueryMainId);
SameLine();
MetricsHelpMarker("Hover an item with the mouse to display elements of the ID Stack leading to the item's final ID.\nEach level of the stack correspond to a PushID() call.\nAll levels of the stack are hashed together to make the final ID of a widget (ID displayed at the bottom level of the stack).\nRead FAQ entry about the ID stack for details.");
// CTRL+C to copy path
const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime;
- Checkbox("Ctrl+C: copy path to clipboard", &tool->CopyToClipboardOnCtrlC);
+ PushStyleVarY(ImGuiStyleVar_FramePadding, 0.0f);
+ Checkbox("Hex-encode non-ASCII", &tool->OptHexEncodeNonAsciiChars);
+ SameLine();
+ Checkbox("Ctrl+C: copy path", &tool->OptCopyToClipboardOnCtrlC);
+ PopStyleVar();
SameLine();
TextColored((time_since_copy >= 0.0f && time_since_copy < 0.75f && ImFmod(time_since_copy, 0.25f) < 0.25f * 0.5f) ? ImVec4(1.f, 1.f, 0.3f, 1.f) : ImVec4(), "*COPIED*");
- if (tool->CopyToClipboardOnCtrlC && Shortcut(ImGuiMod_Ctrl | ImGuiKey_C, ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused))
+ if (tool->OptCopyToClipboardOnCtrlC && Shortcut(ImGuiMod_Ctrl | ImGuiKey_C, ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused))
{
tool->CopyToClipboardLastTime = (float)g.Time;
- char* p = g.TempBuffer.Data;
- char* p_end = p + g.TempBuffer.Size;
- for (int stack_n = 0; stack_n < tool->Results.Size && p + 3 < p_end; stack_n++)
- {
- *p++ = '/';
- char level_desc[256];
- StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc));
- for (int n = 0; level_desc[n] && p + 2 < p_end; n++)
- {
- if (level_desc[n] == '/')
- *p++ = '\\';
- *p++ = level_desc[n];
- }
- }
- *p = '\0';
- SetClipboardText(g.TempBuffer.Data);
+ SetClipboardText(tool->ResultTempBuf.c_str());
}
+ Text("- Path \"%s\"", tool->ResultTempBuf.c_str());
+#ifdef IMGUI_ENABLE_TEST_ENGINE
+ Text("- Label \"%s\"", tool->QueryMainId ? ImGuiTestEngine_FindItemDebugLabel(&g, tool->QueryMainId) : "");
+#endif
+
+ Separator();
+
// Display decorated stack
tool->LastActiveFrame = g.FrameCount;
if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders))
@@ -22758,6 +23754,7 @@ void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {}
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
void ImGui::DebugNodeFont(ImFont*) {}
+void ImGui::DebugNodeFontGlyphesForSrcMask(ImFont*, ImFontBaked*, int) {}
void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
@@ -22772,6 +23769,40 @@ void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
#endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
+#if !defined(IMGUI_DISABLE_DEMO_WINDOWS) || !defined(IMGUI_DISABLE_DEBUG_TOOLS)
+// Demo helper function to select among loaded fonts.
+// Here we use the regular BeginCombo()/EndCombo() api which is the more flexible one.
+void ImGui::ShowFontSelector(const char* label)
+{
+ ImGuiIO& io = GetIO();
+ ImFont* font_current = GetFont();
+ if (BeginCombo(label, font_current->GetDebugName()))
+ {
+ for (ImFont* font : io.Fonts->Fonts)
+ {
+ PushID((void*)font);
+ if (Selectable(font->GetDebugName(), font == font_current, ImGuiSelectableFlags_SelectOnNav))
+ io.FontDefault = font;
+ if (font == font_current)
+ SetItemDefaultFocus();
+ PopID();
+ }
+ EndCombo();
+ }
+ SameLine();
+ if (io.BackendFlags & ImGuiBackendFlags_RendererHasTextures)
+ MetricsHelpMarker(
+ "- Load additional fonts with io.Fonts->AddFontXXX() functions.\n"
+ "- Read FAQ and docs/FONTS.md for more details.");
+ else
+ MetricsHelpMarker(
+ "- Load additional fonts with io.Fonts->AddFontXXX() functions.\n"
+ "- The font atlas is built when calling io.Fonts->GetTexDataAsXXXX() or io.Fonts->Build().\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().");
+}
+#endif // #if !defined(IMGUI_DISABLE_DEMO_WINDOWS) || !defined(IMGUI_DISABLE_DEBUG_TOOLS)
+
//-----------------------------------------------------------------------------
// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
diff --git a/source/code/Libs/imgui/imgui.h b/source/code/Libs/imgui/imgui.h index 12b0037..ac8cddd 100644 --- a/source/code/Libs/imgui/imgui.h +++ b/source/code/Libs/imgui/imgui.h
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.4
+// dear imgui, v1.92.3
// (headers)
// Help:
@@ -28,17 +28,19 @@
// Library Version
// (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
-#define IMGUI_VERSION "1.91.4"
-#define IMGUI_VERSION_NUM 19140
-#define IMGUI_HAS_TABLE
-#define IMGUI_HAS_VIEWPORT // Viewport WIP branch
-#define IMGUI_HAS_DOCK // Docking WIP branch
+#define IMGUI_VERSION "1.92.3"
+#define IMGUI_VERSION_NUM 19230
+#define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000
+#define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198
+#define IMGUI_HAS_VIEWPORT // In 'docking' WIP branch.
+#define IMGUI_HAS_DOCK // In 'docking' WIP branch.
/*
Index of this file:
// [SECTION] Header mess
// [SECTION] Forward declarations and basic types
+// [SECTION] Texture identifiers (ImTextureID, ImTextureRef)
// [SECTION] Dear ImGui end-user API functions
// [SECTION] Flags & Enumerations
// [SECTION] Tables API flags and structures (ImGuiTableFlags, ImGuiTableColumnFlags, ImGuiTableRowFlags, ImGuiTableBgTarget, ImGuiTableSortSpecs, ImGuiTableColumnSortSpecs)
@@ -49,7 +51,8 @@ Index of this file:
// [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, Math Operators, ImColor)
// [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiMultiSelectIO, ImGuiSelectionRequest, ImGuiSelectionBasicStorage, ImGuiSelectionExternalStorage)
// [SECTION] Drawing API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawListFlags, ImDrawList, ImDrawData)
-// [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFont)
+// [SECTION] Texture API (ImTextureFormat, ImTextureStatus, ImTextureRect, ImTextureData)
+// [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFontBaked, ImFont)
// [SECTION] Viewports (ImGuiViewportFlags, ImGuiViewport)
// [SECTION] ImGuiPlatformIO + other Platform Dependent Interfaces (ImGuiPlatformMonitor, ImGuiPlatformImeData)
// [SECTION] Obsolete functions and types
@@ -99,8 +102,10 @@ Index of this file:
#define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx))
// Helper Macros - IM_FMTARGS, IM_FMTLIST: Apply printf-style warnings to our formatting functions.
-// (MSVC provides an equivalent mechanism via SAL Annotations but it would require the macros in a different
-// location. e.g. #include <sal.h> + void myprintf(_Printf_format_string_ const char* format, ...))
+// (MSVC provides an equivalent mechanism via SAL Annotations but it requires the macros in a different
+// location. e.g. #include <sal.h> + void myprintf(_Printf_format_string_ const char* format, ...),
+// and only works when using Code Analysis, rather than just normal compiling).
+// (see https://github.com/ocornut/imgui/issues/8871 for a patch to enable this for MSVC's Code Analysis)
#if !defined(IMGUI_USE_STB_SPRINTF) && defined(__MINGW32__) && !defined(__clang__)
#define IM_FMTARGS(FMT) __attribute__((format(gnu_printf, FMT, FMT+1)))
#define IM_FMTLIST(FMT) __attribute__((format(gnu_printf, FMT, 0)))
@@ -132,15 +137,17 @@ Index of this file:
#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 "-Wold-style-cast"
+#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast
#pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe
-#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
+#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant
#pragma clang diagnostic ignored "-Wreserved-identifier" // warning: identifier '_Xxx' is reserved because it starts with '_' followed by a capital letter
#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access
+#pragma clang diagnostic ignored "-Wnontrivial-memaccess" // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
#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 "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe
+#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
//-----------------------------------------------------------------------------
@@ -158,7 +165,7 @@ typedef unsigned int ImU32; // 32-bit unsigned integer (often used to st
typedef signed long long ImS64; // 64-bit signed integer
typedef unsigned long long ImU64; // 64-bit unsigned integer
-// Forward declarations
+// Forward declarations: ImDrawList, ImFontAtlas layer
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.
@@ -168,11 +175,18 @@ 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 ImFontAtlasBuilder; // Opaque storage for building a ImFontAtlas
+struct ImFontAtlasRect; // Output of ImFontAtlas::GetCustomRect() when using custom rectangles.
+struct ImFontBaked; // Baked data for a ImFont at a given size.
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
+struct ImFontLoader; // Opaque interface to a font loading backend (stb_truetype, FreeType etc.).
+struct ImTextureData; // Specs and pixel storage for a texture used by Dear ImGui.
+struct ImTextureRect; // Coordinates of a rectangle within a texture.
struct ImColor; // Helper functions to create a color that can be converted to either u32 or float4 (*OBSOLETE* please avoid using)
+
+// Forward declarations: ImGui layer
struct ImGuiContext; // Dear ImGui context (opaque structure, unless including imgui_internal.h)
struct ImGuiIO; // Main configuration and I/O between your application and ImGui (also see: ImGuiPlatformIO)
struct ImGuiInputTextCallbackData; // Shared state of InputText() when using custom ImGuiInputTextCallback (rare/advanced use)
@@ -223,7 +237,9 @@ typedef int ImGuiTableBgTarget; // -> enum ImGuiTableBgTarget_ // Enum: A
// - In VS Code, CLion, etc.: CTRL+click can follow symbols inside comments.
typedef int ImDrawFlags; // -> enum ImDrawFlags_ // Flags: for ImDrawList functions
typedef int ImDrawListFlags; // -> enum ImDrawListFlags_ // Flags: for ImDrawList instance
-typedef int ImFontAtlasFlags; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas build
+typedef int ImDrawTextFlags; // -> enum ImDrawTextFlags_ // Internal, do not use!
+typedef int ImFontFlags; // -> enum ImFontFlags_ // Flags: for ImFont
+typedef int ImFontAtlasFlags; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas
typedef int ImGuiBackendFlags; // -> enum ImGuiBackendFlags_ // Flags: for io.BackendFlags
typedef int ImGuiButtonFlags; // -> enum ImGuiButtonFlags_ // Flags: for InvisibleButton()
typedef int ImGuiChildFlags; // -> enum ImGuiChildFlags_ // Flags: for BeginChild()
@@ -238,6 +254,7 @@ typedef int ImGuiInputFlags; // -> enum ImGuiInputFlags_ // Flags: f
typedef int ImGuiInputTextFlags; // -> enum ImGuiInputTextFlags_ // Flags: for InputText(), InputTextMultiline()
typedef int ImGuiItemFlags; // -> enum ImGuiItemFlags_ // Flags: for PushItemFlag(), shared by all items
typedef int ImGuiKeyChord; // -> ImGuiKey | ImGuiMod_XXX // Flags: for IsKeyChordPressed(), Shortcut() etc. an ImGuiKey optionally OR-ed with one or more ImGuiMod_XXX values.
+typedef int ImGuiListClipperFlags; // -> enum ImGuiListClipperFlags_// Flags: for ImGuiListClipper
typedef int ImGuiPopupFlags; // -> enum ImGuiPopupFlags_ // Flags: for OpenPopup*(), BeginPopupContext*(), IsPopupOpen()
typedef int ImGuiMultiSelectFlags; // -> enum ImGuiMultiSelectFlags_// Flags: for BeginMultiSelect()
typedef int ImGuiSelectableFlags; // -> enum ImGuiSelectableFlags_ // Flags: for Selectable()
@@ -251,22 +268,6 @@ typedef int ImGuiTreeNodeFlags; // -> enum ImGuiTreeNodeFlags_ // Flags: f
typedef int ImGuiViewportFlags; // -> enum ImGuiViewportFlags_ // Flags: for ImGuiViewport
typedef int ImGuiWindowFlags; // -> enum ImGuiWindowFlags_ // Flags: for Begin(), BeginChild()
-// ImTexture: user data for renderer backend to identify a texture [Compile-time configurable type]
-// - To use something else than an opaque void* pointer: override with e.g. '#define ImTextureID MyTextureType*' in your imconfig.h file.
-// - This can be whatever to you want it to be! read the FAQ about ImTextureID for details.
-// - You can make this a structure with various constructors if you need. You will have to implement ==/!= operators.
-// - (note: before v1.91.4 (2024/10/08) the default type for ImTextureID was void*. Use intermediary intptr_t cast and read FAQ if you have casting warnings)
-#ifndef ImTextureID
-typedef ImU64 ImTextureID; // Default: store a pointer or an integer fitting in a pointer (most renderer backends are ok with that)
-#endif
-
-// ImDrawIdx: vertex index. [Compile-time configurable type]
-// - To use 16-bit indices + allow large meshes: backend need to set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' and handle ImDrawCmd::VtxOffset (recommended).
-// - To use 32-bit indices: override with '#define ImDrawIdx unsigned int' in your imconfig.h file.
-#ifndef ImDrawIdx
-typedef unsigned short ImDrawIdx; // Default: 16-bit (for maximum compatibility with renderer backends)
-#endif
-
// 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 int ImWchar32; // A single decoded U32 character/code point. We encode them as multi bytes UTF-8 when used in strings.
@@ -317,6 +318,68 @@ struct ImVec4
IM_MSVC_RUNTIME_CHECKS_RESTORE
//-----------------------------------------------------------------------------
+// [SECTION] Texture identifiers (ImTextureID, ImTextureRef)
+//-----------------------------------------------------------------------------
+
+// ImTextureID = backend specific, low-level identifier for a texture uploaded in GPU/graphics system.
+// [Compile-time configurable type]
+// - When a Rendered Backend creates a texture, it store its native identifier into a ImTextureID value.
+// (e.g. Used by DX11 backend to a `ID3D11ShaderResourceView*`; Used by OpenGL backends to store `GLuint`;
+// Used by SDLGPU backend to store a `SDL_GPUTextureSamplerBinding*`, etc.).
+// - User may submit their own textures to e.g. ImGui::Image() function by passing this value.
+// - During the rendering loop, the Renderer Backend retrieve the ImTextureID, which stored inside a
+// ImTextureRef, which is stored inside a ImDrawCmd.
+// - Compile-time type configuration:
+// - To use something other than a 64-bit value: add '#define ImTextureID MyTextureType*' in your imconfig.h file.
+// - This can be whatever to you want it to be! read the FAQ entry about textures for details.
+// - You may decide to store a higher-level structure containing texture, sampler, shader etc. with various
+// constructors if you like. You will need to implement ==/!= operators.
+// History:
+// - In v1.91.4 (2024/10/08): the default type for ImTextureID was changed from 'void*' to 'ImU64'. This allowed backends requirig 64-bit worth of data to build on 32-bit architectures. Use intermediary intptr_t cast and read FAQ if you have casting warnings.
+// - In v1.92.0 (2025/06/11): added ImTextureRef which carry either a ImTextureID either a pointer to internal texture atlas. All user facing functions taking ImTextureID changed to ImTextureRef
+#ifndef ImTextureID
+typedef ImU64 ImTextureID; // Default: store up to 64-bits (any pointer or integer). A majority of backends are ok with that.
+#endif
+
+// Define this if you need 0 to be a valid ImTextureID for your backend.
+#ifndef ImTextureID_Invalid
+#define ImTextureID_Invalid ((ImTextureID)0)
+#endif
+
+// ImTextureRef = higher-level identifier for a texture. Store a ImTextureID _or_ a ImTextureData*.
+// The identifier is valid even before the texture has been uploaded to the GPU/graphics system.
+// This is what gets passed to functions such as `ImGui::Image()`, `ImDrawList::AddImage()`.
+// This is what gets stored in draw commands (`ImDrawCmd`) to identify a texture during rendering.
+// - When a texture is created by user code (e.g. custom images), we directly stores the low-level ImTextureID.
+// Because of this, when displaying your own texture you are likely to ever only manage ImTextureID values on your side.
+// - When a texture is created by the backend, we stores a ImTextureData* which becomes an indirection
+// to extract the ImTextureID value during rendering, after texture upload has happened.
+// - To create a ImTextureRef from a ImTextureData you can use ImTextureData::GetTexRef().
+// We intentionally do not provide an ImTextureRef constructor for this: we don't expect this
+// to be frequently useful to the end-user, and it would be erroneously called by many legacy code.
+// - If you want to bind the current atlas when using custom rectangle, you can use io.Fonts->TexRef.
+// - Binding generators for languages such as C (which don't have constructors), should provide a helper, e.g.
+// inline ImTextureRef ImTextureRefFromID(ImTextureID tex_id) { ImTextureRef tex_ref = { ._TexData = NULL, .TexID = tex_id }; return tex_ref; }
+// In 1.92 we changed most drawing functions using ImTextureID to use ImTextureRef.
+// We intentionally do not provide an implicit ImTextureRef -> ImTextureID cast operator because it is technically lossy to convert ImTextureRef to ImTextureID before rendering.
+IM_MSVC_RUNTIME_CHECKS_OFF
+struct ImTextureRef
+{
+ ImTextureRef() { _TexData = NULL; _TexID = ImTextureID_Invalid; }
+ ImTextureRef(ImTextureID tex_id) { _TexData = NULL; _TexID = tex_id; }
+#if !defined(IMGUI_DISABLE_OBSOLETE_FUNCTIONS) && !defined(ImTextureID)
+ ImTextureRef(void* tex_id) { _TexData = NULL; _TexID = (ImTextureID)(size_t)tex_id; } // For legacy backends casting to ImTextureID
+#endif
+
+ inline ImTextureID GetTexID() const; // == (_TexData ? _TexData->TexID : _TexID) // Implemented below in the file.
+
+ // Members (either are set, never both!)
+ ImTextureData* _TexData; // A texture, generally owned by a ImFontAtlas. Will convert to ImTextureID during render loop, after texture has been uploaded.
+ ImTextureID _TexID; // _OR_ Low-level backend texture identifier, if already uploaded or created by user/app. Generally provided to e.g. ImGui::Image() calls.
+};
+IM_MSVC_RUNTIME_CHECKS_RESTORE
+
+//-----------------------------------------------------------------------------
// [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!)
//-----------------------------------------------------------------------------
@@ -339,7 +402,7 @@ namespace ImGui
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(). 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.
+ IMGUI_API ImDrawData* GetDrawData(); // valid after Render() and until the next call to NewFrame(). Call ImGui_ImplXXXX_RenderDrawData() function in your Renderer Backend to render.
// Demo, Debug, Information
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!
@@ -424,7 +487,6 @@ namespace ImGui
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); // [OBSOLETE] 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().
IMGUI_API void SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond = 0); // set named window position.
IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond = 0); // set named window size. set axis to 0.0f to force an auto-fit on this axis.
IMGUI_API void SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond = 0); // set named window collapsed state
@@ -444,9 +506,29 @@ namespace ImGui
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.
IMGUI_API void SetScrollFromPosY(float local_y, float center_y_ratio = 0.5f); // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position.
- // Parameters stacks (shared)
- IMGUI_API void PushFont(ImFont* font); // use NULL as a shortcut to push default font
+ // Parameters stacks (font)
+ // - PushFont(font, 0.0f) // Change font and keep current size
+ // - PushFont(NULL, 20.0f) // Keep font and change current size
+ // - PushFont(font, 20.0f) // Change font and set size to 20.0f
+ // - PushFont(font, style.FontSizeBase * 2.0f) // Change font and set size to be twice bigger than current size.
+ // - PushFont(font, font->LegacySize) // Change font and set size to size passed to AddFontXXX() function. Same as pre-1.92 behavior.
+ // *IMPORTANT* before 1.92, fonts had a single size. They can now be dynamically be adjusted.
+ // - In 1.92 we have REMOVED the single parameter version of PushFont() because it seems like the easiest way to provide an error-proof transition.
+ // - PushFont(font) before 1.92 = PushFont(font, font->LegacySize) after 1.92 // Use default font size as passed to AddFontXXX() function.
+ // *IMPORTANT* global scale factors are applied over the provided size.
+ // - Global scale factors are: 'style.FontScaleMain', 'style.FontScaleDpi' and maybe more.
+ // - If you want to apply a factor to the _current_ font size:
+ // - CORRECT: PushFont(NULL, style.FontSizeBase) // use current unscaled size == does nothing
+ // - CORRECT: PushFont(NULL, style.FontSizeBase * 2.0f) // use current unscaled size x2 == make text twice bigger
+ // - INCORRECT: PushFont(NULL, GetFontSize()) // INCORRECT! using size after global factors already applied == GLOBAL SCALING FACTORS WILL APPLY TWICE!
+ // - INCORRECT: PushFont(NULL, GetFontSize() * 2.0f) // INCORRECT! using size after global factors already applied == GLOBAL SCALING FACTORS WILL APPLY TWICE!
+ IMGUI_API void PushFont(ImFont* font, float font_size_base_unscaled); // Use NULL as a shortcut to keep current font. Use 0.0f to keep current size.
IMGUI_API void PopFont();
+ IMGUI_API ImFont* GetFont(); // get current font
+ IMGUI_API float GetFontSize(); // get current scaled font size (= height in pixels). AFTER global scale factors applied. *IMPORTANT* DO NOT PASS THIS VALUE TO PushFont()! Use ImGui::GetStyle().FontSizeBase to get value before global scale factors.
+ IMGUI_API ImFontBaked* GetFontBaked(); // get current font bound at current size // == GetFont()->GetFontBaked(GetFontSize())
+
+ // Parameters stacks (shared)
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);
@@ -468,8 +550,6 @@ namespace ImGui
// Style read access
// - Use the ShowStyleEditor() function to interactively see/edit the colors.
- 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 white 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
@@ -548,7 +628,7 @@ namespace ImGui
IMGUI_API void LabelTextV(const char* label, const char* fmt, va_list args) IM_FMTLIST(2);
IMGUI_API void BulletText(const char* fmt, ...) IM_FMTARGS(1); // shortcut for Bullet()+Text()
IMGUI_API void BulletTextV(const char* fmt, va_list args) IM_FMTLIST(1);
- IMGUI_API void SeparatorText(const char* label); // currently: formatted text with an horizontal line
+ IMGUI_API void SeparatorText(const char* label); // currently: formatted text with a horizontal line
// Widgets: Main
// - Most widgets return true when the value has been changed or when pressed/selected
@@ -565,14 +645,17 @@ namespace ImGui
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
IMGUI_API bool TextLink(const char* label); // hyperlink text button, return true when clicked
- IMGUI_API void TextLinkOpenURL(const char* label, const char* url = NULL); // hyperlink text button, automatically open file/url when clicked
+ IMGUI_API bool TextLinkOpenURL(const char* label, const char* url = NULL); // hyperlink text button, automatically open file/url when clicked
// Widgets: Images
- // - Read about ImTextureID here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples
+ // - Read about ImTextureID/ImTextureRef here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples
// - 'uv0' and 'uv1' are texture coordinates. Read about them from the same link above.
- // - Note that Image() may add +2.0f to provided size if a border is visible, ImageButton() adds style.FramePadding*2.0f to provided size.
- IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& image_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(const char* str_id, ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1));
+ // - Image() pads adds style.ImageBorderSize on each side, ImageButton() adds style.FramePadding on each side.
+ // - ImageButton() draws a background based on regular Button() color + optionally an inner background if specified.
+ // - An obsolete version of Image(), before 1.91.9 (March 2025), had a 'tint_col' parameter which is now supported by the ImageWithBg() function.
+ IMGUI_API void Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1));
+ IMGUI_API void ImageWithBg(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1));
+ IMGUI_API bool ImageButton(const char* str_id, ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1));
// Widgets: Combo Box (Dropdown)
// - The BeginCombo()/EndCombo() api allows you to manage your contents and selection state however you want it, by creating e.g. Selectable() items.
@@ -698,8 +781,9 @@ namespace ImGui
// Widgets: List Boxes
// - This is essentially a thin wrapper to using BeginChild/EndChild with the ImGuiChildFlags_FrameStyle flag for stylistic changes + displaying a label.
+ // - If you don't need a label you can probably simply use BeginChild() with the ImGuiChildFlags_FrameStyle flag for the same result.
// - You can submit contents and manage your selection state however you want it, by creating e.g. Selectable() or any other items.
- // - The simplified/old ListBox() api are helpers over BeginListBox()/EndListBox() which are kept available for convenience purpose. This is analoguous to how Combos are created.
+ // - The simplified/old ListBox() api are helpers over BeginListBox()/EndListBox() which are kept available for convenience purpose. This is analogous to how Combos are created.
// - Choose frame width: size.x > 0.0f: custom / size.x < 0.0f or -FLT_MIN: right-align / size.x = 0.0f (default): use current ItemWidth
// - Choose frame height: size.y > 0.0f: custom / size.y < 0.0f or -FLT_MIN: bottom-align / size.y = 0.0f (default): arbitrary default height which can fit ~7 items
IMGUI_API bool BeginListBox(const char* label, const ImVec2& size = ImVec2(0, 0)); // open a framed scrolling region
@@ -844,7 +928,7 @@ namespace ImGui
IMGUI_API ImGuiTableSortSpecs* TableGetSortSpecs(); // get latest sort specs for the table (NULL if not sorting). Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable().
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 int TableGetRowIndex(); // return current row index (header rows are accounted for)
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 TableSetColumnEnabled(int column_n, bool v);// change user accessible enabled/disabled state of a column. Set to false to hide the column. User can use the context menu to change this themselves (right-click in headers, or right-click in columns body with ImGuiTableFlags_ContextMenuInBody)
@@ -928,7 +1012,7 @@ namespace ImGui
IMGUI_API void PopClipRect();
// Focus, Activation
- IMGUI_API void SetItemDefaultFocus(); // make last item the default focused item of of a newly appearing window.
+ IMGUI_API void SetItemDefaultFocus(); // make last item the default focused item of a newly appearing window.
IMGUI_API void SetKeyboardFocusHere(int offset = 0); // focus keyboard on the next widget. Use positive 'offset' to access sub components of a multiple component widget. Use -1 to access previous widget.
// Keyboard/Gamepad Navigation
@@ -989,21 +1073,20 @@ namespace ImGui
// Inputs Utilities: Keyboard/Mouse/Gamepad
// - the ImGuiKey enum contains all possible keyboard, mouse and gamepad inputs (e.g. ImGuiKey_A, ImGuiKey_MouseLeft, ImGuiKey_GamepadDpadUp...).
- // - before v1.87, we used ImGuiKey to carry native/user indices as defined by each backends. About use of those legacy ImGuiKey values:
- // - without IMGUI_DISABLE_OBSOLETE_KEYIO (legacy support): you can still use your legacy native/user indices (< 512) according to how your backend/engine stored them in io.KeysDown[], but need to cast them to ImGuiKey.
- // - with IMGUI_DISABLE_OBSOLETE_KEYIO (this is the way forward): any use of ImGuiKey will assert with key < 512. GetKeyIndex() is pass-through and therefore deprecated (gone if IMGUI_DISABLE_OBSOLETE_KEYIO is defined).
+ // - (legacy: before v1.87, we used ImGuiKey to carry native/user indices as defined by each backends. This was obsoleted in 1.87 (2022-02) and completely removed in 1.91.5 (2024-11). See https://github.com/ocornut/imgui/issues/4921)
+ // - (legacy: any use of ImGuiKey will assert when key < 512 to detect passing legacy native/user indices)
IMGUI_API bool IsKeyDown(ImGuiKey key); // is key being held.
IMGUI_API bool IsKeyPressed(ImGuiKey key, bool repeat = true); // was key pressed (went from !Down to Down)? if repeat=true, uses io.KeyRepeatDelay / KeyRepeatRate
IMGUI_API bool IsKeyReleased(ImGuiKey key); // was key released (went from Down to !Down)?
IMGUI_API bool IsKeyChordPressed(ImGuiKeyChord key_chord); // was key chord (mods + key) pressed, e.g. you can pass 'ImGuiMod_Ctrl | ImGuiKey_S' as a key-chord. This doesn't do any routing or focus check, please consider using Shortcut() function instead.
IMGUI_API int GetKeyPressedAmount(ImGuiKey key, 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 const char* GetKeyName(ImGuiKey key); // [DEBUG] returns English name of the key. Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
+ IMGUI_API const char* GetKeyName(ImGuiKey key); // [DEBUG] returns English name of the key. Those names are provided for debugging purpose and are not meant to be saved persistently nor compared.
IMGUI_API void SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard); // Override io.WantCaptureKeyboard flag next frame (said flag is left for your application to handle, typically when true it instructs your app to ignore inputs). e.g. force capture keyboard when your widget is being hovered. This is equivalent to setting "io.WantCaptureKeyboard = want_capture_keyboard"; after the next NewFrame() call.
// Inputs Utilities: Shortcut Testing & Routing [BETA]
// - ImGuiKeyChord = a ImGuiKey + optional ImGuiMod_Alt/ImGuiMod_Ctrl/ImGuiMod_Shift/ImGuiMod_Super.
- // ImGuiKey_C // Accepted by functions taking ImGuiKey or ImGuiKeyChord arguments)
- // ImGuiMod_Ctrl | ImGuiKey_C // Accepted by functions taking ImGuiKeyChord arguments)
+ // ImGuiKey_C // Accepted by functions taking ImGuiKey or ImGuiKeyChord arguments
+ // ImGuiMod_Ctrl | ImGuiKey_C // Accepted by functions taking ImGuiKeyChord arguments
// only ImGuiMod_XXX values are legal to combine with an ImGuiKey. You CANNOT combine two ImGuiKey values.
// - The general idea is that several callers may register interest in a shortcut, and only one owner gets it.
// Parent -> call Shortcut(Ctrl+S) // When Parent is focused, Parent gets the shortcut.
@@ -1034,6 +1117,7 @@ namespace ImGui
IMGUI_API bool IsMouseClicked(ImGuiMouseButton button, bool repeat = false); // did mouse button clicked? (went from !Down to Down). Same as GetMouseClickedCount() == 1.
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? Same as GetMouseClickedCount() == 2. (note that a double-click will also report IsMouseClicked() == true)
+ IMGUI_API bool IsMouseReleasedWithDelay(ImGuiMouseButton button, float delay); // delayed mouse release (use very sparingly!). Generally used with 'delay >= io.MouseDoubleClickTime' + combined with a 'io.MouseClickedLastCount==1' test. This is a very rarely used UI idiom, but some apps use this: e.g. MS Explorer single click on an icon to rename.
IMGUI_API int GetMouseClickedCount(ImGuiMouseButton button); // return the number of successive mouse-clicks at the time where a click happen (otherwise 0).
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
@@ -1045,7 +1129,7 @@ namespace ImGui
IMGUI_API void ResetMouseDragDelta(ImGuiMouseButton button = 0); //
IMGUI_API ImGuiMouseCursor GetMouseCursor(); // get desired mouse cursor shape. Important: 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 mouse cursor shape
- IMGUI_API void SetNextFrameWantCaptureMouse(bool want_capture_mouse); // Override io.WantCaptureMouse flag next frame (said flag is left for your application to handle, typical when true it instucts your app to ignore inputs). This is equivalent to setting "io.WantCaptureMouse = want_capture_mouse;" after the next NewFrame() call.
+ IMGUI_API void SetNextFrameWantCaptureMouse(bool want_capture_mouse); // Override io.WantCaptureMouse flag next frame (said flag is left for your application to handle, typical when true it instructs your app to ignore inputs). This is equivalent to setting "io.WantCaptureMouse = want_capture_mouse;" after the next NewFrame() call.
// Clipboard Utilities
// - Also see the LogToClipboard() function to capture GUI into clipboard, or easily output text data to the clipboard.
@@ -1084,11 +1168,11 @@ namespace ImGui
// (Optional) Platform/OS interface for multi-viewport support
// Read comments around the ImGuiPlatformIO structure for more details.
// Note: You may use GetWindowViewport() to get the current viewport of the current window.
- 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_render_arg = NULL, void* renderer_render_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 backend 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 backends.
- IMGUI_API ImGuiViewport* FindViewportByPlatformHandle(void* platform_handle); // this is a helper for backends. the type platform_handle is decided by the backend (e.g. HWND, MyWindow*, GLFWwindow* etc.)
+ 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_render_arg = NULL, void* renderer_render_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 backend 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 backends.
+ IMGUI_API ImGuiViewport* FindViewportByPlatformHandle(void* platform_handle); // this is a helper for backends. the type platform_handle is decided by the backend (e.g. HWND, MyWindow*, GLFWwindow* etc.)
} // namespace ImGui
@@ -1126,22 +1210,22 @@ enum ImGuiWindowFlags_
ImGuiWindowFlags_NoInputs = ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus,
// [Internal]
+ ImGuiWindowFlags_DockNodeHost = 1 << 23, // Don't use! For internal use by Begin()/NewFrame()
ImGuiWindowFlags_ChildWindow = 1 << 24, // Don't use! For internal use by BeginChild()
ImGuiWindowFlags_Tooltip = 1 << 25, // Don't use! For internal use by BeginTooltip()
ImGuiWindowFlags_Popup = 1 << 26, // Don't use! For internal use by BeginPopup()
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()
// Obsolete names
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ ImGuiWindowFlags_NavFlattened = 1 << 29, // Obsoleted in 1.90.9: Use ImGuiChildFlags_NavFlattened in BeginChild() call.
ImGuiWindowFlags_AlwaysUseWindowPadding = 1 << 30, // Obsoleted in 1.90.0: Use ImGuiChildFlags_AlwaysUseWindowPadding in BeginChild() call.
- ImGuiWindowFlags_NavFlattened = 1 << 31, // Obsoleted in 1.90.9: Use ImGuiChildFlags_NavFlattened in BeginChild() call.
#endif
};
// Flags for ImGui::BeginChild()
-// (Legacy: bit 0 must always correspond to ImGuiChildFlags_Borders to be backward compatible with old API using 'bool border = false'.
+// (Legacy: bit 0 must always correspond to ImGuiChildFlags_Borders to be backward compatible with old API using 'bool border = false'.)
// About using AutoResizeX/AutoResizeY flags:
// - May be combined with SetNextWindowSizeConstraints() to set a min/max size for each axis (see "Demo->Child->Auto-resize with Constraints").
// - Size measurement for a given axis is only performed when the child window is within visible boundaries, or is just appearing.
@@ -1209,13 +1293,25 @@ enum ImGuiInputTextFlags_
ImGuiInputTextFlags_NoHorizontalScroll = 1 << 15, // Disable following the cursor horizontally
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().
+ // Elide display / Alignment
+ ImGuiInputTextFlags_ElideLeft = 1 << 17, // When text doesn't fit, elide left side to ensure right side stays visible. Useful for path/filenames. Single-line only!
+
// Callback features
- ImGuiInputTextFlags_CallbackCompletion = 1 << 17, // Callback on pressing TAB (for completion handling)
- ImGuiInputTextFlags_CallbackHistory = 1 << 18, // Callback on pressing Up/Down arrows (for history handling)
- ImGuiInputTextFlags_CallbackAlways = 1 << 19, // Callback on each iteration. User code may query cursor position, modify text buffer.
- ImGuiInputTextFlags_CallbackCharFilter = 1 << 20, // Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard.
- ImGuiInputTextFlags_CallbackResize = 1 << 21, // 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 << 22, // 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)
+ ImGuiInputTextFlags_CallbackCompletion = 1 << 18, // Callback on pressing TAB (for completion handling)
+ ImGuiInputTextFlags_CallbackHistory = 1 << 19, // Callback on pressing Up/Down arrows (for history handling)
+ ImGuiInputTextFlags_CallbackAlways = 1 << 20, // Callback on each iteration. User code may query cursor position, modify text buffer.
+ ImGuiInputTextFlags_CallbackCharFilter = 1 << 21, // Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard.
+ ImGuiInputTextFlags_CallbackResize = 1 << 22, // 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 << 23, // Callback on any edit. Note that InputText() already returns true on edit + you can always use IsItemEdited(). The callback is useful to manipulate the underlying buffer while focus is active.
+
+ // Multi-line Word-Wrapping [BETA]
+ // - Not well tested yet. Please report any incorrect cursor movement, selection behavior etc. bug to https://github.com/ocornut/imgui/issues/3237.
+ // - Wrapping style is not ideal. Wrapping of long words/sections (e.g. words larger than total available width) may be particularly unpleasing.
+ // - Wrapping width needs to always account for the possibility of a vertical scrollbar.
+ // - It is much slower than regular text fields.
+ // Ballpark estimate of cost on my 2019 desktop PC: for a 100 KB text buffer: +~0.3 ms (Optimized) / +~1.0 ms (Debug build).
+ // The CPU cost is very roughly proportional to text length, so a 10 KB buffer should cost about ten times less.
+ ImGuiInputTextFlags_WordWrap = 1 << 24, // InputTextMultine(): word-wrap lines that are too long.
// Obsolete names
//ImGuiInputTextFlags_AlwaysInsertMode = ImGuiInputTextFlags_AlwaysOverwrite // [renamed in 1.82] name was not matching behavior
@@ -1238,14 +1334,23 @@ enum ImGuiTreeNodeFlags_
ImGuiTreeNodeFlags_FramePadding = 1 << 10, // Use FramePadding (even for an unframed text node) to vertically align text baseline to regular widget height. Equivalent to calling AlignTextToFramePadding() before the node.
ImGuiTreeNodeFlags_SpanAvailWidth = 1 << 11, // Extend hit box to the right-most edge, even if not framed. This is not the default in order to allow adding other items on the same line without using AllowOverlap mode.
ImGuiTreeNodeFlags_SpanFullWidth = 1 << 12, // Extend hit box to the left-most and right-most edges (cover the indent area).
- ImGuiTreeNodeFlags_SpanTextWidth = 1 << 13, // Narrow hit box + narrow hovering highlight, will only cover the label text.
- ImGuiTreeNodeFlags_SpanAllColumns = 1 << 14, // Frame will span all columns of its container table (text will still fit in current column)
- ImGuiTreeNodeFlags_NavLeftJumpsBackHere = 1 << 15, // (WIP) Nav: left direction may move to this TreeNode() from any of its child (items submitted between TreeNode and TreePop)
+ ImGuiTreeNodeFlags_SpanLabelWidth = 1 << 13, // Narrow hit box + narrow hovering highlight, will only cover the label text.
+ ImGuiTreeNodeFlags_SpanAllColumns = 1 << 14, // Frame will span all columns of its container table (label will still fit in current column)
+ ImGuiTreeNodeFlags_LabelSpanAllColumns = 1 << 15, // Label will span all columns of its container table
//ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 16, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible
+ ImGuiTreeNodeFlags_NavLeftJumpsToParent = 1 << 17, // Nav: left arrow moves back to parent. This is processed in TreePop() when there's an unfullfilled Left nav request remaining.
ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_NoAutoOpenOnLog,
+ // [EXPERIMENTAL] Draw lines connecting TreeNode hierarchy. Discuss in GitHub issue #2920.
+ // Default value is pulled from style.TreeLinesFlags. May be overridden in TreeNode calls.
+ ImGuiTreeNodeFlags_DrawLinesNone = 1 << 18, // No lines drawn
+ ImGuiTreeNodeFlags_DrawLinesFull = 1 << 19, // Horizontal lines to child nodes. Vertical line drawn down to TreePop() position: cover full contents. Faster (for large trees).
+ ImGuiTreeNodeFlags_DrawLinesToNodes = 1 << 20, // Horizontal lines to child nodes. Vertical line drawn down to bottom-most child node. Slower (for large trees).
+
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
- ImGuiTreeNodeFlags_AllowItemOverlap = ImGuiTreeNodeFlags_AllowOverlap, // Renamed in 1.89.7
+ ImGuiTreeNodeFlags_NavLeftJumpsBackHere = ImGuiTreeNodeFlags_NavLeftJumpsToParent, // Renamed in 1.92.0
+ ImGuiTreeNodeFlags_SpanTextWidth = ImGuiTreeNodeFlags_SpanLabelWidth, // Renamed in 1.90.7
+ ImGuiTreeNodeFlags_AllowItemOverlap = ImGuiTreeNodeFlags_AllowOverlap, // Renamed in 1.89.7
#endif
};
@@ -1284,6 +1389,7 @@ enum ImGuiSelectableFlags_
ImGuiSelectableFlags_Disabled = 1 << 3, // Cannot be selected, display grayed out text
ImGuiSelectableFlags_AllowOverlap = 1 << 4, // (WIP) Hit testing to allow subsequent widgets to overlap this one
ImGuiSelectableFlags_Highlight = 1 << 5, // Make the item be displayed as if it is hovered
+ ImGuiSelectableFlags_SelectOnNav = 1 << 6, // Auto-select when moved into, unless Ctrl is held. Automatic when in a BeginMultiSelect() block.
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
ImGuiSelectableFlags_DontClosePopups = ImGuiSelectableFlags_NoAutoClosePopups, // Renamed in 1.91.0
@@ -1317,10 +1423,17 @@ enum ImGuiTabBarFlags_
ImGuiTabBarFlags_NoTabListScrollingButtons = 1 << 4, // Disable scrolling buttons (apply when fitting policy is ImGuiTabBarFlags_FittingPolicyScroll)
ImGuiTabBarFlags_NoTooltip = 1 << 5, // Disable tooltips when hovering a tab
ImGuiTabBarFlags_DrawSelectedOverline = 1 << 6, // Draw selected overline markers over selected tab
- ImGuiTabBarFlags_FittingPolicyResizeDown = 1 << 7, // Resize tabs when they don't fit
- ImGuiTabBarFlags_FittingPolicyScroll = 1 << 8, // Add scroll buttons when tabs don't fit
- ImGuiTabBarFlags_FittingPolicyMask_ = ImGuiTabBarFlags_FittingPolicyResizeDown | ImGuiTabBarFlags_FittingPolicyScroll,
- ImGuiTabBarFlags_FittingPolicyDefault_ = ImGuiTabBarFlags_FittingPolicyResizeDown,
+
+ // Fitting/Resize policy
+ ImGuiTabBarFlags_FittingPolicyMixed = 1 << 7, // Shrink down tabs when they don't fit, until width is style.TabMinWidthShrink, then enable scrolling buttons.
+ ImGuiTabBarFlags_FittingPolicyShrink = 1 << 8, // Shrink down tabs when they don't fit
+ ImGuiTabBarFlags_FittingPolicyScroll = 1 << 9, // Enable scrolling buttons when tabs don't fit
+ ImGuiTabBarFlags_FittingPolicyMask_ = ImGuiTabBarFlags_FittingPolicyMixed | ImGuiTabBarFlags_FittingPolicyShrink | ImGuiTabBarFlags_FittingPolicyScroll,
+ ImGuiTabBarFlags_FittingPolicyDefault_ = ImGuiTabBarFlags_FittingPolicyMixed,
+
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ ImGuiTabBarFlags_FittingPolicyResizeDown = ImGuiTabBarFlags_FittingPolicyShrink, // Renamed in 1.92.2
+#endif
};
// Flags for ImGui::BeginTabItem()
@@ -1453,6 +1566,7 @@ enum ImGuiDataType_
ImGuiDataType_Float, // float
ImGuiDataType_Double, // double
ImGuiDataType_Bool, // bool (provided for user convenience, not supported by scalar widgets)
+ ImGuiDataType_String, // char* (provided for user convenience, not supported by scalar widgets)
ImGuiDataType_COUNT
};
@@ -1475,21 +1589,18 @@ enum ImGuiSortDirection : ImU8
ImGuiSortDirection_Descending = 2 // Descending = 9->0, Z->A etc.
};
-// Since 1.90, defining IMGUI_DISABLE_OBSOLETE_FUNCTIONS automatically defines IMGUI_DISABLE_OBSOLETE_KEYIO as well.
-#if defined(IMGUI_DISABLE_OBSOLETE_FUNCTIONS) && !defined(IMGUI_DISABLE_OBSOLETE_KEYIO)
-#define IMGUI_DISABLE_OBSOLETE_KEYIO
-#endif
-
// A key identifier (ImGuiKey_XXX or ImGuiMod_XXX value): can represent Keyboard, Mouse and Gamepad values.
-// All our named keys are >= 512. Keys value 0 to 511 are left unused as legacy native/opaque key values (< 1.87).
-// Since >= 1.89 we increased typing (went from int to enum), some legacy code may need a cast to ImGuiKey.
-// Read details about the 1.87 and 1.89 transition : https://github.com/ocornut/imgui/issues/4921
+// All our named keys are >= 512. Keys value 0 to 511 are left unused and were legacy native/opaque key values (< 1.87).
+// Support for legacy keys was completely removed in 1.91.5.
+// Read details about the 1.87+ transition : https://github.com/ocornut/imgui/issues/4921
// Note that "Keys" related to physical keys and are not the same concept as input "Characters", the later are submitted via io.AddInputCharacter().
// The keyboard key enum values are named after the keys on a standard US keyboard, and on other keyboard types the keys reported may not match the keycaps.
enum ImGuiKey : int
{
// Keyboard
ImGuiKey_None = 0,
+ ImGuiKey_NamedKey_BEGIN = 512, // First valid key value (other than 0)
+
ImGuiKey_Tab = 512, // == ImGuiKey_NamedKey_BEGIN
ImGuiKey_LeftArrow,
ImGuiKey_RightArrow,
@@ -1505,7 +1616,7 @@ enum ImGuiKey : int
ImGuiKey_Space,
ImGuiKey_Enter,
ImGuiKey_Escape,
- ImGuiKey_LeftCtrl, ImGuiKey_LeftShift, ImGuiKey_LeftAlt, ImGuiKey_LeftSuper,
+ ImGuiKey_LeftCtrl, ImGuiKey_LeftShift, ImGuiKey_LeftAlt, ImGuiKey_LeftSuper, // Also see ImGuiMod_Ctrl, ImGuiMod_Shift, ImGuiMod_Alt, ImGuiMod_Super below!
ImGuiKey_RightCtrl, ImGuiKey_RightShift, ImGuiKey_RightAlt, ImGuiKey_RightSuper,
ImGuiKey_Menu,
ImGuiKey_0, ImGuiKey_1, ImGuiKey_2, ImGuiKey_3, ImGuiKey_4, ImGuiKey_5, ImGuiKey_6, ImGuiKey_7, ImGuiKey_8, ImGuiKey_9,
@@ -1543,33 +1654,36 @@ enum ImGuiKey : int
ImGuiKey_KeypadEqual,
ImGuiKey_AppBack, // Available on some keyboard/mouses. Often referred as "Browser Back"
ImGuiKey_AppForward,
+ ImGuiKey_Oem102, // Non-US backslash.
- // Gamepad (some of those are analog values, 0.0f to 1.0f) // NAVIGATION ACTION
+ // Gamepad
+ // (analog values are 0.0f to 1.0f)
// (download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets)
- ImGuiKey_GamepadStart, // Menu (Xbox) + (Switch) Start/Options (PS)
- ImGuiKey_GamepadBack, // View (Xbox) - (Switch) Share (PS)
- ImGuiKey_GamepadFaceLeft, // X (Xbox) Y (Switch) Square (PS) // Tap: Toggle Menu. Hold: Windowing mode (Focus/Move/Resize windows)
- ImGuiKey_GamepadFaceRight, // B (Xbox) A (Switch) Circle (PS) // Cancel / Close / Exit
- ImGuiKey_GamepadFaceUp, // Y (Xbox) X (Switch) Triangle (PS) // Text Input / On-screen Keyboard
- ImGuiKey_GamepadFaceDown, // A (Xbox) B (Switch) Cross (PS) // Activate / Open / Toggle / Tweak
- ImGuiKey_GamepadDpadLeft, // D-pad Left // Move / Tweak / Resize Window (in Windowing mode)
- ImGuiKey_GamepadDpadRight, // D-pad Right // Move / Tweak / Resize Window (in Windowing mode)
- ImGuiKey_GamepadDpadUp, // D-pad Up // Move / Tweak / Resize Window (in Windowing mode)
- ImGuiKey_GamepadDpadDown, // D-pad Down // Move / Tweak / Resize Window (in Windowing mode)
- ImGuiKey_GamepadL1, // L Bumper (Xbox) L (Switch) L1 (PS) // Tweak Slower / Focus Previous (in Windowing mode)
- ImGuiKey_GamepadR1, // R Bumper (Xbox) R (Switch) R1 (PS) // Tweak Faster / Focus Next (in Windowing mode)
- ImGuiKey_GamepadL2, // L Trig. (Xbox) ZL (Switch) L2 (PS) [Analog]
- ImGuiKey_GamepadR2, // R Trig. (Xbox) ZR (Switch) R2 (PS) [Analog]
- ImGuiKey_GamepadL3, // L Stick (Xbox) L3 (Switch) L3 (PS)
- ImGuiKey_GamepadR3, // R Stick (Xbox) R3 (Switch) R3 (PS)
- ImGuiKey_GamepadLStickLeft, // [Analog] // Move Window (in Windowing mode)
- ImGuiKey_GamepadLStickRight, // [Analog] // Move Window (in Windowing mode)
- ImGuiKey_GamepadLStickUp, // [Analog] // Move Window (in Windowing mode)
- ImGuiKey_GamepadLStickDown, // [Analog] // Move Window (in Windowing mode)
- ImGuiKey_GamepadRStickLeft, // [Analog]
- ImGuiKey_GamepadRStickRight, // [Analog]
- ImGuiKey_GamepadRStickUp, // [Analog]
- ImGuiKey_GamepadRStickDown, // [Analog]
+ // // XBOX | SWITCH | PLAYSTA. | -> ACTION
+ ImGuiKey_GamepadStart, // Menu | + | Options |
+ ImGuiKey_GamepadBack, // View | - | Share |
+ ImGuiKey_GamepadFaceLeft, // X | Y | Square | Tap: Toggle Menu. Hold: Windowing mode (Focus/Move/Resize windows)
+ ImGuiKey_GamepadFaceRight, // B | A | Circle | Cancel / Close / Exit
+ ImGuiKey_GamepadFaceUp, // Y | X | Triangle | Text Input / On-screen Keyboard
+ ImGuiKey_GamepadFaceDown, // A | B | Cross | Activate / Open / Toggle / Tweak
+ ImGuiKey_GamepadDpadLeft, // D-pad Left | " | " | Move / Tweak / Resize Window (in Windowing mode)
+ ImGuiKey_GamepadDpadRight, // D-pad Right | " | " | Move / Tweak / Resize Window (in Windowing mode)
+ ImGuiKey_GamepadDpadUp, // D-pad Up | " | " | Move / Tweak / Resize Window (in Windowing mode)
+ ImGuiKey_GamepadDpadDown, // D-pad Down | " | " | Move / Tweak / Resize Window (in Windowing mode)
+ ImGuiKey_GamepadL1, // L Bumper | L | L1 | Tweak Slower / Focus Previous (in Windowing mode)
+ ImGuiKey_GamepadR1, // R Bumper | R | R1 | Tweak Faster / Focus Next (in Windowing mode)
+ ImGuiKey_GamepadL2, // L Trigger | ZL | L2 | [Analog]
+ ImGuiKey_GamepadR2, // R Trigger | ZR | R2 | [Analog]
+ ImGuiKey_GamepadL3, // L Stick | L3 | L3 |
+ ImGuiKey_GamepadR3, // R Stick | R3 | R3 |
+ ImGuiKey_GamepadLStickLeft, // | | | [Analog] Move Window (in Windowing mode)
+ ImGuiKey_GamepadLStickRight, // | | | [Analog] Move Window (in Windowing mode)
+ ImGuiKey_GamepadLStickUp, // | | | [Analog] Move Window (in Windowing mode)
+ ImGuiKey_GamepadLStickDown, // | | | [Analog] Move Window (in Windowing mode)
+ ImGuiKey_GamepadRStickLeft, // | | | [Analog]
+ ImGuiKey_GamepadRStickRight, // | | | [Analog]
+ ImGuiKey_GamepadRStickUp, // | | | [Analog]
+ ImGuiKey_GamepadRStickDown, // | | | [Analog]
// Aliases: Mouse Buttons (auto-submitted from AddMouseButtonEvent() calls)
// - This is mirroring the data also written to io.MouseDown[], io.MouseWheel, in a format allowing them to be accessed via standard key API.
@@ -1577,11 +1691,15 @@ enum ImGuiKey : int
// [Internal] Reserved for mod storage
ImGuiKey_ReservedForModCtrl, ImGuiKey_ReservedForModShift, ImGuiKey_ReservedForModAlt, ImGuiKey_ReservedForModSuper,
- ImGuiKey_COUNT,
+
+ // [Internal] If you need to iterate all keys (for e.g. an input mapper) you may use ImGuiKey_NamedKey_BEGIN..ImGuiKey_NamedKey_END.
+ ImGuiKey_NamedKey_END,
+ ImGuiKey_NamedKey_COUNT = ImGuiKey_NamedKey_END - ImGuiKey_NamedKey_BEGIN,
// Keyboard Modifiers (explicitly submitted by backend via AddKeyEvent() calls)
- // - This is mirroring the data also written to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper, in a format allowing
- // them to be accessed via standard key API, allowing calls such as IsKeyPressed(), IsKeyReleased(), querying duration etc.
+ // - Any functions taking a ImGuiKeyChord parameter can binary-or those with regular keys, e.g. Shortcut(ImGuiMod_Ctrl | ImGuiKey_S).
+ // - Those are written back into io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper for convenience,
+ // but may be accessed via standard key API such as IsKeyPressed(), IsKeyReleased(), querying duration etc.
// - Code polling every key (e.g. an interface to detect a key press for input mapping) might want to ignore those
// and prefer using the real keys (e.g. ImGuiKey_LeftCtrl, ImGuiKey_RightCtrl instead of ImGuiMod_Ctrl).
// - In theory the value of keyboard modifiers should be roughly equivalent to a logical or of the equivalent left/right keys.
@@ -1595,21 +1713,8 @@ enum ImGuiKey : int
ImGuiMod_Super = 1 << 15, // Windows/Super (non-macOS), Ctrl (macOS)
ImGuiMod_Mask_ = 0xF000, // 4-bits
- // [Internal] Prior to 1.87 we required user to fill io.KeysDown[512] using their own native index + the io.KeyMap[] array.
- // We are ditching this method but keeping a legacy path for user code doing e.g. IsKeyPressed(MY_NATIVE_KEY_CODE)
- // If you need to iterate all keys (for e.g. an input mapper) you may use ImGuiKey_NamedKey_BEGIN..ImGuiKey_NamedKey_END.
- ImGuiKey_NamedKey_BEGIN = 512,
- ImGuiKey_NamedKey_END = ImGuiKey_COUNT,
- ImGuiKey_NamedKey_COUNT = ImGuiKey_NamedKey_END - ImGuiKey_NamedKey_BEGIN,
-#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
- ImGuiKey_KeysData_SIZE = ImGuiKey_NamedKey_COUNT, // Size of KeysData[]: only hold named keys
- ImGuiKey_KeysData_OFFSET = ImGuiKey_NamedKey_BEGIN, // Accesses to io.KeysData[] must use (key - ImGuiKey_KeysData_OFFSET) index.
-#else
- ImGuiKey_KeysData_SIZE = ImGuiKey_COUNT, // Size of KeysData[]: hold legacy 0..512 keycodes + named keys
- ImGuiKey_KeysData_OFFSET = 0, // Accesses to io.KeysData[] must use (key - ImGuiKey_KeysData_OFFSET) index.
-#endif
-
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ ImGuiKey_COUNT = ImGuiKey_NamedKey_END, // Obsoleted in 1.91.5 because it was extremely misleading (since named keys don't start at 0 anymore)
ImGuiMod_Shortcut = ImGuiMod_Ctrl, // Removed in 1.90.7, you can now simply use ImGuiMod_Ctrl
ImGuiKey_ModCtrl = ImGuiMod_Ctrl, ImGuiKey_ModShift = ImGuiMod_Shift, ImGuiKey_ModAlt = ImGuiMod_Alt, ImGuiKey_ModSuper = ImGuiMod_Super, // Renamed in 1.89
//ImGuiKey_KeyPadEnter = ImGuiKey_KeypadEnter, // Renamed in 1.87
@@ -1641,18 +1746,6 @@ enum ImGuiInputFlags_
ImGuiInputFlags_Tooltip = 1 << 18, // Automatically display a tooltip when hovering item [BETA] Unsure of right api (opt-in/opt-out)
};
-#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
-// OBSOLETED in 1.88 (from July 2022): ImGuiNavInput and io.NavInputs[].
-// Official backends between 1.60 and 1.86: will keep working and feed gamepad inputs as long as IMGUI_DISABLE_OBSOLETE_KEYIO is not set.
-// Custom backends: feed gamepad inputs via io.AddKeyEvent() and ImGuiKey_GamepadXXX enums.
-enum ImGuiNavInput
-{
- ImGuiNavInput_Activate, ImGuiNavInput_Cancel, ImGuiNavInput_Input, ImGuiNavInput_Menu, ImGuiNavInput_DpadLeft, ImGuiNavInput_DpadRight, ImGuiNavInput_DpadUp, ImGuiNavInput_DpadDown,
- ImGuiNavInput_LStickLeft, ImGuiNavInput_LStickRight, ImGuiNavInput_LStickUp, ImGuiNavInput_LStickDown, ImGuiNavInput_FocusPrev, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakSlow, ImGuiNavInput_TweakFast,
- ImGuiNavInput_COUNT,
-};
-#endif
-
// Configuration flags stored in io.ConfigFlags. Set by user/application.
enum ImGuiConfigFlags_
{
@@ -1669,8 +1762,6 @@ enum ImGuiConfigFlags_
// [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 ImGuiBackendFlags_PlatformHasViewports + ImGuiBackendFlags_RendererHasViewports set by the respective backends)
- 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 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.
@@ -1679,6 +1770,8 @@ enum ImGuiConfigFlags_
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
ImGuiConfigFlags_NavEnableSetMousePos = 1 << 2, // [moved/renamed in 1.91.4] -> use bool io.ConfigNavMoveSetMousePos
ImGuiConfigFlags_NavNoCaptureKeyboard = 1 << 3, // [moved/renamed in 1.91.4] -> use bool io.ConfigNavCaptureKeyboard
+ ImGuiConfigFlags_DpiEnableScaleFonts = 1 << 14, // [moved/renamed in 1.92.0] -> use bool io.ConfigDpiScaleFonts
+ ImGuiConfigFlags_DpiEnableScaleViewports= 1 << 15, // [moved/renamed in 1.92.0] -> use bool io.ConfigDpiScaleViewports
#endif
};
@@ -1690,6 +1783,7 @@ enum ImGuiBackendFlags_
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 io.ConfigNavMoveSetMousePos 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.
+ ImGuiBackendFlags_RendererHasTextures = 1 << 4, // Backend Renderer supports ImTextureData requests to create/update/destroy textures. This enables incremental texture updates and texture reloads. See https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md for instructions on how to upgrade your custom backend.
// [BETA] Viewports
ImGuiBackendFlags_PlatformHasViewports = 1 << 10, // Backend Platform supports multiple viewports.
@@ -1733,6 +1827,7 @@ enum ImGuiCol_
ImGuiCol_ResizeGrip, // Resize grip in lower-right and lower-left corners of windows.
ImGuiCol_ResizeGripHovered,
ImGuiCol_ResizeGripActive,
+ ImGuiCol_InputTextCursor, // InputText cursor/caret
ImGuiCol_TabHovered, // Tab background, when hovered
ImGuiCol_Tab, // Tab background, when tab-bar is focused & tab is unselected
ImGuiCol_TabSelected, // Tab background, when tab-bar is focused & tab is selected
@@ -1752,7 +1847,8 @@ enum ImGuiCol_
ImGuiCol_TableRowBg, // Table row background (even rows)
ImGuiCol_TableRowBgAlt, // Table row background (odd rows)
ImGuiCol_TextLink, // Hyperlink color
- ImGuiCol_TextSelectedBg,
+ ImGuiCol_TextSelectedBg, // Selected text inside an InputText
+ ImGuiCol_TreeLines, // Tree node hierarchy outlines when using ImGuiTreeNodeFlags_DrawLines
ImGuiCol_DragDropTarget, // Rectangle highlighting a drop target
ImGuiCol_NavCursor, // Color of keyboard/gamepad navigation cursor/rectangle, when visible
ImGuiCol_NavWindowingHighlight, // Highlight window when using CTRL+TAB
@@ -1799,14 +1895,20 @@ enum ImGuiStyleVar_
ImGuiStyleVar_CellPadding, // ImVec2 CellPadding
ImGuiStyleVar_ScrollbarSize, // float ScrollbarSize
ImGuiStyleVar_ScrollbarRounding, // float ScrollbarRounding
+ ImGuiStyleVar_ScrollbarPadding, // float ScrollbarPadding
ImGuiStyleVar_GrabMinSize, // float GrabMinSize
ImGuiStyleVar_GrabRounding, // float GrabRounding
+ ImGuiStyleVar_ImageBorderSize, // float ImageBorderSize
ImGuiStyleVar_TabRounding, // float TabRounding
ImGuiStyleVar_TabBorderSize, // float TabBorderSize
+ ImGuiStyleVar_TabMinWidthBase, // float TabMinWidthBase
+ ImGuiStyleVar_TabMinWidthShrink, // float TabMinWidthShrink
ImGuiStyleVar_TabBarBorderSize, // float TabBarBorderSize
ImGuiStyleVar_TabBarOverlineSize, // float TabBarOverlineSize
ImGuiStyleVar_TableAngledHeadersAngle, // float TableAngledHeadersAngle
ImGuiStyleVar_TableAngledHeadersTextAlign,// ImVec2 TableAngledHeadersTextAlign
+ ImGuiStyleVar_TreeLinesSize, // float TreeLinesSize
+ ImGuiStyleVar_TreeLinesRounding, // float TreeLinesRounding
ImGuiStyleVar_ButtonTextAlign, // ImVec2 ButtonTextAlign
ImGuiStyleVar_SelectableTextAlign, // ImVec2 SelectableTextAlign
ImGuiStyleVar_SeparatorTextBorderSize, // float SeparatorTextBorderSize
@@ -1842,10 +1944,16 @@ enum ImGuiColorEditFlags_
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)
+ // Alpha preview
+ // - Prior to 1.91.8 (2025/01/21): alpha was made opaque in the preview by default using old name ImGuiColorEditFlags_AlphaPreview.
+ // - We now display the preview as transparent by default. You can use ImGuiColorEditFlags_AlphaOpaque to use old behavior.
+ // - The new flags may be combined better and allow finer controls.
+ ImGuiColorEditFlags_AlphaOpaque = 1 << 11, // // ColorEdit, ColorPicker, ColorButton: disable alpha in the preview,. Contrary to _NoAlpha it may still be edited when calling ColorEdit4()/ColorPicker4(). For ColorButton() this does the same as _NoAlpha.
+ ImGuiColorEditFlags_AlphaNoBg = 1 << 12, // // ColorEdit, ColorPicker, ColorButton: disable rendering a checkerboard background behind transparent color.
+ ImGuiColorEditFlags_AlphaPreviewHalf= 1 << 13, // // ColorEdit, ColorPicker, ColorButton: display half opaque / half transparent preview.
+
// User Options (right-click on widget to change some of them).
ImGuiColorEditFlags_AlphaBar = 1 << 16, // // ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker.
- ImGuiColorEditFlags_AlphaPreview = 1 << 17, // // ColorEdit, ColorPicker, ColorButton: display preview as a transparent color over a checkerboard, instead of opaque.
- ImGuiColorEditFlags_AlphaPreviewHalf= 1 << 18, // // ColorEdit, ColorPicker, ColorButton: display half opaque / half checkerboard, instead of opaque.
ImGuiColorEditFlags_HDR = 1 << 19, // // (WIP) ColorEdit: Currently only disable 0.0f..1.0f limits in RGBA edition (note: you probably want to use ImGuiColorEditFlags_Float flag as well).
ImGuiColorEditFlags_DisplayRGB = 1 << 20, // [Display] // ColorEdit: override _display_ type among RGB/HSV/Hex. ColorPicker: select any combination using one or more of RGB/HSV/Hex.
ImGuiColorEditFlags_DisplayHSV = 1 << 21, // [Display] // "
@@ -1862,12 +1970,16 @@ enum ImGuiColorEditFlags_
ImGuiColorEditFlags_DefaultOptions_ = ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_PickerHueBar,
// [Internal] Masks
+ ImGuiColorEditFlags_AlphaMask_ = ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaOpaque | ImGuiColorEditFlags_AlphaNoBg | ImGuiColorEditFlags_AlphaPreviewHalf,
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
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ ImGuiColorEditFlags_AlphaPreview = 0, // [Removed in 1.91.8] This is the default now. Will display a checkerboard unless ImGuiColorEditFlags_AlphaNoBg is set.
+#endif
//ImGuiColorEditFlags_RGB = ImGuiColorEditFlags_DisplayRGB, ImGuiColorEditFlags_HSV = ImGuiColorEditFlags_DisplayHSV, ImGuiColorEditFlags_HEX = ImGuiColorEditFlags_DisplayHex // [renamed in 1.69]
};
@@ -1883,6 +1995,7 @@ enum ImGuiSliderFlags_
ImGuiSliderFlags_WrapAround = 1 << 8, // Enable wrapping around from max to min and from min to max. Only supported by DragXXX() functions for now.
ImGuiSliderFlags_ClampOnInput = 1 << 9, // Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds.
ImGuiSliderFlags_ClampZeroRange = 1 << 10, // Clamp even if min==max==0.0f. Otherwise due to legacy reason DragXXX functions don't clamp with those values. When your clamping limits are dynamic you almost always want to use it.
+ ImGuiSliderFlags_NoSpeedTweaks = 1 << 11, // Disable keyboard modifiers altering tweak speed. Useful if you want to alter tweak speed yourself based on your own logic.
ImGuiSliderFlags_AlwaysClamp = ImGuiSliderFlags_ClampOnInput | ImGuiSliderFlags_ClampZeroRange,
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.
};
@@ -1910,6 +2023,8 @@ 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_Wait, // When waiting for something to process/load.
+ ImGuiMouseCursor_Progress, // When waiting for something to process/load, but application is still interactive.
ImGuiMouseCursor_NotAllowed, // When hovering something with disallowed interaction. Usually a crossed circle.
ImGuiMouseCursor_COUNT
};
@@ -2158,7 +2273,7 @@ struct ImVector
// Constructors, destructor
inline ImVector() { Size = Capacity = 0; Data = NULL; }
inline ImVector(const ImVector<T>& src) { Size = Capacity = 0; Data = NULL; operator=(src); }
- inline ImVector<T>& operator=(const ImVector<T>& src) { clear(); resize(src.Size); if (src.Data) memcpy(Data, src.Data, (size_t)Size * sizeof(T)); return *this; }
+ inline ImVector<T>& operator=(const ImVector<T>& src) { clear(); resize(src.Size); if (Data && src.Data) memcpy(Data, src.Data, (size_t)Size * sizeof(T)); return *this; }
inline ~ImVector() { if (Data) IM_FREE(Data); } // Important: does not destruct anything
inline void clear() { if (Data) { Size = Capacity = 0; IM_FREE(Data); Data = NULL; } } // Important: does not destruct anything
@@ -2218,11 +2333,18 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE
struct ImGuiStyle
{
+ // Font scaling
+ // - recap: ImGui::GetFontSize() == FontSizeBase * (FontScaleMain * FontScaleDpi * other_scaling_factors)
+ float FontSizeBase; // Current base font size before external global factors are applied. Use PushFont(NULL, size) to modify. Use ImGui::GetFontSize() to obtain scaled value.
+ float FontScaleMain; // Main global scale factor. May be set by application once, or exposed to end-user.
+ float FontScaleDpi; // Additional global scale factor from viewport/monitor contents scale. When io.ConfigDpiScaleFonts is enabled, this is automatically overwritten when changing monitor DPI.
+
float Alpha; // Global alpha applies to everything in Dear ImGui.
float DisabledAlpha; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
ImVec2 WindowPadding; // Padding within a window.
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).
+ float WindowBorderHoverPadding; // Hit-testing extent outside/inside resizing border. Also extend determination of hovered window. Generally meaningfully larger than WindowBorderSize to make it easy to reach borders.
ImVec2 WindowMinSize; // Minimum window size. This is a global setting. If you want to constrain individual windows, use SetNextWindowSizeConstraints().
ImVec2 WindowTitleAlign; // Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically centered.
ImGuiDir WindowMenuButtonPosition; // Side of the collapsing/docking button in the title bar (None/Left/Right). Defaults to ImGuiDir_Left.
@@ -2241,16 +2363,24 @@ struct ImGuiStyle
float ColumnsMinSpacing; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
float ScrollbarSize; // Width of the vertical scrollbar, Height of the horizontal scrollbar.
float ScrollbarRounding; // Radius of grab corners for scrollbar.
+ float ScrollbarPadding; // Padding of scrollbar grab within its frame (same for both axises).
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 ImageBorderSize; // Thickness of border around Image() calls.
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 appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
+ float TabMinWidthBase; // Minimum tab width, to make tabs larger than their contents. TabBar buttons are not affected.
+ float TabMinWidthShrink; // Minimum tab width after shrinking, when using ImGuiTabBarFlags_FittingPolicyMixed policy.
+ float TabCloseButtonMinWidthSelected; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width.
+ float TabCloseButtonMinWidthUnselected; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width. FLT_MAX: never show close button when unselected.
float TabBarBorderSize; // Thickness of tab-bar separator, which takes on the tab active color to denote focus.
float TabBarOverlineSize; // Thickness of tab-bar overline, which highlights the selected tab-bar.
float TableAngledHeadersAngle; // Angle of angled headers (supported values range from -50.0f degrees to +50.0f degrees).
ImVec2 TableAngledHeadersTextAlign;// Alignment of angled headers within the cell
+ ImGuiTreeNodeFlags TreeLinesFlags; // Default way to draw lines connecting TreeNode hierarchy. ImGuiTreeNodeFlags_DrawLinesNone or ImGuiTreeNodeFlags_DrawLinesFull or ImGuiTreeNodeFlags_DrawLinesToNodes.
+ float TreeLinesSize; // Thickness of outlines when using ImGuiTreeNodeFlags_DrawLines.
+ float TreeLinesRounding; // Radius of lines connecting child nodes to the vertical line.
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. 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.
@@ -2259,6 +2389,7 @@ struct ImGuiStyle
ImVec2 SeparatorTextPadding; // Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y.
ImVec2 DisplayWindowPadding; // Apply to regular windows: amount which we enforce to keep visible when moving near edges of your screen.
ImVec2 DisplaySafeAreaPadding; // Apply to every windows, menus, popups, tooltips: amount where we avoid displaying contents. Adjust if you cannot see the edges of your screen (e.g. on a TV where scaling has not been configured).
+ bool DockingNodeHasCloseButton; // Docking node has their own CloseButton() to close all docked windows.
float DockingSeparatorSize; // Thickness of resizing border between docked windows
float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). We apply per-monitor DPI scaling over this scale. May be removed later.
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).
@@ -2266,6 +2397,8 @@ struct ImGuiStyle
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 CircleTessellationMaxError; // 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.
+
+ // Colors
ImVec4 Colors[ImGuiCol_COUNT];
// Behaviors
@@ -2276,8 +2409,18 @@ struct ImGuiStyle
ImGuiHoveredFlags HoverFlagsForTooltipMouse;// Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse.
ImGuiHoveredFlags HoverFlagsForTooltipNav; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad.
- IMGUI_API ImGuiStyle();
- IMGUI_API void ScaleAllSizes(float scale_factor);
+ // [Internal]
+ float _MainScale; // FIXME-WIP: Reference scale, as applied by ScaleAllSizes().
+ float _NextFrameFontSizeBase; // FIXME: Temporary hack until we finish remaining work.
+
+ // Functions
+ IMGUI_API ImGuiStyle();
+ IMGUI_API void ScaleAllSizes(float scale_factor); // Scale all spacing/padding/thickness values. Do not scale fonts.
+
+ // Obsolete names
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ // TabMinWidthForCloseButton = TabCloseButtonMinWidthUnselected // Renamed in 1.91.9.
+#endif
};
//-----------------------------------------------------------------------------
@@ -2310,7 +2453,8 @@ struct ImGuiIO
ImGuiConfigFlags ConfigFlags; // = 0 // See ImGuiConfigFlags_ enum. Set by user/application. Keyboard/Gamepad navigation options, etc.
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; // <unset> // Main display size, in pixels (generally == GetMainViewport()->Size). May change every frame.
+ ImVec2 DisplaySize; // <unset> // Main display size, in pixels (== GetMainViewport()->Size). May change every frame.
+ ImVec2 DisplayFramebufferScale; // = (1, 1) // Main display density. For retina display where window coordinates are different from framebuffer coordinates. This will affect font density + will end up in ImDrawData::FramebufferScale.
float DeltaTime; // = 1.0f/60.0f // Time elapsed since last frame, in seconds. May change every frame.
float IniSavingRate; // = 5.0f // Minimum time between saving positions/sizes to .ini file, in seconds.
const char* IniFilename; // = "imgui.ini" // Path to .ini file (important: default "imgui.ini" is relative to current working dir!). Set NULL to disable automatic .ini loading/saving or if you want to manually call LoadIniSettingsXXX() / SaveIniSettingsXXX() functions.
@@ -2319,14 +2463,12 @@ struct ImGuiIO
// Font system
ImFontAtlas*Fonts; // <auto> // Font atlas: load, rasterize and pack one or more fonts into a single texture.
- float FontGlobalScale; // = 1.0f // Global scale all fonts
- bool FontAllowUserScaling; // = false // Allow user scaling text of individual window with CTRL+Wheel.
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.
+ bool FontAllowUserScaling; // = false // [OBSOLETE] Allow user scaling text of individual window with CTRL+Wheel.
// Keyboard/Gamepad Navigation options
bool ConfigNavSwapGamepadButtons; // = false // Swap Activate<>Cancel (A<>B) buttons, matching typical "Nintendo/Japanese style" gamepad layout.
- bool ConfigNavMoveSetMousePos; // = false // Directional/tabbing navigation teleports the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is difficult. Will update io.MousePos and set io.WantSetMousePos=true.
+ bool ConfigNavMoveSetMousePos; // = false // Directional/tabbing navigation teleports the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is difficult. Will update io.MousePos and set io.WantSetMousePos=true.
bool ConfigNavCaptureKeyboard; // = true // Sets io.WantCaptureKeyboard when io.NavActive is set.
bool ConfigNavEscapeClearFocusItem; // = true // Pressing Escape can clear focused item + navigation id/highlight. Set to false if you want to always keep highlight on.
bool ConfigNavEscapeClearFocusWindow;// = false // Pressing Escape can clear focused window as well (super set of io.ConfigNavEscapeClearFocusItem).
@@ -2344,6 +2486,12 @@ struct ImGuiIO
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 // 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 = <main_viewport>, expecting the platform backend to setup a parent/child relationship between the OS windows (some backend may ignore this). Set to true if you want the default to be 0, then all viewports will be top-level OS windows.
+ bool ConfigViewportPlatformFocusSetsImGuiFocus; //= true // When a platform window is focused (e.g. using Alt+Tab, clicking Platform Title Bar), apply corresponding focus on imgui windows (may clear focus/active id from imgui windows location in other platform windows). In principle this is better enabled but we provide an opt-out, because some Linux window managers tend to eagerly focus windows (e.g. on mouse hover, or even a simple window pos/size change).
+
+ // DPI/Scaling options
+ // This may keep evolving during 1.92.x releases. Expect some turbulence.
+ bool ConfigDpiScaleFonts; // = false // [EXPERIMENTAL] Automatically overwrite style.FontScaleDpi when Monitor DPI changes. This will scale fonts but _NOT_ scale sizes/padding for now.
+ bool ConfigDpiScaleViewports; // = false // [EXPERIMENTAL] Scale Dear ImGui and Platform Windows when Monitor DPI changes.
// Miscellaneous options
// (you can visualize and interact with all options in 'Demo->Configuration')
@@ -2353,8 +2501,9 @@ struct ImGuiIO
bool ConfigInputTextCursorBlink; // = true // Enable blinking cursor (optional as some users consider it to be distracting).
bool ConfigInputTextEnterKeepActive; // = false // [BETA] Pressing Enter will keep item active and select contents (single-line only).
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 ConfigWindowsResizeFromEdges; // = true // Enable resizing of windows from their edges and from the lower-left corner. This requires ImGuiBackendFlags_HasMouseCursors for better mouse cursor feedback. (This used to be a per-window ImGuiWindowFlags_ResizeFromAnySide flag)
bool ConfigWindowsMoveFromTitleBarOnly; // = false // Enable allowing to move windows only when clicking on their title bar. Does not apply to windows without a title bar.
+ bool ConfigWindowsCopyContentsWithCtrlC; // = false // [EXPERIMENTAL] CTRL+C copy the contents of focused window into the clipboard. Experimental because: (1) has known issues with nested Begin/End pairs (2) text output quality varies (3) text output is in submission order rather than spatial order.
bool ConfigScrollbarScrollByPage; // = true // Enable scrolling page by page when clicking outside the scrollbar grab. When disabled, always scroll to clicked location. When enabled, Shift+Click scrolls to clicked location.
float ConfigMemoryCompactTimer; // = 60.0f // Timer (in seconds) to free transient windows/tables memory buffers when unused. Set to -1.0f to disable.
@@ -2392,14 +2541,15 @@ struct ImGuiIO
// Option to enable various debug tools showing buttons that will call the IM_DEBUG_BREAK() macro.
// - The Item Picker tool will be available regardless of this being enabled, in order to maximize its discoverability.
// - Requires a debugger being attached, otherwise IM_DEBUG_BREAK() options will appear to crash your application.
- // e.g. io.ConfigDebugIsDebuggerPresent = ::IsDebuggerPresent() on Win32, or refer to ImOsIsDebuggerPresent() imgui_test_engine/imgui_te_utils.cpp for a Unix compatible version).
+ // e.g. io.ConfigDebugIsDebuggerPresent = ::IsDebuggerPresent() on Win32, or refer to ImOsIsDebuggerPresent() imgui_test_engine/imgui_te_utils.cpp for a Unix compatible version.
bool ConfigDebugIsDebuggerPresent; // = false // Enable various tools calling IM_DEBUG_BREAK().
// Tools to detect code submitting items with conflicting/duplicate IDs
// - Code should use PushID()/PopID() in loops, or append "##xx" to same-label identifiers.
// - Empty label e.g. Button("") == same ID as parent widget/node. Use Button("##xx") instead!
// - See FAQ https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#q-about-the-id-stack-system
- bool ConfigDebugHighlightIdConflicts;// = true // Highlight and show an error message when multiple items have conflicting identifiers.
+ bool ConfigDebugHighlightIdConflicts;// = true // Highlight and show an error message popup when multiple items have conflicting identifiers.
+ bool ConfigDebugHighlightIdConflictsShowItemPicker;//=true // Show "Item Picker" button in aforementioned popup.
// Tools to test correct Begin/End and BeginChild/EndChild behaviors.
// - Presently Begin()/End() and BeginChild()/EndChild() needs to ALWAYS be called in tandem, regardless of return value of BeginXXX()
@@ -2421,6 +2571,7 @@ struct ImGuiIO
// (the imgui_impl_xxxx backend files are setting those up for you)
//------------------------------------------------------------------
+ // Nowadays those would be stored in ImGuiPlatformIO but we are leaving them here for legacy reasons.
// 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
@@ -2489,14 +2640,14 @@ struct ImGuiIO
float MouseWheelH; // Mouse wheel Horizontal. >0 scrolls Left, <0 scrolls Right. Most users don't have a mouse with a horizontal wheel, may not be filled by all backends.
ImGuiMouseSource MouseSource; // Mouse actual input peripheral (Mouse/TouchScreen/Pen).
ImGuiID MouseHoveredViewport; // (Optional) Modify using io.AddMouseViewportEvent(). With multi-viewports: viewport the OS mouse is hovering. If possible _IGNORING_ viewports with the ImGuiViewportFlags_NoInputs flag is much better (few backends can handle that). 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).
- bool KeyCtrl; // Keyboard modifier down: Control
+ bool KeyCtrl; // Keyboard modifier down: Ctrl (non-macOS), Cmd (macOS)
bool KeyShift; // Keyboard modifier down: Shift
bool KeyAlt; // Keyboard modifier down: Alt
- bool KeySuper; // Keyboard modifier down: Cmd/Super/Windows
+ bool KeySuper; // Keyboard modifier down: Windows/Super (non-macOS), Ctrl (macOS)
// Other state maintained from data above + IO function calls
- ImGuiKeyChord KeyMods; // Key mods flags (any of ImGuiMod_Ctrl/ImGuiMod_Shift/ImGuiMod_Alt/ImGuiMod_Super flags, same as io.KeyCtrl/KeyShift/KeyAlt/KeySuper but merged into flags. Read-only, updated by NewFrame()
- ImGuiKeyData KeysData[ImGuiKey_KeysData_SIZE]; // Key state for all known keys. Use IsKeyXXX() functions to access this.
+ ImGuiKeyChord KeyMods; // Key mods flags (any of ImGuiMod_Ctrl/ImGuiMod_Shift/ImGuiMod_Alt/ImGuiMod_Super flags, same as io.KeyCtrl/KeyShift/KeyAlt/KeySuper but merged into flags). Read-only, updated by NewFrame()
+ ImGuiKeyData KeysData[ImGuiKey_NamedKey_COUNT];// Key state for all known keys. MUST use 'key - ImGuiKey_NamedKey_BEGIN' as index. Use IsKeyXXX() functions to access this.
bool WantCaptureMouseUnlessPopupClose; // Alternative to WantCaptureMouse: (WantCaptureMouse == true && WantCaptureMouseUnlessPopupClose == false) when a click over void is expected to close a popup.
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
@@ -2506,10 +2657,11 @@ struct ImGuiIO
ImU16 MouseClickedCount[5]; // == 0 (not clicked), == 1 (same as MouseClicked[]), == 2 (double-clicked), == 3 (triple-clicked) etc. when going from !Down to Down
ImU16 MouseClickedLastCount[5]; // Count successive number of clicks. Stays valid after mouse release. Reset after another click is done.
bool MouseReleased[5]; // Mouse button went from Down to !Down
+ double MouseReleasedTime[5]; // Time of last released (rarely used! but useful to handle delayed single-click when trying to disambiguate them from double-click).
bool MouseDownOwned[5]; // Track if button was clicked inside a dear imgui window or over void blocked by a popup. We don't request mouse capture from the application if click started outside ImGui bounds.
bool MouseDownOwnedUnlessPopupClose[5]; // Track if button was clicked inside a dear imgui window.
bool MouseWheelRequestAxisSwap; // On a non-Mac system, holding SHIFT requests WheelY to perform the equivalent of a WheelX event. On a Mac system this is already enforced by the system.
- bool MouseCtrlLeftAsRightClick; // (OSX) Set to true when the current click was a ctrl-click that spawned a simulated right click
+ bool MouseCtrlLeftAsRightClick; // (OSX) Set to true when the current click was a Ctrl+click that spawned a simulated right click
float MouseDownDuration[5]; // Duration the mouse button has been down (0.0f == just clicked)
float MouseDownDurationPrev[5]; // Previous time the mouse button has been down
ImVec2 MouseDragMaxDistanceAbs[5]; // Maximum distance, absolute, on each axis, of how much mouse has traveled from the clicking point
@@ -2517,24 +2669,24 @@ struct ImGuiIO
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.
bool AppFocusLost; // Only modify via AddFocusEvent()
bool AppAcceptingEvents; // Only modify via SetAppAcceptingEvents()
- ImS8 BackendUsingLegacyKeyArrays; // -1: unknown, 0: using AddKeyEvent(), 1: using legacy io.KeysDown[]
- bool BackendUsingLegacyNavInputArray; // 0: using AddKeyAnalogEvent(), 1: writing to legacy io.NavInputs[] directly
ImWchar16 InputQueueSurrogate; // For AddInputCharacterUTF16()
ImVector<ImWchar> InputQueueCharacters; // Queue of _characters_ input (obtained by platform backend). Fill using AddInputCharacter() helper.
// Legacy: before 1.87, we required backend to fill io.KeyMap[] (imgui->native map) during initialization and io.KeysDown[] (native indices) every frame.
// This is still temporarily supported as a legacy feature. However the new preferred scheme is for backend to call io.AddKeyEvent().
// Old (<1.87): ImGui::IsKeyPressed(ImGui::GetIO().KeyMap[ImGuiKey_Space]) --> New (1.87+) ImGui::IsKeyPressed(ImGuiKey_Space)
-#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
- int KeyMap[ImGuiKey_COUNT]; // [LEGACY] Input: map of indices into the KeysDown[512] entries array which represent your "native" keyboard state. The first 512 are now unused and should be kept zero. Legacy backend will write into KeyMap[] using ImGuiKey_ indices which are always >512.
- bool KeysDown[ImGuiKey_COUNT]; // [LEGACY] Input: Keyboard keys that are pressed (ideally left in the "native" order your engine has access to keyboard keys, so you can use your own defines/enums for keys). This used to be [512] sized. It is now ImGuiKey_COUNT to allow legacy io.KeysDown[GetKeyIndex(...)] to work without an overflow.
- float NavInputs[ImGuiNavInput_COUNT]; // [LEGACY] Since 1.88, NavInputs[] was removed. Backends from 1.60 to 1.86 won't build. Feed gamepad inputs via io.AddKeyEvent() and ImGuiKey_GamepadXXX enums.
+ // Old (<1.87): ImGui::IsKeyPressed(MYPLATFORM_KEY_SPACE) --> New (1.87+) ImGui::IsKeyPressed(ImGuiKey_Space)
+ // Read https://github.com/ocornut/imgui/issues/4921 for details.
+ //int KeyMap[ImGuiKey_COUNT]; // [LEGACY] Input: map of indices into the KeysDown[512] entries array which represent your "native" keyboard state. The first 512 are now unused and should be kept zero. Legacy backend will write into KeyMap[] using ImGuiKey_ indices which are always >512.
+ //bool KeysDown[ImGuiKey_COUNT]; // [LEGACY] Input: Keyboard keys that are pressed (ideally left in the "native" order your engine has access to keyboard keys, so you can use your own defines/enums for keys). This used to be [512] sized. It is now ImGuiKey_COUNT to allow legacy io.KeysDown[GetKeyIndex(...)] to work without an overflow.
+ //float NavInputs[ImGuiNavInput_COUNT]; // [LEGACY] Since 1.88, NavInputs[] was removed. Backends from 1.60 to 1.86 won't build. Feed gamepad inputs via io.AddKeyEvent() and ImGuiKey_GamepadXXX enums.
//void* ImeWindowHandle; // [Obsoleted in 1.87] Set ImGuiViewport::PlatformHandleRaw instead. Set this to your HWND to get automatic IME cursor positioning.
-#endif
+
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ float FontGlobalScale; // Moved io.FontGlobalScale to style.FontScaleMain in 1.92 (June 2025)
// Legacy: before 1.91.1, clipboard functions were stored in ImGuiIO instead of ImGuiPlatformIO.
// As this is will affect all users of custom engines/backends, we are providing proper legacy redirection (will obsolete).
-#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
const char* (*GetClipboardTextFn)(void* user_data);
void (*SetClipboardTextFn)(void* user_data, const char* text);
void* ClipboardUserData;
@@ -2550,7 +2702,7 @@ struct ImGuiIO
// 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_CallbackEdit: Callback on buffer edit. Note that InputText() already returns true on edit + you can always use IsItemEdited(). The callback is useful 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
@@ -2572,10 +2724,10 @@ struct ImGuiInputTextCallbackData
ImGuiKey EventKey; // Key pressed (Up/Down/TAB) // Read-only // [Completion,History]
char* Buf; // Text buffer // Read-write // [Resize] Can replace pointer / [Completion,History,Always] Only write to pointed data, don't replace the actual pointer!
int BufTextLen; // Text length (in bytes) // Read-write // [Resize,Completion,History,Always] Exclude zero-terminator storage. In C land: == strlen(some_text), in C++ land: string.length()
- int BufSize; // Buffer size (in bytes) = capacity+1 // Read-only // [Resize,Completion,History,Always] Include zero-terminator storage. In C land == ARRAYSIZE(my_char_array), in C++ land: string.capacity()+1
+ int BufSize; // Buffer size (in bytes) = capacity+1 // Read-only // [Resize,Completion,History,Always] Include zero-terminator storage. In C land: == ARRAYSIZE(my_char_array), in C++ land: string.capacity()+1
bool BufDirty; // Set if you modify Buf/BufTextLen! // Write // [Completion,History,Always]
int CursorPos; // // Read-write // [Completion,History,Always]
- int SelectionStart; // // Read-write // [Completion,History,Always] == to SelectionEnd when no selection)
+ int SelectionStart; // // Read-write // [Completion,History,Always] == to SelectionEnd when no selection
int SelectionEnd; // // Read-write // [Completion,History,Always]
// Helper functions for text manipulation.
@@ -2699,10 +2851,11 @@ struct ImGuiTextBuffer
ImGuiTextBuffer() { }
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
+ 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() const { return Buf.Size <= 1; }
void clear() { Buf.clear(); }
+ void resize(int size) { if (Buf.Size > size) Buf.Data[size] = 0; Buf.resize(size ? size + 1 : 0, 0); } // Similar to resize(0) on ImVector: empty string but don't free buffer.
void reserve(int capacity) { Buf.reserve(capacity); }
const char* c_str() const { return Buf.Data ? Buf.Data : EmptyString; }
IMGUI_API void append(const char* str, const char* str_end = NULL);
@@ -2765,6 +2918,13 @@ struct ImGuiStorage
#endif
};
+// Flags for ImGuiListClipper (currently not fully exposed in function calls: a future refactor will likely add this to ImGuiListClipper::Begin function equivalent)
+enum ImGuiListClipperFlags_
+{
+ ImGuiListClipperFlags_None = 0,
+ ImGuiListClipperFlags_NoSetTableRowCounters = 1 << 0, // [Internal] Disabled modifying table row counters. Avoid assumption that 1 clipper item == 1 table row.
+};
+
// Helper: Manually clip large list of items.
// If you have lots evenly spaced items and you have random access to the list, you can perform coarse
// clipping based on visibility to only submit items that are in view.
@@ -2792,9 +2952,10 @@ struct ImGuiListClipper
int DisplayEnd; // End of items to display (exclusive)
int ItemsCount; // [Internal] Number of items
float ItemsHeight; // [Internal] Height of item after a first step and item submission can calculate it
- float StartPosY; // [Internal] Cursor position at the time of Begin() or after table frozen rows are all processed
+ double StartPosY; // [Internal] Cursor position at the time of Begin() or after table frozen rows are all processed
double StartSeekOffsetY; // [Internal] Account for frozen rows in a table and initial loss of precision in very large windows.
void* TempData; // [Internal] Internal data
+ ImGuiListClipperFlags Flags; // [Internal] Flags, currently not yet well exposed.
// 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, and you can call SeekCursorForItem() manually if you need)
// items_height: Use -1.0f to be calculated automatically on first step. Otherwise pass in the distance between your items, typically GetTextLineHeightWithSpacing() or GetFrameHeightWithSpacing().
@@ -2816,7 +2977,7 @@ struct ImGuiListClipper
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
inline void IncludeRangeByIndices(int item_begin, int item_end) { IncludeItemsByIndex(item_begin, item_end); } // [renamed in 1.89.9]
- inline void ForceDisplayRangeByIndices(int item_begin, int item_end) { IncludeItemsByIndex(item_begin, item_end); } // [renamed in 1.89.6]
+ //inline void ForceDisplayRangeByIndices(int item_begin, int item_end) { IncludeItemsByIndex(item_begin, item_end); } // [renamed in 1.89.6]
//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
};
@@ -2825,34 +2986,42 @@ struct ImGuiListClipper
// - It is important that we are keeping those disabled by default so they don't leak in user space.
// - This is in order to allow user enabling implicit cast operators between ImVec2/ImVec4 and their own types (using IM_VEC2_CLASS_EXTRA in imconfig.h)
// - Add '#define IMGUI_DEFINE_MATH_OPERATORS' before including this file (or in imconfig.h) to access courtesy maths operators for ImVec2 and ImVec4.
+// - We intentionally provide ImVec2*float but not float*ImVec2: this is rare enough and we want to reduce the surface for possible user mistake.
#ifdef IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_MATH_OPERATORS_IMPLEMENTED
IM_MSVC_RUNTIME_CHECKS_OFF
-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-(const ImVec2& lhs) { return ImVec2(-lhs.x, -lhs.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 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 bool operator==(const ImVec2& lhs, const ImVec2& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y; }
-static inline bool operator!=(const ImVec2& lhs, const ImVec2& rhs) { return lhs.x != rhs.x || lhs.y != rhs.y; }
-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 bool operator==(const ImVec4& lhs, const ImVec4& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w; }
-static inline bool operator!=(const ImVec4& lhs, const ImVec4& rhs) { return lhs.x != rhs.x || lhs.y != rhs.y || lhs.z != rhs.z || lhs.w != rhs.w; }
+// ImVec2 operators
+inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x * rhs, lhs.y * rhs); }
+inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x / rhs, lhs.y / rhs); }
+inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x + rhs.x, lhs.y + rhs.y); }
+inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x - rhs.x, lhs.y - rhs.y); }
+inline ImVec2 operator*(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); }
+inline ImVec2 operator/(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x / rhs.x, lhs.y / rhs.y); }
+inline ImVec2 operator-(const ImVec2& lhs) { return ImVec2(-lhs.x, -lhs.y); }
+inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; }
+inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; }
+inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; }
+inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; }
+inline ImVec2& operator*=(ImVec2& lhs, const ImVec2& rhs) { lhs.x *= rhs.x; lhs.y *= rhs.y; return lhs; }
+inline ImVec2& operator/=(ImVec2& lhs, const ImVec2& rhs) { lhs.x /= rhs.x; lhs.y /= rhs.y; return lhs; }
+inline bool operator==(const ImVec2& lhs, const ImVec2& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y; }
+inline bool operator!=(const ImVec2& lhs, const ImVec2& rhs) { return lhs.x != rhs.x || lhs.y != rhs.y; }
+// ImVec4 operators
+inline ImVec4 operator*(const ImVec4& lhs, const float rhs) { return ImVec4(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs, lhs.w * rhs); }
+inline ImVec4 operator/(const ImVec4& lhs, const float rhs) { return ImVec4(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs, lhs.w / rhs); }
+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); }
+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); }
+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); }
+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); }
+inline ImVec4 operator-(const ImVec4& lhs) { return ImVec4(-lhs.x, -lhs.y, -lhs.z, -lhs.w); }
+inline bool operator==(const ImVec4& lhs, const ImVec4& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w; }
+inline bool operator!=(const ImVec4& lhs, const ImVec4& rhs) { return lhs.x != rhs.x || lhs.y != rhs.y || lhs.z != rhs.z || lhs.w != rhs.w; }
IM_MSVC_RUNTIME_CHECKS_RESTORE
#endif
// Helpers macros to generate 32-bit encoded colors
-// User can declare their own format by #defining the 5 _SHIFT/_MASK macros in their imconfig file.
+// - User can declare their own format by #defining the 5 _SHIFT/_MASK macros in their imconfig file.
+// - Any setting other than the default will need custom backend support. The only standard backend that supports anything else than the default is DirectX9.
#ifndef IM_COL32_R_SHIFT
#ifdef IMGUI_USE_BGRA_PACKED_COLOR
#define IM_COL32_R_SHIFT 16
@@ -3025,7 +3194,7 @@ struct ImGuiSelectionBasicStorage
IMGUI_API void Clear(); // Clear selection
IMGUI_API void Swap(ImGuiSelectionBasicStorage& r); // Swap two selections
IMGUI_API void SetItemSelected(ImGuiID id, bool selected); // Add/remove an item from selection (generally done by ApplyRequests() function)
- IMGUI_API bool GetNextSelectedItem(void** opaque_it, ImGuiID* out_id); // Iterate selection with 'void* it = NULL; ImGuiId id; while (selection.GetNextSelectedItem(&it, &id)) { ... }'
+ IMGUI_API bool GetNextSelectedItem(void** opaque_it, ImGuiID* out_id); // Iterate selection with 'void* it = NULL; ImGuiID id; while (selection.GetNextSelectedItem(&it, &id)) { ... }'
inline ImGuiID GetStorageIdFromIndex(int idx) { return AdapterIndexToStorageId(this, idx); } // Convert index to item id based on provided adapter.
};
@@ -3049,7 +3218,14 @@ struct ImGuiSelectionExternalStorage
// 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)
+#define IM_DRAWLIST_TEX_LINES_WIDTH_MAX (32)
+#endif
+
+// ImDrawIdx: vertex index. [Compile-time configurable type]
+// - To use 16-bit indices + allow large meshes: backend need to set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' and handle ImDrawCmd::VtxOffset (recommended).
+// - To use 32-bit indices: override with '#define ImDrawIdx unsigned int' in your imconfig.h file.
+#ifndef ImDrawIdx
+typedef unsigned short ImDrawIdx; // Default: 16-bit (for maximum compatibility with renderer backends)
#endif
// ImDrawCallback: Draw callbacks for advanced uses [configurable type: override in imconfig.h]
@@ -3073,11 +3249,11 @@ typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* c
// - VtxOffset: When 'io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset' is enabled,
// this fields allow us to render meshes larger than 64K vertices while keeping 16-bit indices.
// Backends made for <1.71. will typically ignore the VtxOffset fields.
-// - The ClipRect/TextureId/VtxOffset fields must be contiguous as we memcmp() them together (this is asserted for).
+// - The ClipRect/TexRef/VtxOffset fields must be contiguous as we memcmp() them together (this is asserted for).
struct ImDrawCmd
{
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.
+ ImTextureRef TexRef; // 16 // Reference to a font/texture atlas (where backend called ImTextureData::SetTexID()) or to a user-provided texture ID (via e.g. ImGui::Image() calls). Both will lead to a ImTextureID value.
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.
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[].
@@ -3089,7 +3265,8 @@ struct ImDrawCmd
ImDrawCmd() { memset(this, 0, sizeof(*this)); } // Also ensure our padding fields are zeroed
// Since 1.83: returns ImTextureID associated with this draw call. Warning: DO NOT assume this is always same as 'TextureId' (we will change this function for an upcoming feature)
- inline ImTextureID GetTexID() const { return TextureId; }
+ // Since 1.92: removed ImDrawCmd::TextureId field, the getter function must be used!
+ inline ImTextureID GetTexID() const; // == (TexRef._TexData ? TexRef._TexData->TexID : TexRef._TexID)
};
// Vertex layout
@@ -3112,7 +3289,7 @@ IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT;
struct ImDrawCmdHeader
{
ImVec4 ClipRect;
- ImTextureID TextureId;
+ ImTextureRef TexRef;
unsigned int VtxOffset;
};
@@ -3123,7 +3300,6 @@ struct ImDrawChannel
ImVector<ImDrawIdx> _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/Tables API, so items of each column can be batched together in a same draw call.
struct ImDrawListSplitter
@@ -3179,7 +3355,7 @@ enum ImDrawListFlags_
// access the current window draw list and draw custom primitives.
// You can interleave normal ImGui:: calls and adding primitives to the current draw list.
// In single viewport mode, top-left is == GetMainViewport()->Pos (generally 0,0), bottom-right is == GetMainViewport()->Pos+Size (generally io.DisplaySize).
-// You are totally free to apply whatever transformation matrix to want to the data (depending on the use of the transformation you may want to apply it to ClipRect as well!)
+// You are totally free to apply whatever transformation matrix you want to the data (depending on the use of the transformation you may 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
{
@@ -3198,20 +3374,21 @@ struct ImDrawList
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!)
ImVector<ImVec4> _ClipRectStack; // [Internal]
- ImVector<ImTextureID> _TextureIdStack; // [Internal]
+ ImVector<ImTextureRef> _TextureStack; // [Internal]
ImVector<ImU8> _CallbacksDataBuf; // [Internal]
float _FringeScale; // [Internal] anti-alias fringe is scaled by this value, this helps to keep things sharp while zooming at vertex buffer content
const char* _OwnerName; // Pointer to owner window's name for debugging
- // 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(ImDrawListSharedData* shared_data) { memset(this, 0, sizeof(*this)); _Data = shared_data; }
+ // If you want to create ImDrawList instances, pass them ImGui::GetDrawListSharedData().
+ // (advanced: you may create and use your own ImDrawListSharedData so you can use ImDrawList without ImGui, but that's more involved)
+ IMGUI_API ImDrawList(ImDrawListSharedData* shared_data);
+ IMGUI_API ~ImDrawList();
- ~ImDrawList() { _ClearFreeMemory(); }
IMGUI_API void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect = false); // Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling)
IMGUI_API void PushClipRectFullScreen();
IMGUI_API void PopClipRect();
- IMGUI_API void PushTextureID(ImTextureID texture_id);
- IMGUI_API void PopTextureID();
+ IMGUI_API void PushTexture(ImTextureRef tex_ref);
+ IMGUI_API void PopTexture();
inline ImVec2 GetClipRectMin() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.x, cr.y); }
inline ImVec2 GetClipRectMax() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.z, cr.w); }
@@ -3237,24 +3414,24 @@ struct ImDrawList
IMGUI_API void AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 col, float rot = 0.0f, int num_segments = 0, float thickness = 1.0f);
IMGUI_API void AddEllipseFilled(const ImVec2& center, const ImVec2& radius, ImU32 col, float rot = 0.0f, int num_segments = 0);
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 AddText(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 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)
// General polygon
// - Only simple polygons are supported by filling functions (no self-intersections, no holes).
- // - Concave polygon fill is more expensive than convex one: it has O(N^2) complexity. Provided as a convenience fo user but not used by main library.
+ // - Concave polygon fill is more expensive than convex one: it has O(N^2) complexity. Provided as a convenience for the user but not used by the main library.
IMGUI_API void AddPolyline(const ImVec2* points, int num_points, ImU32 col, ImDrawFlags flags, float thickness);
IMGUI_API void AddConvexPolyFilled(const ImVec2* points, int num_points, ImU32 col);
IMGUI_API void AddConcavePolyFilled(const ImVec2* points, int num_points, ImU32 col);
// Image primitives
- // - Read FAQ to understand what ImTextureID is.
+ // - Read FAQ to understand what ImTextureID/ImTextureRef are.
// - "p_min" and "p_max" represent the upper-left and lower-right corners of the rectangle.
// - "uv_min" and "uv_max" represent the normalized texture coordinates to use for those corners. Using (0,0)->(1,1) texture coordinates will generally display the entire texture.
- IMGUI_API void AddImage(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min = ImVec2(0, 0), const ImVec2& uv_max = ImVec2(1, 1), ImU32 col = IM_COL32_WHITE);
- IMGUI_API void AddImageQuad(ImTextureID user_texture_id, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& uv1 = ImVec2(0, 0), const ImVec2& uv2 = ImVec2(1, 0), const ImVec2& uv3 = ImVec2(1, 1), const ImVec2& uv4 = ImVec2(0, 1), ImU32 col = IM_COL32_WHITE);
- IMGUI_API void AddImageRounded(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col, float rounding, ImDrawFlags flags = 0);
+ IMGUI_API void AddImage(ImTextureRef tex_ref, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min = ImVec2(0, 0), const ImVec2& uv_max = ImVec2(1, 1), ImU32 col = IM_COL32_WHITE);
+ IMGUI_API void AddImageQuad(ImTextureRef tex_ref, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& uv1 = ImVec2(0, 0), const ImVec2& uv2 = ImVec2(1, 0), const ImVec2& uv3 = ImVec2(1, 1), const ImVec2& uv4 = ImVec2(0, 1), ImU32 col = IM_COL32_WHITE);
+ IMGUI_API void AddImageRounded(ImTextureRef tex_ref, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col, float rounding, ImDrawFlags flags = 0);
// Stateful path API, add points then finish with PathFillConvex() or PathStroke()
// - Important: filled shapes must always use clockwise winding order! The anti-aliasing fringe depends on it. Counter-clockwise shapes will have "inward" anti-aliasing.
@@ -3285,7 +3462,7 @@ struct ImDrawList
// Advanced: Miscellaneous
IMGUI_API void AddDrawCmd(); // This is useful if you need to forcefully create a new draw call (to allow for dependent rendering / blending). Otherwise primitives are merged into the same draw-call as much as possible
- IMGUI_API ImDrawList* CloneOutput() const; // Create a clone of the CmdBuffer/IdxBuffer/VtxBuffer.
+ IMGUI_API ImDrawList* CloneOutput() const; // Create a clone of the CmdBuffer/IdxBuffer/VtxBuffer. For multi-threaded rendering, consider using `imgui_threaded_rendering` from https://github.com/ocornut/imgui_club instead.
// Advanced: Channels
// - Use to split render into layers. By switching channels to can render out-of-order (e.g. submit FG primitives before BG primitives)
@@ -3310,6 +3487,10 @@ struct ImDrawList
inline void PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { PrimWriteIdx((ImDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); } // Write vertex with unique index
// Obsolete names
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ inline void PushTextureID(ImTextureRef tex_ref) { PushTexture(tex_ref); } // RENAMED in 1.92.x
+ inline void PopTextureID() { PopTexture(); } // RENAMED in 1.92.x
+#endif
//inline void AddEllipse(const ImVec2& center, float radius_x, float radius_y, ImU32 col, float rot = 0.0f, int num_segments = 0, float thickness = 1.0f) { AddEllipse(center, ImVec2(radius_x, radius_y), col, rot, num_segments, thickness); } // OBSOLETED in 1.90.5 (Mar 2024)
//inline void AddEllipseFilled(const ImVec2& center, float radius_x, float radius_y, ImU32 col, float rot = 0.0f, int num_segments = 0) { AddEllipseFilled(center, ImVec2(radius_x, radius_y), col, rot, num_segments); } // OBSOLETED in 1.90.5 (Mar 2024)
//inline void PathEllipticalArcTo(const ImVec2& center, float radius_x, float radius_y, float rot, float a_min, float a_max, int num_segments = 0) { PathEllipticalArcTo(center, ImVec2(radius_x, radius_y), rot, a_min, a_max, num_segments); } // OBSOLETED in 1.90.5 (Mar 2024)
@@ -3317,14 +3498,15 @@ struct ImDrawList
//inline void PathBezierCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments = 0) { PathBezierCubicCurveTo(p2, p3, p4, num_segments); } // OBSOLETED in 1.80 (Jan 2021)
// [Internal helpers]
+ IMGUI_API void _SetDrawListSharedData(ImDrawListSharedData* data);
IMGUI_API void _ResetForNewFrame();
IMGUI_API void _ClearFreeMemory();
IMGUI_API void _PopUnusedDrawCmd();
IMGUI_API void _TryMergeDrawCmds();
IMGUI_API void _OnChangedClipRect();
- IMGUI_API void _OnChangedTextureID();
+ IMGUI_API void _OnChangedTexture();
IMGUI_API void _OnChangedVtxOffset();
- IMGUI_API void _SetTextureID(ImTextureID texture_id);
+ IMGUI_API void _SetTexture(ImTextureRef tex_ref);
IMGUI_API int _CalcCircleAutoSegmentCount(float radius) const;
IMGUI_API void _PathArcToFastEx(const ImVec2& center, float radius, int a_min_sample, int a_max_sample, int a_step);
IMGUI_API void _PathArcToN(const ImVec2& center, float radius, float a_min, float a_max, int num_segments);
@@ -3336,14 +3518,15 @@ struct ImDrawList
struct ImDrawData
{
bool Valid; // Only valid after Render() is called and before the next NewFrame() is called.
- int CmdListsCount; // Number of ImDrawList* to render
+ int CmdListsCount; // == CmdLists.Size. (OBSOLETE: exists for legacy reasons). Number of ImDrawList* to render.
int TotalIdxCount; // For convenience, sum of all ImDrawList's IdxBuffer.Size
int TotalVtxCount; // For convenience, sum of all ImDrawList's VtxBuffer.Size
ImVector<ImDrawList*> CmdLists; // Array of ImDrawList* to render. The ImDrawLists are owned by ImGuiContext and only pointed to from here.
ImVec2 DisplayPos; // Top-left position of the viewport to render (== top-left of the orthogonal projection matrix to use) (== GetMainViewport()->Pos for the main viewport, == (0.0) in most single-viewport applications)
ImVec2 DisplaySize; // Size of the viewport to render (== GetMainViewport()->Size for the main viewport, == io.DisplaySize in most single-viewport applications)
- 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.
+ ImVec2 FramebufferScale; // Amount of pixels for each unit of DisplaySize. Copied from viewport->FramebufferScale (== io.DisplayFramebufferScale for main viewport). 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).
+ ImVector<ImTextureData*>* Textures; // List of textures to update. Most of the times the list is shared by all ImDrawData, has only 1 texture and it doesn't need any update. This almost always points to ImGui::GetPlatformIO().Textures[]. May be overriden or set to NULL if you want to manually update textures.
// Functions
ImDrawData() { Clear(); }
@@ -3354,47 +3537,143 @@ struct ImDrawData
};
//-----------------------------------------------------------------------------
+// [SECTION] Texture API (ImTextureFormat, ImTextureStatus, ImTextureRect, ImTextureData)
+//-----------------------------------------------------------------------------
+// In principle, the only data types that user/application code should care about are 'ImTextureRef' and 'ImTextureID'.
+// They are defined above in this header file. Read their description to the difference between ImTextureRef and ImTextureID.
+// FOR ALL OTHER ImTextureXXXX TYPES: ONLY CORE LIBRARY AND RENDERER BACKENDS NEED TO KNOW AND CARE ABOUT THEM.
+//-----------------------------------------------------------------------------
+
+#undef Status // X11 headers are leaking this.
+
+// We intentionally support a limited amount of texture formats to limit burden on CPU-side code and extension.
+// Most standard backends only support RGBA32 but we provide a single channel option for low-resource/embedded systems.
+enum ImTextureFormat
+{
+ ImTextureFormat_RGBA32, // 4 components per pixel, each is unsigned 8-bit. Total size = TexWidth * TexHeight * 4
+ ImTextureFormat_Alpha8, // 1 component per pixel, each is unsigned 8-bit. Total size = TexWidth * TexHeight
+};
+
+// Status of a texture to communicate with Renderer Backend.
+enum ImTextureStatus
+{
+ ImTextureStatus_OK,
+ ImTextureStatus_Destroyed, // Backend destroyed the texture.
+ ImTextureStatus_WantCreate, // Requesting backend to create the texture. Set status OK when done.
+ ImTextureStatus_WantUpdates, // Requesting backend to update specific blocks of pixels (write to texture portions which have never been used before). Set status OK when done.
+ ImTextureStatus_WantDestroy, // Requesting backend to destroy the texture. Set status to Destroyed when done.
+};
+
+// Coordinates of a rectangle within a texture.
+// When a texture is in ImTextureStatus_WantUpdates state, we provide a list of individual rectangles to copy to the graphics system.
+// You may use ImTextureData::Updates[] for the list, or ImTextureData::UpdateBox for a single bounding box.
+struct ImTextureRect
+{
+ unsigned short x, y; // Upper-left coordinates of rectangle to update
+ unsigned short w, h; // Size of rectangle to update (in pixels)
+};
+
+// Specs and pixel storage for a texture used by Dear ImGui.
+// This is only useful for (1) core library and (2) backends. End-user/applications do not need to care about this.
+// Renderer Backends will create a GPU-side version of this.
+// Why does we store two identifiers: TexID and BackendUserData?
+// - ImTextureID TexID = lower-level identifier stored in ImDrawCmd. ImDrawCmd can refer to textures not created by the backend, and for which there's no ImTextureData.
+// - void* BackendUserData = higher-level opaque storage for backend own book-keeping. Some backends may have enough with TexID and not need both.
+ // In columns below: who reads/writes each fields? 'r'=read, 'w'=write, 'core'=main library, 'backend'=renderer backend
+struct ImTextureData
+{
+ //------------------------------------------ core / backend ---------------------------------------
+ int UniqueID; // w - // [DEBUG] Sequential index to facilitate identifying a texture when debugging/printing. Unique per atlas.
+ ImTextureStatus Status; // rw rw // ImTextureStatus_OK/_WantCreate/_WantUpdates/_WantDestroy. Always use SetStatus() to modify!
+ void* BackendUserData; // - rw // Convenience storage for backend. Some backends may have enough with TexID.
+ ImTextureID TexID; // r w // Backend-specific texture identifier. Always use SetTexID() to modify! The identifier will stored in ImDrawCmd::GetTexID() and passed to backend's RenderDrawData function.
+ ImTextureFormat Format; // w r // ImTextureFormat_RGBA32 (default) or ImTextureFormat_Alpha8
+ int Width; // w r // Texture width
+ int Height; // w r // Texture height
+ int BytesPerPixel; // w r // 4 or 1
+ unsigned char* Pixels; // w r // Pointer to buffer holding 'Width*Height' pixels and 'Width*Height*BytesPerPixels' bytes.
+ ImTextureRect UsedRect; // w r // Bounding box encompassing all past and queued Updates[].
+ ImTextureRect UpdateRect; // w r // Bounding box encompassing all queued Updates[].
+ ImVector<ImTextureRect> Updates; // w r // Array of individual updates.
+ int UnusedFrames; // w r // In order to facilitate handling Status==WantDestroy in some backend: this is a count successive frames where the texture was not used. Always >0 when Status==WantDestroy.
+ unsigned short RefCount; // w r // Number of contexts using this texture. Used during backend shutdown.
+ bool UseColors; // w r // Tell whether our texture data is known to use colors (rather than just white + alpha).
+ bool WantDestroyNextFrame; // rw - // [Internal] Queued to set ImTextureStatus_WantDestroy next frame. May still be used in the current frame.
+
+ // Functions
+ ImTextureData() { memset(this, 0, sizeof(*this)); Status = ImTextureStatus_Destroyed; TexID = ImTextureID_Invalid; }
+ ~ImTextureData() { DestroyPixels(); }
+ IMGUI_API void Create(ImTextureFormat format, int w, int h);
+ IMGUI_API void DestroyPixels();
+ void* GetPixels() { IM_ASSERT(Pixels != NULL); return Pixels; }
+ void* GetPixelsAt(int x, int y) { IM_ASSERT(Pixels != NULL); return Pixels + (x + y * Width) * BytesPerPixel; }
+ int GetSizeInBytes() const { return Width * Height * BytesPerPixel; }
+ int GetPitch() const { return Width * BytesPerPixel; }
+ ImTextureRef GetTexRef() { ImTextureRef tex_ref; tex_ref._TexData = this; tex_ref._TexID = ImTextureID_Invalid; return tex_ref; }
+ ImTextureID GetTexID() const { return TexID; }
+
+ // Called by Renderer backend
+ void SetTexID(ImTextureID tex_id) { TexID = tex_id; } // Call after creating or destroying the texture. Never modify TexID directly!
+ void SetStatus(ImTextureStatus status) { Status = status; } // Call after honoring a request. Never modify Status directly!
+};
+
+//-----------------------------------------------------------------------------
// [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontAtlasFlags, ImFontAtlas, ImFontGlyphRangesBuilder, ImFont)
//-----------------------------------------------------------------------------
+// A font input/source (we may rename this to ImFontSource in the future)
struct ImFontConfig
{
+ // Data Source
+ char Name[40]; // <auto> // Name (strictly to ease debugging, hence limited size buffer)
void* FontData; // // TTF/OTF data
int FontDataSize; // // TTF/OTF data size
bool FontDataOwnedByAtlas; // true // TTF/OTF data ownership taken by the container ImFontAtlas (will delete memory itself).
- int FontNo; // 0 // Index of font within TTF/OTF file
+
+ // Options
+ 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.
+ bool PixelSnapH; // false // Align every glyph AdvanceX to pixel boundaries. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1.
+ bool PixelSnapV; // true // Align Scaled GlyphOffset.y to pixel boundaries.
+ ImS8 OversampleH; // 0 (2) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1 or 2 depending on size. Note the difference between 2 and 3 is minimal. You can reduce this to 1 for large glyphs save memory. Read https://github.com/nothings/stb/blob/master/tests/oversample/README.md for details.
+ ImS8 OversampleV; // 0 (1) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1. This is not really useful as we don't use sub-pixel positions on the Y axis.
+ ImWchar EllipsisChar; // 0 // Explicitly specify Unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used.
float SizePixels; // // Size in pixels for rasterizer (more or less maps to the resulting font height).
- int OversampleH; // 2 // Rasterize at higher quality for sub-pixel positioning. Note the difference between 2 and 3 is minimal. You can reduce this to 1 for large glyphs save memory. Read https://github.com/nothings/stb/blob/master/tests/oversample/README.md for details.
- int OversampleV; // 1 // Rasterize at higher quality for sub-pixel positioning. This is not really useful as we don't use sub-pixel positions on the Y axis.
- bool PixelSnapH; // false // Align every glyph to pixel boundary. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1.
- ImVec2 GlyphExtraSpacing; // 0, 0 // Extra spacing (in pixels) between glyphs. Only X axis is supported for now.
- ImVec2 GlyphOffset; // 0, 0 // Offset all glyphs from this font input.
- const ImWchar* GlyphRanges; // NULL // THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list).
- float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font
+ const ImWchar* GlyphRanges; // NULL // *LEGACY* THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list).
+ const ImWchar* GlyphExcludeRanges; // NULL // Pointer to a small user-provided list of Unicode ranges (2 value per range, values are inclusive, zero-terminated list). This is very close to GlyphRanges[] but designed to exclude ranges from a font source, when merging fonts with overlapping glyphs. Use "Input Glyphs Overlap Detection Tool" to find about your overlapping ranges.
+ //ImVec2 GlyphExtraSpacing; // 0, 0 // (REMOVED AT IT SEEMS LARGELY OBSOLETE. PLEASE REPORT IF YOU WERE USING THIS). Extra spacing (in pixels) between glyphs when rendered: essentially add to glyph->AdvanceX. Only X axis is supported for now.
+ ImVec2 GlyphOffset; // 0, 0 // Offset (in pixels) all glyphs from this font input. Absolute value for default size, other sizes will scale this value.
+ float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font. Absolute value for default size, other sizes will scale this value.
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 FontBuilderFlags; // 0 // Settings for custom font builder. THIS IS BUILDER IMPLEMENTATION DEPENDENT. Leave as zero if unsure.
+ float GlyphExtraAdvanceX; // 0 // Extra spacing (in pixels) between glyphs. Please contact us if you are using this. // FIXME-NEWATLAS: Intentionally unscaled
+ ImU32 FontNo; // 0 // Index of font within TTF/OTF file
+ unsigned int FontLoaderFlags; // 0 // Settings for custom font builder. THIS IS BUILDER IMPLEMENTATION DEPENDENT. Leave as zero if unsure.
+ //unsigned int FontBuilderFlags; // -- // [Renamed in 1.92] Ue FontLoaderFlags.
float RasterizerMultiply; // 1.0f // Linearly brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable. This is a silly thing we may remove in the future.
- float RasterizerDensity; // 1.0f // DPI scale for rasterization, not altering other font metrics: make it easy to swap between e.g. a 100% and a 400% fonts for a zooming display. IMPORTANT: If you increase this it is expected that you increase font scale accordingly, otherwise quality may look lowered.
- ImWchar EllipsisChar; // -1 // Explicitly specify unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used.
+ float RasterizerDensity; // 1.0f // [LEGACY: this only makes sense when ImGuiBackendFlags_RendererHasTextures is not supported] DPI scale multiplier for rasterization. Not altering other font metrics: makes it easy to swap between e.g. a 100% and a 400% fonts for a zooming display, or handle Retina screen. IMPORTANT: If you change this it is expected that you increase/decrease font scale roughly to the inverse of this, otherwise quality may look lowered.
// [Internal]
- char Name[40]; // Name (strictly to ease debugging)
- ImFont* DstFont;
+ ImFontFlags Flags; // Font flags (don't use just yet, will be exposed in upcoming 1.92.X updates)
+ ImFont* DstFont; // Target font (as we merging fonts, multiple ImFontConfig may target the same font)
+ const ImFontLoader* FontLoader; // Custom font backend for this source (default source is the one stored in ImFontAtlas)
+ void* FontLoaderData; // Font loader opaque storage (per font config)
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)
+// (Note: some language parsers may fail to convert the bitfield members, in this case maybe drop store a single u32 or we can rework this)
struct ImFontGlyph
{
unsigned int Colored : 1; // Flag to indicate glyph is colored and should generally ignore tinting (make it usable with no shift on little-endian as this is used in loops)
unsigned int Visible : 1; // Flag to indicate glyph has no visible pixels (e.g. space). Allow early out when rendering.
- unsigned int Codepoint : 30; // 0x0000..0x10FFFF
- 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
+ unsigned int SourceIdx : 4; // Index of source in parent font
+ unsigned int Codepoint : 26; // 0x0000..0x10FFFF
+ float AdvanceX; // Horizontal distance to advance cursor/layout position.
+ float X0, Y0, X1, Y1; // Glyph corners. Offsets from current cursor/layout position.
+ float U0, V0, U1, V1; // Texture coordinates for the current value of ImFontAtlas->TexRef. Cached equivalent of calling GetCustomRect() with PackId.
+ int PackId; // [Internal] ImFontAtlasRectId value (FIXME: Cold data, could be moved elsewhere?)
+
+ ImFontGlyph() { memset(this, 0, sizeof(*this)); PackId = -1; }
};
// Helper to build glyph ranges from text/string data. Feed your application strings/characters to it then call BuildRanges().
@@ -3413,17 +3692,21 @@ struct ImFontGlyphRangesBuilder
IMGUI_API void BuildRanges(ImVector<ImWchar>* out_ranges); // Output new ranges
};
-// See ImFontAtlas::AddCustomRectXXX functions.
-struct ImFontAtlasCustomRect
+// An opaque identifier to a rectangle in the atlas. -1 when invalid.
+// The rectangle may move and UV may be invalidated, use GetCustomRect() to retrieve it.
+typedef int ImFontAtlasRectId;
+#define ImFontAtlasRectId_Invalid -1
+
+// Output of ImFontAtlas::GetCustomRect() when using custom rectangles.
+// Those values may not be cached/stored as they are only valid for the current value of atlas->TexRef
+// (this is in theory derived from ImTextureRect but we use separate structures for reasons)
+struct ImFontAtlasRect
{
- unsigned short Width, Height; // Input // Desired rectangle dimension
- unsigned short X, Y; // Output // Packed position in Atlas
- 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; }
+ unsigned short x, y; // Position (in current texture)
+ unsigned short w, h; // Size
+ ImVec2 uv0, uv1; // UV coordinates (in current texture)
+
+ ImFontAtlasRect() { memset(this, 0, sizeof(*this)); }
};
// Flags for ImFontAtlas build
@@ -3439,12 +3722,14 @@ enum ImFontAtlasFlags_
// - One or more fonts.
// - Custom graphics data needed to render the shapes needed by Dear ImGui.
// - Mouse cursor shapes for software cursor rendering (unless setting 'Flags |= ImFontAtlasFlags_NoMouseCursors' in the font atlas).
-// It is the user-code responsibility to setup/build the atlas, then upload the pixel data into a texture accessible by your graphics api.
-// - Optionally, call any of the AddFont*** functions. If you don't call any, the default font embedded in the code will be loaded for you.
-// - Call GetTexDataAsAlpha8() or GetTexDataAsRGBA32() to build and retrieve pixels data.
-// - Upload the pixels data into a texture within your graphics system (see imgui_impl_xxxx.cpp examples)
+// - If you don't call any AddFont*** functions, the default font embedded in the code will be loaded for you.
+// It is the rendering backend responsibility to upload texture into your graphics API:
+// - ImGui_ImplXXXX_RenderDrawData() functions generally iterate platform_io->Textures[] to create/update/destroy each ImTextureData instance.
+// - Backend then set ImTextureData's TexID and BackendUserData.
+// - Texture id are passed back to you during rendering to identify the texture. Read FAQ entry about ImTextureID/ImTextureRef for more details.
+// Legacy path:
+// - Call Build() + GetTexDataAsAlpha8() or GetTexDataAsRGBA32() to build and retrieve pixels data.
// - Call SetTexID(my_tex_id); and pass the pointer/identifier to your texture in a format natural to your graphics API.
-// This value will be passed back to you during rendering to identify the texture. Read FAQ entry about ImTextureID for more details.
// Common pitfalls:
// - If you pass a 'glyph_ranges' array to AddFont*** functions, you need to make sure that your array persist up until the
// atlas is build (when calling GetTexData*** or Build()). We only copy the pointer, not the data.
@@ -3458,35 +3743,49 @@ struct ImFontAtlas
IMGUI_API ~ImFontAtlas();
IMGUI_API ImFont* AddFont(const ImFontConfig* font_cfg);
IMGUI_API ImFont* AddFontDefault(const ImFontConfig* font_cfg = NULL);
- IMGUI_API ImFont* AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL);
- IMGUI_API ImFont* AddFontFromMemoryTTF(void* font_data, int font_data_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // Note: Transfer ownership of 'ttf_data' to ImFontAtlas! Will be deleted after destruction of the atlas. Set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed.
- IMGUI_API ImFont* AddFontFromMemoryCompressedTTF(const void* compressed_font_data, int compressed_font_data_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data' still owned by caller. Compress with binary_to_compressed_c.cpp.
- IMGUI_API ImFont* AddFontFromMemoryCompressedBase85TTF(const char* compressed_font_data_base85, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data_base85' still owned by caller. Compress with binary_to_compressed_c.cpp with -base85 parameter.
- IMGUI_API void ClearInputData(); // Clear input data (all ImFontConfig structures including sizes, TTF data, glyph ranges, etc.) = all the data used to build the texture and fonts.
- IMGUI_API void ClearTexData(); // Clear output texture data (CPU side). Saves RAM once the texture has been copied to graphics memory.
- IMGUI_API void ClearFonts(); // Clear output font data (glyphs storage, UV coordinates).
- IMGUI_API void Clear(); // Clear all input and output.
-
- // Build atlas, retrieve pixel data.
- // User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID().
- // The pitch is always = Width * BytesPerPixels (1 or 4)
- // Building in RGBA32 format is provided for convenience and compatibility, but note that unless you manually manipulate or copy color data into
- // the texture (e.g. when using the AddCustomRect*** api), then the RGB pixels emitted will always be white (~75% of memory/bandwidth waste.
- 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() const { return Fonts.Size > 0 && TexReady; } // Bit ambiguous: used to detect when user didn't build texture but effectively we should check TexID != 0 except that would be backend dependent...
- void SetTexID(ImTextureID id) { TexID = id; }
+ IMGUI_API ImFont* AddFontFromFileTTF(const char* filename, float size_pixels = 0.0f, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL);
+ IMGUI_API ImFont* AddFontFromMemoryTTF(void* font_data, int font_data_size, float size_pixels = 0.0f, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // Note: Transfer ownership of 'ttf_data' to ImFontAtlas! Will be deleted after destruction of the atlas. Set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed.
+ IMGUI_API ImFont* AddFontFromMemoryCompressedTTF(const void* compressed_font_data, int compressed_font_data_size, float size_pixels = 0.0f, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data' still owned by caller. Compress with binary_to_compressed_c.cpp.
+ IMGUI_API ImFont* AddFontFromMemoryCompressedBase85TTF(const char* compressed_font_data_base85, float size_pixels = 0.0f, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data_base85' still owned by caller. Compress with binary_to_compressed_c.cpp with -base85 parameter.
+ IMGUI_API void RemoveFont(ImFont* font);
+
+ IMGUI_API void Clear(); // Clear everything (input fonts, output glyphs/textures)
+ IMGUI_API void CompactCache(); // Compact cached glyphs and texture.
+ IMGUI_API void SetFontLoader(const ImFontLoader* font_loader); // Change font loader at runtime.
+
+ // As we are transitioning toward a new font system, we expect to obsolete those soon:
+ IMGUI_API void ClearInputData(); // [OBSOLETE] Clear input data (all ImFontConfig structures including sizes, TTF data, glyph ranges, etc.) = all the data used to build the texture and fonts.
+ IMGUI_API void ClearFonts(); // [OBSOLETE] Clear input+output font data (same as ClearInputData() + glyphs storage, UV coordinates).
+ IMGUI_API void ClearTexData(); // [OBSOLETE] Clear CPU-side copy of the texture data. Saves RAM once the texture has been copied to graphics memory.
+
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ // Legacy path for build atlas + retrieving pixel data.
+ // - User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID().
+ // - The pitch is always = Width * BytesPerPixels (1 or 4)
+ // - Building in RGBA32 format is provided for convenience and compatibility, but note that unless you manually manipulate or copy color data into
+ // the texture (e.g. when using the AddCustomRect*** api), then the RGB pixels emitted will always be white (~75% of memory/bandwidth waste).
+ // - From 1.92 with backends supporting ImGuiBackendFlags_RendererHasTextures:
+ // - Calling Build(), GetTexDataAsAlpha8(), GetTexDataAsRGBA32() is not needed.
+ // - In backend: replace calls to ImFontAtlas::SetTexID() with calls to ImTextureData::SetTexID() after honoring texture creation.
+ 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
+ void SetTexID(ImTextureID id) { IM_ASSERT(TexRef._TexID == ImTextureID_Invalid); TexRef._TexData->TexID = id; } // Called by legacy backends. May be called before texture creation.
+ void SetTexID(ImTextureRef id) { IM_ASSERT(TexRef._TexID == ImTextureID_Invalid && id._TexData == NULL); TexRef._TexData->TexID = id._TexID; } // Called by legacy backends.
+ bool IsBuilt() const { return Fonts.Size > 0 && TexIsBuilt; } // Bit ambiguous: used to detect when user didn't build texture but effectively we should check TexID != 0 except that would be backend dependent..
+#endif
//-------------------------------------------
// Glyph Ranges
//-------------------------------------------
+ // Since 1.92: specifying glyph ranges is only useful/necessary if your backend doesn't support ImGuiBackendFlags_RendererHasTextures!
+ IMGUI_API const ImWchar* GetGlyphRangesDefault(); // Basic Latin, Extended Latin
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
// Helpers to retrieve list of common Unicode ranges (2 value per range, values are inclusive, zero-terminated list)
// NB: Make sure that your string are UTF-8 and NOT in your local code page.
// Read https://github.com/ocornut/imgui/blob/master/docs/FONTS.md/#about-utf-8-encoding for details.
// NB: Consider using ImFontGlyphRangesBuilder to build glyph ranges from textual data.
- IMGUI_API const ImWchar* GetGlyphRangesDefault(); // Basic Latin, Extended Latin
IMGUI_API const ImWchar* GetGlyphRangesGreek(); // Default + Greek and Coptic
IMGUI_API const ImWchar* GetGlyphRangesKorean(); // Default + Korean characters
IMGUI_API const ImWchar* GetGlyphRangesJapanese(); // Default + Hiragana, Katakana, Half-Width, Selection of 2999 Ideographs
@@ -3495,120 +3794,211 @@ struct ImFontAtlas
IMGUI_API const ImWchar* GetGlyphRangesCyrillic(); // Default + about 400 Cyrillic characters
IMGUI_API const ImWchar* GetGlyphRangesThai(); // Default + Thai characters
IMGUI_API const ImWchar* GetGlyphRangesVietnamese(); // Default + Vietnamese characters
+#endif
//-------------------------------------------
- // [BETA] Custom Rectangles/Glyphs API
+ // [ALPHA] Custom Rectangles/Glyphs API
//-------------------------------------------
- // You can request arbitrary rectangles to be packed into the atlas, for your own purposes.
- // - After calling Build(), you can query the rectangle position and render your pixels.
- // - If you render colored output, set 'atlas->TexPixelsUseColors = true' as this may help some backends decide of preferred texture format.
- // - 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.
+ // Register and retrieve custom rectangles
+ // - You can request arbitrary rectangles to be packed into the atlas, for your own purpose.
+ // - Since 1.92.X, packing is done immediately in the function call (previously packing was done during the Build call)
+ // - You can render your pixels into the texture right after calling the AddCustomRect() functions.
+ // - VERY IMPORTANT:
+ // - Texture may be created/resized at any time when calling ImGui or ImFontAtlas functions.
+ // - IT WILL INVALIDATE RECTANGLE DATA SUCH AS UV COORDINATES. Always use latest values from GetCustomRect().
+ // - UV coordinates are associated to the current texture identifier aka 'atlas->TexRef'. Both TexRef and UV coordinates are typically changed at the same time.
+ // - If you render colored output into your custom rectangles: set 'atlas->TexPixelsUseColors = true' as this may help some backends decide of preferred texture format.
// - 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) const;
- IMGUI_API bool GetMouseCursorTexData(ImGuiMouseCursor cursor, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]);
+ // - Note: this API may be reworked further in order to facilitate supporting e.g. multi-monitor, varying DPI settings.
+ // - (Pre-1.92 names) ------------> (1.92 names)
+ // - GetCustomRectByIndex() --> Use GetCustomRect()
+ // - CalcCustomRectUV() --> Use GetCustomRect() and read uv0, uv1 fields.
+ // - AddCustomRectRegular() --> Renamed to AddCustomRect()
+ // - AddCustomRectFontGlyph() --> Prefer using custom ImFontLoader inside ImFontConfig
+ // - ImFontAtlasCustomRect --> Renamed to ImFontAtlasRect
+ IMGUI_API ImFontAtlasRectId AddCustomRect(int width, int height, ImFontAtlasRect* out_r = NULL);// Register a rectangle. Return -1 (ImFontAtlasRectId_Invalid) on error.
+ IMGUI_API void RemoveCustomRect(ImFontAtlasRectId id); // Unregister a rectangle. Existing pixels will stay in texture until resized / garbage collected.
+ IMGUI_API bool GetCustomRect(ImFontAtlasRectId id, ImFontAtlasRect* out_r) const; // Get rectangle coordinates for current texture. Valid immediately, never store this (read above)!
//-------------------------------------------
// Members
//-------------------------------------------
+ // Input
ImFontAtlasFlags Flags; // Build flags (see ImFontAtlasFlags_)
- ImTextureID TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure.
- int TexDesiredWidth; // Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height.
- int TexGlyphPadding; // Padding between glyphs within texture in pixels. Defaults to 1. If your rendering method doesn't rely on bilinear filtering you may set this to 0 (will also need to set AntiAliasedLinesUseTex = false).
- bool Locked; // Marked as Locked by ImGui::NewFrame() so attempt to modify the atlas will assert.
+ ImTextureFormat TexDesiredFormat; // Desired texture format (default to ImTextureFormat_RGBA32 but may be changed to ImTextureFormat_Alpha8).
+ int TexGlyphPadding; // FIXME: Should be called "TexPackPadding". Padding between glyphs within texture in pixels. Defaults to 1. If your rendering method doesn't rely on bilinear filtering you may set this to 0 (will also need to set AntiAliasedLinesUseTex = false).
+ int TexMinWidth; // Minimum desired texture width. Must be a power of two. Default to 512.
+ int TexMinHeight; // Minimum desired texture height. Must be a power of two. Default to 128.
+ int TexMaxWidth; // Maximum desired texture width. Must be a power of two. Default to 8192.
+ int TexMaxHeight; // Maximum desired texture height. Must be a power of two. Default to 8192.
void* UserData; // Store your own atlas related user-data (if e.g. you have multiple font atlas).
+ // Output
+ // - Because textures are dynamically created/resized, the current texture identifier may changed at *ANY TIME* during the frame.
+ // - This should not affect you as you can always use the latest value. But note that any precomputed UV coordinates are only valid for the current TexRef.
+#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ ImTextureRef TexRef; // Latest texture identifier == TexData->GetTexRef().
+#else
+ union { ImTextureRef TexRef; ImTextureRef TexID; }; // Latest texture identifier == TexData->GetTexRef(). // RENAMED TexID to TexRef in 1.92.x
+#endif
+ ImTextureData* TexData; // Latest texture.
+
// [Internal]
- // NB: Access texture data via GetTexData*() calls! Which will setup a default font for you.
- bool TexReady; // Set when texture was built matching current font input
- bool TexPixelsUseColors; // Tell whether our texture data is known to use colors (rather than just alpha channel), in order to help backend select a format.
- unsigned char* TexPixelsAlpha8; // 1 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight
- unsigned int* TexPixelsRGBA32; // 4 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight * 4
- int TexWidth; // Texture width calculated during Build().
- int TexHeight; // Texture height calculated during Build().
- ImVec2 TexUvScale; // = (1.0f/TexWidth, 1.0f/TexHeight)
- ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel
+ ImVector<ImTextureData*> TexList; // Texture list (most often TexList.Size == 1). TexData is always == TexList.back(). DO NOT USE DIRECTLY, USE GetDrawData().Textures[]/GetPlatformIO().Textures[] instead!
+ bool Locked; // Marked as locked during ImGui::NewFrame()..EndFrame() scope if TexUpdates are not supported. Any attempt to modify the atlas will assert.
+ bool RendererHasTextures;// Copy of (BackendFlags & ImGuiBackendFlags_RendererHasTextures) from supporting context.
+ bool TexIsBuilt; // Set when texture was built matching current font input. Mostly useful for legacy IsBuilt() call.
+ bool TexPixelsUseColors; // Tell whether our texture data is known to use colors (rather than just alpha channel), in order to help backend select a format or conversion process.
+ ImVec2 TexUvScale; // = (1.0f/TexData->TexWidth, 1.0f/TexData->TexHeight). May change as new texture gets created.
+ ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel. May change as new texture gets created.
ImVector<ImFont*> Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font.
- ImVector<ImFontAtlasCustomRect> CustomRects; // Rectangles for packing custom texture data into the atlas.
- ImVector<ImFontConfig> ConfigData; // Configuration data
+ ImVector<ImFontConfig> Sources; // Source/configuration data
ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines
+ int TexNextUniqueID; // Next value to be stored in TexData->UniqueID
+ int FontNextUniqueID; // Next value to be stored in ImFont->FontID
+ ImVector<ImDrawListSharedData*> DrawListSharedDatas; // List of users for this atlas. Typically one per Dear ImGui context.
+ ImFontAtlasBuilder* Builder; // Opaque interface to our data that doesn't need to be public and may be discarded when rebuilding.
+ const ImFontLoader* FontLoader; // Font loader opaque interface (default to use FreeType when IMGUI_ENABLE_FREETYPE is defined, otherwise default to use stb_truetype). Use SetFontLoader() to change this at runtime.
+ const char* FontLoaderName; // Font loader name (for display e.g. in About box) == FontLoader->Name
+ void* FontLoaderData; // Font backend opaque storage
+ unsigned int FontLoaderFlags; // Shared flags (for all fonts) for font loader. THIS IS BUILD IMPLEMENTATION DEPENDENT (e.g. Per-font override is also available in ImFontConfig).
+ int RefCount; // Number of contexts using this atlas
+ ImGuiContext* OwnerContext; // Context which own the atlas will be in charge of updating and destroying it.
+
+ // [Obsolete]
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ // Legacy: You can 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. --> Prefer using a custom ImFontLoader.
+ ImFontAtlasRect TempRect; // For old GetCustomRectByIndex() API
+ inline ImFontAtlasRectId AddCustomRectRegular(int w, int h) { return AddCustomRect(w, h); } // RENAMED in 1.92.X
+ inline const ImFontAtlasRect* GetCustomRectByIndex(ImFontAtlasRectId id) { return GetCustomRect(id, &TempRect) ? &TempRect : NULL; } // OBSOLETED in 1.92.X
+ inline void CalcCustomRectUV(const ImFontAtlasRect* r, ImVec2* out_uv_min, ImVec2* out_uv_max) const { *out_uv_min = r->uv0; *out_uv_max = r->uv1; } // OBSOLETED in 1.92.X
+ IMGUI_API ImFontAtlasRectId AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int w, int h, float advance_x, const ImVec2& offset = ImVec2(0, 0)); // OBSOLETED in 1.92.X: Use custom ImFontLoader in ImFontConfig
+ IMGUI_API ImFontAtlasRectId AddCustomRectFontGlyphForSize(ImFont* font, float font_size, ImWchar codepoint, int w, int h, float advance_x, const ImVec2& offset = ImVec2(0, 0)); // ADDED AND OBSOLETED in 1.92.X
+#endif
+ //unsigned int FontBuilderFlags; // OBSOLETED in 1.92.X: Renamed to FontLoaderFlags.
+ //int TexDesiredWidth; // OBSOLETED in 1.92.X: Force texture width before calling Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height.
+ //typedef ImFontAtlasRect ImFontAtlasCustomRect; // OBSOLETED in 1.92.X
+ //typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+
+ //typedef ImFontGlyphRangesBuilder GlyphRangesBuilder; // OBSOLETED in 1.67+
+};
- // [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.
+// Font runtime data for a given size
+// Important: pointers to ImFontBaked are only valid for the current frame.
+struct ImFontBaked
+{
+ // [Internal] Members: Hot ~20/24 bytes (for CalcTextSize)
+ ImVector<float> IndexAdvanceX; // 12-16 // out // Sparse. Glyphs->AdvanceX in a directly indexable way (cache-friendly for CalcTextSize functions which only this info, and are often bottleneck in large UI).
+ float FallbackAdvanceX; // 4 // out // FindGlyph(FallbackChar)->AdvanceX
+ float Size; // 4 // in // Height of characters/line, set during loading (doesn't change after loading)
+ float RasterizerDensity; // 4 // in // Density this is baked at
+
+ // [Internal] Members: Hot ~28/36 bytes (for RenderText loop)
+ ImVector<ImU16> IndexLookup; // 12-16 // out // Sparse. Index glyphs by Unicode code-point.
+ ImVector<ImFontGlyph> Glyphs; // 12-16 // out // All glyphs.
+ int FallbackGlyphIndex; // 4 // out // Index of FontFallbackChar
+
+ // [Internal] Members: Cold
+ float Ascent, Descent; // 4+4 // out // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] (unscaled)
+ unsigned int MetricsTotalSurface:26;// 3 // 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)
+ unsigned int WantDestroy:1; // 0 // // Queued for destroy
+ unsigned int LoadNoFallback:1; // 0 // // Disable loading fallback in lower-level calls.
+ unsigned int LoadNoRenderOnLayout:1;// 0 // // Enable a two-steps mode where CalcTextSize() calls will load AdvanceX *without* rendering/packing glyphs. Only advantagous if you know that the glyph is unlikely to actually be rendered, otherwise it is slower because we'd do one query on the first CalcTextSize and one query on the first Draw.
+ int LastUsedFrame; // 4 // // Record of that time this was bounds
+ ImGuiID BakedId; // 4 // // Unique ID for this baked storage
+ ImFont* ContainerFont; // 4-8 // in // Parent font
+ void* FontLoaderDatas; // 4-8 // // Font loader opaque storage (per baked font * sources): single contiguous buffer allocated by imgui, passed to loader.
- // [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
+ // Functions
+ IMGUI_API ImFontBaked();
+ IMGUI_API void ClearOutputData();
+ IMGUI_API ImFontGlyph* FindGlyph(ImWchar c); // Return U+FFFD glyph if requested glyph doesn't exists.
+ IMGUI_API ImFontGlyph* FindGlyphNoFallback(ImWchar c); // Return NULL if glyph doesn't exist
+ IMGUI_API float GetCharAdvance(ImWchar c);
+ IMGUI_API bool IsGlyphLoaded(ImWchar c);
+};
- // [Obsolete]
- //typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+
- //typedef ImFontGlyphRangesBuilder GlyphRangesBuilder; // OBSOLETED in 1.67+
+// Font flags
+// (in future versions as we redesign font loading API, this will become more important and better documented. for now please consider this as internal/advanced use)
+enum ImFontFlags_
+{
+ ImFontFlags_None = 0,
+ ImFontFlags_NoLoadError = 1 << 1, // Disable throwing an error/assert when calling AddFontXXX() with missing file/data. Calling code is expected to check AddFontXXX() return value.
+ ImFontFlags_NoLoadGlyphs = 1 << 2, // [Internal] Disable loading new glyphs.
+ ImFontFlags_LockBakedSizes = 1 << 3, // [Internal] Disable loading new baked sizes, disable garbage collecting current ones. e.g. if you want to lock a font to a single size. Important: if you use this to preload given sizes, consider the possibility of multiple font density used on Retina display.
};
// Font runtime data and rendering
-// ImFontAtlas automatically loads a default embedded font for you when you call GetTexDataAsAlpha8() or GetTexDataAsRGBA32().
+// - ImFontAtlas automatically loads a default embedded font for you if you didn't load one manually.
+// - Since 1.92.X a font may be rendered as any size! Therefore a font doesn't have one specific size.
+// - Use 'font->GetFontBaked(size)' to retrieve the ImFontBaked* corresponding to a given size.
+// - If you used g.Font + g.FontSize (which is frequent from the ImGui layer), you can use g.FontBaked as a shortcut, as g.FontBaked == g.Font->GetFontBaked(g.FontSize).
struct ImFont
{
- // Members: Hot ~20/24 bytes (for CalcTextSize)
- ImVector<float> IndexAdvanceX; // 12-16 // out // // Sparse. Glyphs->AdvanceX in a directly indexable way (cache-friendly for CalcTextSize functions which only this info, and are often bottleneck in large UI).
- float FallbackAdvanceX; // 4 // out // = FallbackGlyph->AdvanceX
- float FontSize; // 4 // in // // Height of characters/line, set during loading (don't change after loading)
-
- // Members: Hot ~28/40 bytes (for CalcTextSize + render loop)
- ImVector<ImWchar> IndexLookup; // 12-16 // out // // Sparse. Index glyphs by Unicode code-point.
- ImVector<ImFontGlyph> Glyphs; // 12-16 // out // // All glyphs.
- const ImFontGlyph* FallbackGlyph; // 4-8 // out // = FindGlyph(FontFallbackChar)
-
- // Members: Cold ~32/40 bytes
- ImFontAtlas* ContainerAtlas; // 4-8 // out // // What we has been loaded into
- const ImFontConfig* ConfigData; // 4-8 // in // // Pointer within ContainerAtlas->ConfigData
- 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 // out // = FFFD/'?' // Character used if a glyph isn't found.
- ImWchar EllipsisChar; // 2 // out // = '...'/'.'// Character used for ellipsis rendering.
- short EllipsisCharCount; // 1 // out // 1 or 3
- float EllipsisWidth; // 4 // out // Width
- float EllipsisCharStep; // 4 // out // Step between characters when EllipsisCount > 0
- 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] (unscaled)
- 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)
- 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.
+ // [Internal] Members: Hot ~12-20 bytes
+ ImFontBaked* LastBaked; // 4-8 // Cache last bound baked. NEVER USE DIRECTLY. Use GetFontBaked().
+ ImFontAtlas* ContainerAtlas; // 4-8 // What we have been loaded into.
+ ImFontFlags Flags; // 4 // Font flags.
+ float CurrentRasterizerDensity; // Current rasterizer density. This is a varying state of the font.
+
+ // [Internal] Members: Cold ~24-52 bytes
+ // Conceptually Sources[] is the list of font sources merged to create this font.
+ ImGuiID FontId; // Unique identifier for the font
+ float LegacySize; // 4 // in // Font size passed to AddFont(). Use for old code calling PushFont() expecting to use that size. (use ImGui::GetFontBaked() to get font baked at current bound size).
+ ImVector<ImFontConfig*> Sources; // 16 // in // List of sources. Pointers within ContainerAtlas->Sources[]
+ ImWchar EllipsisChar; // 2-4 // out // Character used for ellipsis rendering ('...').
+ ImWchar FallbackChar; // 2-4 // out // Character used if a glyph isn't found (U+FFFD, '?')
+ ImU8 Used8kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/8192/8]; // 1 bytes if ImWchar=ImWchar16, 16 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.
+ bool EllipsisAutoBake; // 1 // // Mark when the "..." glyph needs to be generated.
+ ImGuiStorage RemapPairs; // 16 // // Remapping pairs when using AddRemapChar(), otherwise empty.
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ float Scale; // 4 // in // Legacy base font scale (~1.0f), multiplied by the per-window font scale which you can adjust with SetWindowFontScale()
+#endif
// Methods
IMGUI_API ImFont();
IMGUI_API ~ImFont();
- IMGUI_API const ImFontGlyph*FindGlyph(ImWchar c) const;
- IMGUI_API const ImFontGlyph*FindGlyphNoFallback(ImWchar c) const;
- float GetCharAdvance(ImWchar c) const { return ((int)c < IndexAdvanceX.Size) ? IndexAdvanceX[(int)c] : FallbackAdvanceX; }
- bool IsLoaded() const { return ContainerAtlas != NULL; }
- const char* GetDebugName() const { return ConfigData ? ConfigData->Name : "<unknown>"; }
+ IMGUI_API bool IsGlyphInFont(ImWchar c);
+ bool IsLoaded() const { return ContainerAtlas != NULL; }
+ const char* GetDebugName() const { return Sources.Size ? Sources[0]->Name : "<unknown>"; } // Fill ImFontConfig::Name.
+ // [Internal] Don't use!
// 'max_width' stops rendering after a certain width (could be turned into a 2d size). FLT_MAX to disable.
// 'wrap_width' enable automatic word-wrapping across multiple lines to fit into given width. 0.0f to disable.
- IMGUI_API ImVec2 CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** remaining = NULL) const; // utf8
- IMGUI_API const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const;
- IMGUI_API void RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, ImWchar c) const;
- IMGUI_API void RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width = 0.0f, bool cpu_fine_clip = false) const;
+ IMGUI_API ImFontBaked* GetFontBaked(float font_size, float density = -1.0f); // Get or create baked data for given size
+ IMGUI_API ImVec2 CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** out_remaining = NULL);
+ IMGUI_API const char* CalcWordWrapPosition(float size, const char* text, const char* text_end, float wrap_width);
+ IMGUI_API void RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, ImWchar c, const ImVec4* cpu_fine_clip = NULL);
+ IMGUI_API void RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width = 0.0f, ImDrawTextFlags flags = 0);
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ inline const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) { return CalcWordWrapPosition(LegacySize * scale, text, text_end, wrap_width); }
+#endif
// [Internal] Don't use!
- IMGUI_API void BuildLookupTable();
IMGUI_API void ClearOutputData();
- IMGUI_API void GrowIndex(int new_size);
- 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 AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint); // Makes 'from_codepoint' character points to 'to_codepoint' glyph.
IMGUI_API bool IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last);
};
+// This is provided for consistency (but we don't actually use this)
+inline ImTextureID ImTextureRef::GetTexID() const
+{
+ IM_ASSERT(!(_TexData != NULL && _TexID != ImTextureID_Invalid));
+ return _TexData ? _TexData->TexID : _TexID;
+}
+
+// Using an indirection to avoid patching ImDrawCmd after a SetTexID() call (but this could be an alternative solution too)
+inline ImTextureID ImDrawCmd::GetTexID() const
+{
+ // If you are getting this assert: A renderer backend with support for ImGuiBackendFlags_RendererHasTextures (1.92)
+ // must iterate and handle ImTextureData requests stored in ImDrawData::Textures[].
+ ImTextureID tex_id = TexRef._TexData ? TexRef._TexData->TexID : TexRef._TexID; // == TexRef.GetTexID() above.
+ if (TexRef._TexData != NULL)
+ IM_ASSERT(tex_id != ImTextureID_Invalid && "ImDrawCmd is referring to ImTextureData that wasn't uploaded to graphics system. Backend must call ImTextureData::SetTexID() after handling ImTextureStatus_WantCreate request!");
+ return tex_id;
+}
+
//-----------------------------------------------------------------------------
// [SECTION] Viewports
//-----------------------------------------------------------------------------
@@ -3648,6 +4038,7 @@ struct ImGuiViewport
ImGuiViewportFlags Flags; // See ImGuiViewportFlags_
ImVec2 Pos; // Main Area: Position of the viewport (Dear ImGui coordinates are the same as OS desktop/native coordinates)
ImVec2 Size; // Main Area: Size of the viewport.
+ ImVec2 FramebufferScale; // Density of the viewport for Retina display (always 1,1 on Windows, may be 2,2 etc on macOS/iOS). This will affect font rasterizer density.
ImVec2 WorkPos; // Work Area: Position of the viewport minus task bars, menus bars, status bars (>= Pos)
ImVec2 WorkSize; // Work Area: Size of the viewport minus task bars, menu bars, status bars (<= Size)
float DpiScale; // 1.0f = 96 DPI = No extra scale.
@@ -3661,8 +4052,8 @@ struct ImGuiViewport
// The library never uses those fields, they are merely storage to facilitate backend implementation.
void* RendererUserData; // void* to hold custom data structure for the renderer (e.g. swap chain, framebuffers etc.). generally set by your Renderer_CreateWindow function.
void* PlatformUserData; // void* to hold custom data structure for the OS / platform (e.g. windowing info, render context). generally set by your Platform_CreateWindow function.
- void* PlatformHandle; // void* to hold higher-level, platform window handle (e.g. HWND, GLFWWindow*, SDL_Window*), for FindViewportByPlatformHandle().
- void* PlatformHandleRaw; // void* to hold lower-level, platform-native window handle (under Win32 this is expected to be a HWND, unused for other platforms), when using an abstraction layer like GLFW or SDL (where PlatformHandle would be a SDL_Window*)
+ void* PlatformHandle; // void* to hold higher-level, platform window handle (e.g. HWND for Win32 backend, Uint32 WindowID for SDL, GLFWWindow* for GLFW), for FindViewportByPlatformHandle().
+ void* PlatformHandleRaw; // void* to hold lower-level, platform-native window handle (always HWND on Win32 platform, unused for other platforms).
bool PlatformWindowCreated; // Platform window has been created (Platform_CreateWindow() has been called). This is false during the first frame where a viewport is being created.
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)
@@ -3732,7 +4123,7 @@ struct ImGuiPlatformIO
IMGUI_API ImGuiPlatformIO();
//------------------------------------------------------------------
- // Interface with OS and Platform backend (basic)
+ // Input - Interface with OS and Platform backend (most common stuff)
//------------------------------------------------------------------
// Optional: Access OS clipboard
@@ -3742,7 +4133,7 @@ struct ImGuiPlatformIO
void* Platform_ClipboardUserData;
// Optional: Open link/folder/file in OS Shell
- // (default to use ShellExecuteA() on Windows, system() on Linux/Mac)
+ // (default to use ShellExecuteW() on Windows, system() on Linux/Mac)
bool (*Platform_OpenInShellFn)(ImGuiContext* ctx, const char* path);
void* Platform_OpenInShellUserData;
@@ -3757,14 +4148,18 @@ struct ImGuiPlatformIO
ImWchar Platform_LocaleDecimalPoint; // '.'
//------------------------------------------------------------------
- // Interface with Renderer Backend
+ // Input - Interface with Renderer Backend
//------------------------------------------------------------------
+ // Optional: Maximum texture size supported by renderer (used to adjust how we size textures). 0 if not known.
+ int Renderer_TextureMaxWidth;
+ int Renderer_TextureMaxHeight;
+
// Written by some backends during ImGui_ImplXXXX_RenderDrawData() call to point backend_specific ImGui_ImplXXXX_RenderState* structure.
void* Renderer_RenderState;
//------------------------------------------------------------------
- // Input - Interface with OS/backends (Multi-Viewport support!)
+ // Input - Interface with Platform & Renderer backends for Multi-Viewport support
//------------------------------------------------------------------
// For reference, the second column shows which function are generally calling the Platform Functions:
@@ -3787,6 +4182,7 @@ struct ImGuiPlatformIO
ImVec2 (*Platform_GetWindowPos)(ImGuiViewport* vp); // N . . . . //
void (*Platform_SetWindowSize)(ImGuiViewport* vp, ImVec2 size); // . . U . . // Set platform window client area size (ignoring OS decorations such as OS title bar etc.)
ImVec2 (*Platform_GetWindowSize)(ImGuiViewport* vp); // N . . . . // Get platform window client area size
+ ImVec2 (*Platform_GetWindowFramebufferScale)(ImGuiViewport* vp); // N . . . . // Return viewport density. Always 1,1 on Windows, often 2,2 on Retina display on macOS/iOS. MUST BE INTEGER VALUES.
void (*Platform_SetWindowFocus)(ImGuiViewport* vp); // N . . . . // Move window to front and set input focus
bool (*Platform_GetWindowFocus)(ImGuiViewport* vp); // . . U . . //
bool (*Platform_GetWindowMinimized)(ImGuiViewport* vp); // N . . . . // Get platform window minimized state. When minimized, we generally won't attempt to get/set size and contents will be culled more easily
@@ -3813,12 +4209,16 @@ struct ImGuiPlatformIO
ImVector<ImGuiPlatformMonitor> Monitors;
//------------------------------------------------------------------
- // Output - List of viewports to render into platform windows
+ // Output
//------------------------------------------------------------------
+ // Textures list (the list is updated by calling ImGui::EndFrame or ImGui::Render)
+ // The ImGui_ImplXXXX_RenderDrawData() function of each backend generally access this via ImDrawData::Textures which points to this. The array is available here mostly because backends will want to destroy textures on shutdown.
+ ImVector<ImTextureData*> Textures; // List of textures used by Dear ImGui (most often 1) + contents of external texture list is automatically appended into this.
+
// Viewports list (the list is updated by calling ImGui::EndFrame or ImGui::Render)
// (in the future we will attempt to organize this feature to remove the need for a "main viewport")
- ImVector<ImGuiViewport*> Viewports; // Main viewports, followed by all secondary viewports.
+ ImVector<ImGuiViewport*> Viewports; // Main viewports, followed by all secondary viewports.
};
// (Optional) This is required when enabling multi-viewport. Represent the bounds of each connected monitor/display and their DPI.
@@ -3832,14 +4232,16 @@ struct ImGuiPlatformMonitor
ImGuiPlatformMonitor() { MainPos = MainSize = WorkPos = WorkSize = ImVec2(0, 0); DpiScale = 1.0f; PlatformHandle = NULL; }
};
-// (Optional) Support for IME (Input Method Editor) via the platform_io.Platform_SetImeDataFn() function.
+// (Optional) Support for IME (Input Method Editor) via the platform_io.Platform_SetImeDataFn() function. Handler is called during EndFrame().
struct ImGuiPlatformImeData
{
- bool WantVisible; // A widget wants the IME to be visible
- ImVec2 InputPos; // Position of the input cursor
- float InputLineHeight; // Line height
+ bool WantVisible; // A widget wants the IME to be visible.
+ bool WantTextInput; // A widget wants text input, not necessarily IME to be visible. This is automatically set to the upcoming value of io.WantTextInput.
+ ImVec2 InputPos; // Position of input cursor (for IME).
+ float InputLineHeight; // Line height (for IME).
+ ImGuiID ViewportId; // ID of platform window/viewport.
- ImGuiPlatformImeData() { memset(this, 0, sizeof(*this)); }
+ ImGuiPlatformImeData() { memset(this, 0, sizeof(*this)); }
};
//-----------------------------------------------------------------------------
@@ -3851,37 +4253,42 @@ struct ImGuiPlatformImeData
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
namespace ImGui
{
+ // OBSOLETED in 1.92.0 (from June 2025)
+ inline void PushFont(ImFont* font) { PushFont(font, font ? font->LegacySize : 0.0f); }
+ IMGUI_API void SetWindowFontScale(float scale); // Set font scale factor for current window. Prefer using PushFont(NULL, style.FontSizeBase * factor) or use style.FontScaleMain to scale all windows.
+ // OBSOLETED in 1.91.9 (from February 2025)
+ IMGUI_API void Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col); // <-- 'border_col' was removed in favor of ImGuiCol_ImageBorder. If you use 'tint_col', use ImageWithBg() instead.
// OBSOLETED in 1.91.0 (from July 2024)
- static inline void PushButtonRepeat(bool repeat) { PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat); }
- static inline void PopButtonRepeat() { PopItemFlag(); }
- static inline void PushTabStop(bool tab_stop) { PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); }
- static inline void PopTabStop() { PopItemFlag(); }
+ inline void PushButtonRepeat(bool repeat) { PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat); }
+ inline void PopButtonRepeat() { PopItemFlag(); }
+ inline void PushTabStop(bool tab_stop) { PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); }
+ inline void PopTabStop() { PopItemFlag(); }
IMGUI_API ImVec2 GetContentRegionMax(); // Content boundaries max (e.g. window boundaries including scrolling, or current column boundaries). You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()!
IMGUI_API ImVec2 GetWindowContentRegionMin(); // Content boundaries min for the window (roughly (0,0)-Scroll), in window-local coordinates. You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()!
IMGUI_API ImVec2 GetWindowContentRegionMax(); // Content boundaries max for the window (roughly (0,0)+Size-Scroll), in window-local coordinates. You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()!
// OBSOLETED in 1.90.0 (from September 2023)
- static inline bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags window_flags = 0) { return BeginChild(id, size, ImGuiChildFlags_FrameStyle, window_flags); }
- static inline void EndChildFrame() { EndChild(); }
- //static inline bool BeginChild(const char* str_id, const ImVec2& size_arg, bool borders, ImGuiWindowFlags window_flags){ return BeginChild(str_id, size_arg, borders ? ImGuiChildFlags_Borders : ImGuiChildFlags_None, window_flags); } // Unnecessary as true == ImGuiChildFlags_Borders
- //static inline bool BeginChild(ImGuiID id, const ImVec2& size_arg, bool borders, ImGuiWindowFlags window_flags) { return BeginChild(id, size_arg, borders ? ImGuiChildFlags_Borders : ImGuiChildFlags_None, window_flags); } // Unnecessary as true == ImGuiChildFlags_Borders
- static inline void ShowStackToolWindow(bool* p_open = NULL) { ShowIDStackToolWindow(p_open); }
+ inline bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags window_flags = 0) { return BeginChild(id, size, ImGuiChildFlags_FrameStyle, window_flags); }
+ inline void EndChildFrame() { EndChild(); }
+ //inline bool BeginChild(const char* str_id, const ImVec2& size_arg, bool borders, ImGuiWindowFlags window_flags){ return BeginChild(str_id, size_arg, borders ? ImGuiChildFlags_Borders : ImGuiChildFlags_None, window_flags); } // Unnecessary as true == ImGuiChildFlags_Borders
+ //inline bool BeginChild(ImGuiID id, const ImVec2& size_arg, bool borders, ImGuiWindowFlags window_flags) { return BeginChild(id, size_arg, borders ? ImGuiChildFlags_Borders : ImGuiChildFlags_None, window_flags); } // Unnecessary as true == ImGuiChildFlags_Borders
+ inline void ShowStackToolWindow(bool* p_open = NULL) { ShowIDStackToolWindow(p_open); }
IMGUI_API bool Combo(const char* label, int* current_item, bool (*old_callback)(void* user_data, int idx, const char** out_text), void* user_data, int items_count, int popup_max_height_in_items = -1);
IMGUI_API bool ListBox(const char* label, int* current_item, bool (*old_callback)(void* user_data, int idx, const char** out_text), void* user_data, int items_count, int height_in_items = -1);
// OBSOLETED in 1.89.7 (from June 2023)
IMGUI_API void SetItemAllowOverlap(); // Use SetNextItemAllowOverlap() before item.
- // OBSOLETED in 1.89.4 (from March 2023)
- static inline void PushAllowKeyboardFocus(bool tab_stop) { PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); }
- static inline void PopAllowKeyboardFocus() { PopItemFlag(); }
- // OBSOLETED in 1.87 (from February 2022 but more formally obsoleted April 2024)
- IMGUI_API ImGuiKey GetKeyIndex(ImGuiKey key); // Map ImGuiKey_* values into legacy native key index. == io.KeyMap[key]. When using a 1.87+ backend using io.AddKeyEvent(), calling GetKeyIndex() with ANY ImGuiKey_XXXX values will return the same value!
- //static inline ImGuiKey GetKeyIndex(ImGuiKey key) { IM_ASSERT(key >= ImGuiKey_NamedKey_BEGIN && key < ImGuiKey_NamedKey_END); return key; }
// Some of the older obsolete names along with their replacement (commented out so they are not reported in IDE)
+ //-- OBSOLETED in 1.89.4 (from March 2023)
+ //static inline void PushAllowKeyboardFocus(bool tab_stop) { PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); }
+ //static inline void PopAllowKeyboardFocus() { PopItemFlag(); }
//-- OBSOLETED in 1.89 (from August 2022)
//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)); // --> Use new ImageButton() signature (explicit item id, regular FramePadding). Refer to code in 1.91 if you want to grab a copy of this version.
//-- OBSOLETED in 1.88 (from May 2022)
//static inline void CaptureKeyboardFromApp(bool want_capture_keyboard = true) { SetNextFrameWantCaptureKeyboard(want_capture_keyboard); } // Renamed as name was misleading + removed default value.
//static inline void CaptureMouseFromApp(bool want_capture_mouse = true) { SetNextFrameWantCaptureMouse(want_capture_mouse); } // Renamed as name was misleading + removed default value.
+ //-- OBSOLETED in 1.87 (from February 2022, more formally obsoleted April 2024)
+ //IMGUI_API ImGuiKey GetKeyIndex(ImGuiKey key); { IM_ASSERT(key >= ImGuiKey_NamedKey_BEGIN && key < ImGuiKey_NamedKey_END); const ImGuiKeyData* key_data = GetKeyData(key); return (ImGuiKey)(key_data - g.IO.KeysData); } // Map ImGuiKey_* values into legacy native key index. == io.KeyMap[key]. When using a 1.87+ backend using io.AddKeyEvent(), calling GetKeyIndex() with ANY ImGuiKey_XXXX values will return the same value!
+ //static inline ImGuiKey GetKeyIndex(ImGuiKey key) { IM_ASSERT(key >= ImGuiKey_NamedKey_BEGIN && key < ImGuiKey_NamedKey_END); return key; }
//-- OBSOLETED in 1.86 (from November 2021)
//IMGUI_API void CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end); // Code removed, see 1.90 for last version of the code. Calculate range of visible items for large list of evenly sized items. Prefer using ImGuiListClipper.
//-- OBSOLETED in 1.85 (from August 2021)
@@ -3936,6 +4343,25 @@ namespace ImGui
//static inline void SetScrollPosHere() { SetScrollHere(); } // OBSOLETED in 1.42
}
+//-- OBSOLETED in 1.92.x: ImFontAtlasCustomRect becomes ImTextureRect
+// - ImFontAtlasCustomRect::X,Y --> ImTextureRect::x,y
+// - ImFontAtlasCustomRect::Width,Height --> ImTextureRect::w,h
+// - ImFontAtlasCustomRect::GlyphColored --> if you need to write to this, instead you can write to 'font->Glyphs.back()->Colored' after calling AddCustomRectFontGlyph()
+// We could make ImTextureRect an union to use old names, but 1) this would be confusing 2) the fix is easy 3) ImFontAtlasCustomRect was always a rather esoteric api.
+typedef ImFontAtlasRect ImFontAtlasCustomRect;
+/*struct ImFontAtlasCustomRect
+{
+ unsigned short X, Y; // Output // Packed position in Atlas
+ unsigned short Width, Height; // Input // [Internal] Desired rectangle dimension
+ unsigned int GlyphID:31; // Input // [Internal] For custom font glyphs only (ID < 0x110000)
+ unsigned int GlyphColored:1; // Input // [Internal] For custom font glyphs only: glyph is colored, removed tinting.
+ float GlyphAdvanceX; // Input // [Internal] For custom font glyphs only: glyph xadvance
+ ImVec2 GlyphOffset; // Input // [Internal] For custom font glyphs only: glyph display offset
+ ImFont* Font; // Input // [Internal] For custom font glyphs only: target font
+ ImFontAtlasCustomRect() { X = Y = 0xFFFF; Width = Height = 0; GlyphID = 0; GlyphColored = 0; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0, 0); Font = NULL; }
+ bool IsPacked() const { return X != 0xFFFF; }
+};*/
+
//-- OBSOLETED in 1.82 (from Mars 2021): flags for AddRect(), AddRectFilled(), AddImageRounded(), PathRect()
//typedef ImDrawFlags ImDrawCornerFlags;
//enum ImDrawCornerFlags_
diff --git a/source/code/Libs/imgui/imgui_draw.cpp b/source/code/Libs/imgui/imgui_draw.cpp index 5efea94..98cca3c 100644 --- a/source/code/Libs/imgui/imgui_draw.cpp +++ b/source/code/Libs/imgui/imgui_draw.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.4
+// dear imgui, v1.92.3
// (drawing and font code)
/*
@@ -13,8 +13,9 @@ Index of this file:
// [SECTION] ImDrawData
// [SECTION] Helpers ShadeVertsXXX functions
// [SECTION] ImFontConfig
-// [SECTION] ImFontAtlas
-// [SECTION] ImFontAtlas glyph ranges helpers
+// [SECTION] ImFontAtlas, ImFontAtlasBuilder
+// [SECTION] ImFontAtlas: backend for stb_truetype
+// [SECTION] ImFontAtlas: glyph ranges helpers
// [SECTION] ImFontGlyphRangesBuilder
// [SECTION] ImFont
// [SECTION] ImGui Internal Render Helpers
@@ -39,6 +40,7 @@ Index of this file:
#endif
#include <stdio.h> // vsnprintf, sscanf, printf
+#include <stdint.h> // intptr_t
// Visual Studio warnings
#ifdef _MSC_VER
@@ -46,7 +48,7 @@ Index of this file:
#pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff)
#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
#pragma warning (disable: 26451) // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
-#pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3). [MSVC Static Analyzer)
+#pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
#endif
// Clang/GCC warnings with -Weverything
@@ -66,13 +68,19 @@ Index of this file:
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
#pragma clang diagnostic ignored "-Wreserved-identifier" // warning: identifier '_Xxx' is reserved because it starts with '_' followed by a capital letter
#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access
+#pragma clang diagnostic ignored "-Wnontrivial-memaccess" // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
+#pragma clang diagnostic ignored "-Wcast-qual" // warning: cast from 'const xxxx *' to 'xxx *' drops const qualifier
+#pragma clang diagnostic ignored "-Wswitch-default" // warning: 'switch' missing 'default' label
#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
-#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 "-Wstack-protector" // warning: stack protector not protecting local variables: variable length buffer
-#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 "-Wunused-function" // warning: 'xxxx' defined but not used
+#pragma GCC diagnostic ignored "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe
+#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 "-Wstack-protector" // warning: stack protector not protecting local variables: variable length buffer
+#pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when simplifying division / ..when changing X +- C1 cmp C2 to X cmp C2 -+ C1
+#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 "-Wcast-qual" // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers
#endif
//-------------------------------------------------------------------------
@@ -101,16 +109,15 @@ namespace IMGUI_STB_NAMESPACE
#if defined(__clang__)
#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wunused-function"
+#pragma clang diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
#pragma clang diagnostic ignored "-Wmissing-prototypes"
#pragma clang diagnostic ignored "-Wimplicit-fallthrough"
-#pragma clang diagnostic ignored "-Wcast-qual" // warning: cast from 'const xxxx *' to 'xxx *' drops const qualifier
#endif
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wtype-limits" // warning: comparison is always true due to limited range of data type [-Wtype-limits]
-#pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers
+#pragma GCC diagnostic ignored "-Wimplicit-fallthrough" // warning: this statement may fall through
#endif
#ifndef STB_RECT_PACK_IMPLEMENTATION // in case the user already have an implementation in the _same_ compilation unit (e.g. unity builds)
@@ -139,6 +146,7 @@ namespace IMGUI_STB_NAMESPACE
#define STBTT_fabs(x) ImFabs(x)
#define STBTT_ifloor(x) ((int)ImFloor(x))
#define STBTT_iceil(x) ((int)ImCeil(x))
+#define STBTT_strlen(x) ImStrlen(x)
#define STBTT_STATIC
#define STB_TRUETYPE_IMPLEMENTATION
#else
@@ -211,13 +219,14 @@ void ImGui::StyleColorsDark(ImGuiStyle* dst)
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_InputTextCursor] = colors[ImGuiCol_Text];
colors[ImGuiCol_TabHovered] = colors[ImGuiCol_HeaderHovered];
colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.80f);
colors[ImGuiCol_TabSelected] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f);
colors[ImGuiCol_TabSelectedOverline] = colors[ImGuiCol_HeaderActive];
colors[ImGuiCol_TabDimmed] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f);
colors[ImGuiCol_TabDimmedSelected] = ImLerp(colors[ImGuiCol_TabSelected], colors[ImGuiCol_TitleBg], 0.40f);
- colors[ImGuiCol_TabDimmedSelectedOverline] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f);
+ colors[ImGuiCol_TabDimmedSelectedOverline] = ImVec4(0.50f, 0.50f, 0.50f, 0.00f);
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);
@@ -231,6 +240,7 @@ void ImGui::StyleColorsDark(ImGuiStyle* dst)
colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.06f);
colors[ImGuiCol_TextLink] = colors[ImGuiCol_HeaderActive];
colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f);
+ colors[ImGuiCol_TreeLines] = colors[ImGuiCol_Border];
colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f);
colors[ImGuiCol_NavCursor] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f);
@@ -276,13 +286,14 @@ void ImGui::StyleColorsClassic(ImGuiStyle* dst)
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_InputTextCursor] = colors[ImGuiCol_Text];
colors[ImGuiCol_TabHovered] = colors[ImGuiCol_HeaderHovered];
colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.80f);
colors[ImGuiCol_TabSelected] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f);
colors[ImGuiCol_TabSelectedOverline] = colors[ImGuiCol_HeaderActive];
colors[ImGuiCol_TabDimmed] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f);
colors[ImGuiCol_TabDimmedSelected] = ImLerp(colors[ImGuiCol_TabSelected], colors[ImGuiCol_TitleBg], 0.40f);
- colors[ImGuiCol_TabDimmedSelectedOverline] = colors[ImGuiCol_HeaderActive];
+ colors[ImGuiCol_TabDimmedSelectedOverline] = ImVec4(0.53f, 0.53f, 0.87f, 0.00f);
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);
@@ -296,6 +307,7 @@ void ImGui::StyleColorsClassic(ImGuiStyle* dst)
colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.07f);
colors[ImGuiCol_TextLink] = colors[ImGuiCol_HeaderActive];
colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f);
+ colors[ImGuiCol_TreeLines] = colors[ImGuiCol_Border];
colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f);
colors[ImGuiCol_NavCursor] = colors[ImGuiCol_HeaderHovered];
colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f);
@@ -342,13 +354,14 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst)
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_InputTextCursor] = colors[ImGuiCol_Text];
colors[ImGuiCol_TabHovered] = colors[ImGuiCol_HeaderHovered];
colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.90f);
colors[ImGuiCol_TabSelected] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f);
colors[ImGuiCol_TabSelectedOverline] = colors[ImGuiCol_HeaderActive];
colors[ImGuiCol_TabDimmed] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f);
colors[ImGuiCol_TabDimmedSelected] = ImLerp(colors[ImGuiCol_TabSelected], colors[ImGuiCol_TitleBg], 0.40f);
- colors[ImGuiCol_TabDimmedSelectedOverline] = ImVec4(0.26f, 0.59f, 1.00f, 1.00f);
+ colors[ImGuiCol_TabDimmedSelectedOverline] = ImVec4(0.26f, 0.59f, 1.00f, 0.00f);
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);
@@ -362,6 +375,7 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst)
colors[ImGuiCol_TableRowBgAlt] = ImVec4(0.30f, 0.30f, 0.30f, 0.09f);
colors[ImGuiCol_TextLink] = colors[ImGuiCol_HeaderActive];
colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f);
+ colors[ImGuiCol_TreeLines] = colors[ImGuiCol_Border];
colors[ImGuiCol_DragDropTarget] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f);
colors[ImGuiCol_NavCursor] = colors[ImGuiCol_HeaderHovered];
colors[ImGuiCol_NavWindowingHighlight] = ImVec4(0.70f, 0.70f, 0.70f, 0.70f);
@@ -376,6 +390,7 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst)
ImDrawListSharedData::ImDrawListSharedData()
{
memset(this, 0, sizeof(*this));
+ InitialFringeScale = 1.0f;
for (int i = 0; i < IM_ARRAYSIZE(ArcFastVtx); i++)
{
const float a = ((float)i * 2 * IM_PI) / (float)IM_ARRAYSIZE(ArcFastVtx);
@@ -384,6 +399,11 @@ ImDrawListSharedData::ImDrawListSharedData()
ArcFastRadiusCutoff = IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_R(IM_DRAWLIST_ARCFAST_SAMPLE_MAX, CircleSegmentMaxError);
}
+ImDrawListSharedData::~ImDrawListSharedData()
+{
+ IM_ASSERT(DrawLists.Size == 0);
+}
+
void ImDrawListSharedData::SetCircleTessellationMaxError(float max_error)
{
if (CircleSegmentMaxError == max_error)
@@ -399,14 +419,35 @@ void ImDrawListSharedData::SetCircleTessellationMaxError(float max_error)
ArcFastRadiusCutoff = IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_R(IM_DRAWLIST_ARCFAST_SAMPLE_MAX, CircleSegmentMaxError);
}
+ImDrawList::ImDrawList(ImDrawListSharedData* shared_data)
+{
+ memset(this, 0, sizeof(*this));
+ _SetDrawListSharedData(shared_data);
+}
+
+ImDrawList::~ImDrawList()
+{
+ _ClearFreeMemory();
+ _SetDrawListSharedData(NULL);
+}
+
+void ImDrawList::_SetDrawListSharedData(ImDrawListSharedData* data)
+{
+ if (_Data != NULL)
+ _Data->DrawLists.find_erase_unsorted(this);
+ _Data = data;
+ if (_Data != NULL)
+ _Data->DrawLists.push_back(this);
+}
+
// Initialize before use in a new frame. We always have a command ready in the buffer.
-// In the majority of cases, you would want to call PushClipRect() and PushTextureID() after this.
+// In the majority of cases, you would want to call PushClipRect() and PushTexture() after this.
void ImDrawList::_ResetForNewFrame()
{
// Verify that the ImDrawCmd fields we want to memcmp() are contiguous in memory.
IM_STATIC_ASSERT(offsetof(ImDrawCmd, ClipRect) == 0);
- IM_STATIC_ASSERT(offsetof(ImDrawCmd, TextureId) == sizeof(ImVec4));
- IM_STATIC_ASSERT(offsetof(ImDrawCmd, VtxOffset) == sizeof(ImVec4) + sizeof(ImTextureID));
+ IM_STATIC_ASSERT(offsetof(ImDrawCmd, TexRef) == sizeof(ImVec4));
+ IM_STATIC_ASSERT(offsetof(ImDrawCmd, VtxOffset) == sizeof(ImVec4) + sizeof(ImTextureRef));
if (_Splitter._Count > 1)
_Splitter.Merge(this);
@@ -419,12 +460,12 @@ void ImDrawList::_ResetForNewFrame()
_VtxWritePtr = NULL;
_IdxWritePtr = NULL;
_ClipRectStack.resize(0);
- _TextureIdStack.resize(0);
+ _TextureStack.resize(0);
_CallbacksDataBuf.resize(0);
_Path.resize(0);
_Splitter.Clear();
CmdBuffer.push_back(ImDrawCmd());
- _FringeScale = 1.0f;
+ _FringeScale = _Data->InitialFringeScale;
}
void ImDrawList::_ClearFreeMemory()
@@ -437,15 +478,16 @@ void ImDrawList::_ClearFreeMemory()
_VtxWritePtr = NULL;
_IdxWritePtr = NULL;
_ClipRectStack.clear();
- _TextureIdStack.clear();
+ _TextureStack.clear();
_CallbacksDataBuf.clear();
_Path.clear();
_Splitter.ClearFreeMemory();
}
+// Note: For multi-threaded rendering, consider using `imgui_threaded_rendering` from https://github.com/ocornut/imgui_club
ImDrawList* ImDrawList::CloneOutput() const
{
- ImDrawList* dst = IM_NEW(ImDrawList(_Data));
+ ImDrawList* dst = IM_NEW(ImDrawList(NULL));
dst->CmdBuffer = CmdBuffer;
dst->IdxBuffer = IdxBuffer;
dst->VtxBuffer = VtxBuffer;
@@ -457,7 +499,7 @@ void ImDrawList::AddDrawCmd()
{
ImDrawCmd draw_cmd;
draw_cmd.ClipRect = _CmdHeader.ClipRect; // Same as calling ImDrawCmd_HeaderCopy()
- draw_cmd.TextureId = _CmdHeader.TextureId;
+ draw_cmd.TexRef = _CmdHeader.TexRef;
draw_cmd.VtxOffset = _CmdHeader.VtxOffset;
draw_cmd.IdxOffset = IdxBuffer.Size;
@@ -482,6 +524,7 @@ void ImDrawList::AddCallback(ImDrawCallback callback, void* userdata, size_t use
{
IM_ASSERT_PARANOID(CmdBuffer.Size > 0);
ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];
+ IM_ASSERT(callback != NULL);
IM_ASSERT(curr_cmd->UserCallback == NULL);
if (curr_cmd->ElemCount != 0)
{
@@ -512,10 +555,10 @@ void ImDrawList::AddCallback(ImDrawCallback callback, void* userdata, size_t use
AddDrawCmd(); // Force a new command after us (see comment below)
}
-// Compare ClipRect, TextureId and VtxOffset with a single memcmp()
+// Compare ClipRect, TexRef and VtxOffset with a single memcmp()
#define ImDrawCmd_HeaderSize (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
+#define ImDrawCmd_HeaderCompare(CMD_LHS, CMD_RHS) (memcmp(CMD_LHS, CMD_RHS, ImDrawCmd_HeaderSize)) // Compare ClipRect, TexRef, VtxOffset
+#define ImDrawCmd_HeaderCopy(CMD_DST, CMD_SRC) (memcpy(CMD_DST, CMD_SRC, ImDrawCmd_HeaderSize)) // Copy ClipRect, TexRef, VtxOffset
#define ImDrawCmd_AreSequentialIdxOffset(CMD_0, CMD_1) (CMD_0->IdxOffset + CMD_0->ElemCount == CMD_1->IdxOffset)
// Try to merge two last draw commands
@@ -555,17 +598,20 @@ void ImDrawList::_OnChangedClipRect()
curr_cmd->ClipRect = _CmdHeader.ClipRect;
}
-void ImDrawList::_OnChangedTextureID()
+void ImDrawList::_OnChangedTexture()
{
// If current command is used with different settings we need to add a new command
IM_ASSERT_PARANOID(CmdBuffer.Size > 0);
ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];
- if (curr_cmd->ElemCount != 0 && curr_cmd->TextureId != _CmdHeader.TextureId)
+ if (curr_cmd->ElemCount != 0 && curr_cmd->TexRef != _CmdHeader.TexRef)
{
AddDrawCmd();
return;
}
- IM_ASSERT(curr_cmd->UserCallback == NULL);
+
+ // Unlike other _OnChangedXXX functions this may be called by ImFontAtlasUpdateDrawListsTextures() in more locations so we need to handle this case.
+ if (curr_cmd->UserCallback != NULL)
+ return;
// Try to merge with previous command if it matches, else use current command
ImDrawCmd* prev_cmd = curr_cmd - 1;
@@ -574,7 +620,7 @@ void ImDrawList::_OnChangedTextureID()
CmdBuffer.pop_back();
return;
}
- curr_cmd->TextureId = _CmdHeader.TextureId;
+ curr_cmd->TexRef = _CmdHeader.TexRef;
}
void ImDrawList::_OnChangedVtxOffset()
@@ -635,27 +681,30 @@ void ImDrawList::PopClipRect()
_OnChangedClipRect();
}
-void ImDrawList::PushTextureID(ImTextureID texture_id)
+void ImDrawList::PushTexture(ImTextureRef tex_ref)
{
- _TextureIdStack.push_back(texture_id);
- _CmdHeader.TextureId = texture_id;
- _OnChangedTextureID();
+ _TextureStack.push_back(tex_ref);
+ _CmdHeader.TexRef = tex_ref;
+ if (tex_ref._TexData != NULL)
+ IM_ASSERT(tex_ref._TexData->WantDestroyNextFrame == false);
+ _OnChangedTexture();
}
-void ImDrawList::PopTextureID()
+void ImDrawList::PopTexture()
{
- _TextureIdStack.pop_back();
- _CmdHeader.TextureId = (_TextureIdStack.Size == 0) ? (ImTextureID)NULL : _TextureIdStack.Data[_TextureIdStack.Size - 1];
- _OnChangedTextureID();
+ _TextureStack.pop_back();
+ _CmdHeader.TexRef = (_TextureStack.Size == 0) ? ImTextureRef() : _TextureStack.Data[_TextureStack.Size - 1];
+ _OnChangedTexture();
}
-// This is used by ImGui::PushFont()/PopFont(). It works because we never use _TextureIdStack[] elsewhere than in PushTextureID()/PopTextureID().
-void ImDrawList::_SetTextureID(ImTextureID texture_id)
+// This is used by ImGui::PushFont()/PopFont(). It works because we never use _TextureIdStack[] elsewhere than in PushTexture()/PopTexture().
+void ImDrawList::_SetTexture(ImTextureRef tex_ref)
{
- if (_CmdHeader.TextureId == texture_id)
+ if (_CmdHeader.TexRef == tex_ref)
return;
- _CmdHeader.TextureId = texture_id;
- _OnChangedTextureID();
+ _CmdHeader.TexRef = tex_ref;
+ _TextureStack.back() = tex_ref;
+ _OnChangedTexture();
}
// Reserve space for a number of vertices and indices.
@@ -841,7 +890,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32
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 for the outer edges
+ // Add temporary vertices 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;
@@ -868,7 +917,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32
idx1 = idx2;
}
- // Add vertexes for each point on the line
+ // Add vertices for each point on the line
if (use_texture)
{
// If we're using textures we only need to emit the left/right edge vertices
@@ -1652,7 +1701,7 @@ void ImDrawList::AddBezierQuadratic(const ImVec2& p1, const ImVec2& p2, const Im
PathStroke(col, 0, thickness);
}
-void ImDrawList::AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end, float wrap_width, const ImVec4* cpu_fine_clip_rect)
+void ImDrawList::AddText(ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end, float wrap_width, const ImVec4* cpu_fine_clip_rect)
{
if ((col & IM_COL32_A_MASK) == 0)
return;
@@ -1660,8 +1709,7 @@ void ImDrawList::AddText(const ImFont* font, float font_size, const ImVec2& pos,
// Accept null ranges
if (text_begin == text_end || text_begin[0] == 0)
return;
- if (text_end == NULL)
- text_end = text_begin + strlen(text_begin);
+ // No need to strlen() here: font->RenderText() will do it and may early out.
// Pull default font/size from the shared ImDrawListSharedData instance
if (font == NULL)
@@ -1669,8 +1717,6 @@ 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 == _CmdHeader.TextureId); // Use high-level ImGui::PushFont() or low-level ImDrawList::PushTextureId() to change font.
-
ImVec4 clip_rect = _CmdHeader.ClipRect;
if (cpu_fine_clip_rect)
{
@@ -1679,47 +1725,47 @@ void ImDrawList::AddText(const ImFont* font, float font_size, const ImVec2& pos,
clip_rect.z = ImMin(clip_rect.z, cpu_fine_clip_rect->z);
clip_rect.w = ImMin(clip_rect.w, cpu_fine_clip_rect->w);
}
- font->RenderText(this, font_size, pos, col, clip_rect, text_begin, text_end, wrap_width, cpu_fine_clip_rect != NULL);
+ font->RenderText(this, font_size, pos, col, clip_rect, text_begin, text_end, wrap_width, (cpu_fine_clip_rect != NULL) ? ImDrawTextFlags_CpuFineClip : ImDrawTextFlags_None);
}
void ImDrawList::AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end)
{
- AddText(NULL, 0.0f, pos, col, text_begin, text_end);
+ AddText(_Data->Font, _Data->FontSize, pos, col, text_begin, text_end);
}
-void ImDrawList::AddImage(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col)
+void ImDrawList::AddImage(ImTextureRef tex_ref, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col)
{
if ((col & IM_COL32_A_MASK) == 0)
return;
- const bool push_texture_id = user_texture_id != _CmdHeader.TextureId;
+ const bool push_texture_id = tex_ref != _CmdHeader.TexRef;
if (push_texture_id)
- PushTextureID(user_texture_id);
+ PushTexture(tex_ref);
PrimReserve(6, 4);
PrimRectUV(p_min, p_max, uv_min, uv_max, col);
if (push_texture_id)
- PopTextureID();
+ PopTexture();
}
-void ImDrawList::AddImageQuad(ImTextureID user_texture_id, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& uv1, const ImVec2& uv2, const ImVec2& uv3, const ImVec2& uv4, ImU32 col)
+void ImDrawList::AddImageQuad(ImTextureRef tex_ref, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& uv1, const ImVec2& uv2, const ImVec2& uv3, const ImVec2& uv4, ImU32 col)
{
if ((col & IM_COL32_A_MASK) == 0)
return;
- const bool push_texture_id = user_texture_id != _CmdHeader.TextureId;
+ const bool push_texture_id = tex_ref != _CmdHeader.TexRef;
if (push_texture_id)
- PushTextureID(user_texture_id);
+ PushTexture(tex_ref);
PrimReserve(6, 4);
PrimQuadUV(p1, p2, p3, p4, uv1, uv2, uv3, uv4, col);
if (push_texture_id)
- PopTextureID();
+ PopTexture();
}
-void ImDrawList::AddImageRounded(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col, float rounding, ImDrawFlags flags)
+void ImDrawList::AddImageRounded(ImTextureRef tex_ref, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col, float rounding, ImDrawFlags flags)
{
if ((col & IM_COL32_A_MASK) == 0)
return;
@@ -1727,13 +1773,13 @@ void ImDrawList::AddImageRounded(ImTextureID user_texture_id, const ImVec2& p_mi
flags = FixRectCornerFlags(flags);
if (rounding < 0.5f || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone)
{
- AddImage(user_texture_id, p_min, p_max, uv_min, uv_max, col);
+ AddImage(tex_ref, p_min, p_max, uv_min, uv_max, col);
return;
}
- const bool push_texture_id = user_texture_id != _CmdHeader.TextureId;
+ const bool push_texture_id = tex_ref != _CmdHeader.TexRef;
if (push_texture_id)
- PushTextureID(user_texture_id);
+ PushTexture(tex_ref);
int vert_start_idx = VtxBuffer.Size;
PathRect(p_min, p_max, rounding, flags);
@@ -1742,7 +1788,7 @@ void ImDrawList::AddImageRounded(ImTextureID user_texture_id, const ImVec2& p_mi
ImGui::ShadeVertsLinearUV(this, vert_start_idx, vert_end_idx, p_min, p_max, uv_min, uv_max, true);
if (push_texture_id)
- PopTextureID();
+ PopTexture();
}
//-----------------------------------------------------------------------------
@@ -2170,7 +2216,7 @@ void ImDrawListSplitter::Merge(ImDrawList* draw_list)
// 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
+ ImDrawCmd_HeaderCopy(curr_cmd, &draw_list->_CmdHeader); // Copy ClipRect, TexRef, VtxOffset
else if (ImDrawCmd_HeaderCompare(curr_cmd, &draw_list->_CmdHeader) != 0)
draw_list->AddDrawCmd();
@@ -2196,7 +2242,7 @@ void ImDrawListSplitter::SetCurrentChannel(ImDrawList* draw_list, int idx)
if (curr_cmd == NULL)
draw_list->AddDrawCmd();
else if (curr_cmd->ElemCount == 0)
- ImDrawCmd_HeaderCopy(curr_cmd, &draw_list->_CmdHeader); // Copy ClipRect, TextureId, VtxOffset
+ ImDrawCmd_HeaderCopy(curr_cmd, &draw_list->_CmdHeader); // Copy ClipRect, TexRef, VtxOffset
else if (ImDrawCmd_HeaderCompare(curr_cmd, &draw_list->_CmdHeader) != 0)
draw_list->AddDrawCmd();
}
@@ -2212,6 +2258,7 @@ void ImDrawData::Clear()
CmdLists.resize(0); // The ImDrawList are NOT owned by ImDrawData but e.g. by ImGuiContext, so we don't clear them.
DisplayPos = DisplaySize = FramebufferScale = ImVec2(0.0f, 0.0f);
OwnerViewport = NULL;
+ Textures = NULL;
}
// Important: 'out_list' is generally going to be draw_data->CmdLists, but may be another temporary list
@@ -2273,17 +2320,16 @@ void ImDrawData::DeIndexAllBuffers()
{
ImVector<ImDrawVert> new_vtx_buffer;
TotalVtxCount = TotalIdxCount = 0;
- for (int i = 0; i < CmdListsCount; i++)
+ for (ImDrawList* draw_list : CmdLists)
{
- ImDrawList* cmd_list = CmdLists[i];
- if (cmd_list->IdxBuffer.empty())
+ if (draw_list->IdxBuffer.empty())
continue;
- new_vtx_buffer.resize(cmd_list->IdxBuffer.Size);
- for (int j = 0; j < cmd_list->IdxBuffer.Size; j++)
- new_vtx_buffer[j] = cmd_list->VtxBuffer[cmd_list->IdxBuffer[j]];
- cmd_list->VtxBuffer.swap(new_vtx_buffer);
- cmd_list->IdxBuffer.resize(0);
- TotalVtxCount += cmd_list->VtxBuffer.Size;
+ new_vtx_buffer.resize(draw_list->IdxBuffer.Size);
+ for (int j = 0; j < draw_list->IdxBuffer.Size; j++)
+ new_vtx_buffer[j] = draw_list->VtxBuffer[draw_list->IdxBuffer[j]];
+ draw_list->VtxBuffer.swap(new_vtx_buffer);
+ draw_list->IdxBuffer.resize(0);
+ TotalVtxCount += draw_list->VtxBuffer.Size;
}
}
@@ -2362,20 +2408,171 @@ void ImGui::ShadeVertsTransformPos(ImDrawList* draw_list, int vert_start_idx, in
// [SECTION] ImFontConfig
//-----------------------------------------------------------------------------
+// FIXME-NEWATLAS: Oversample specification could be more dynamic. For now, favoring automatic selection.
ImFontConfig::ImFontConfig()
{
memset(this, 0, sizeof(*this));
FontDataOwnedByAtlas = true;
- OversampleH = 2;
- OversampleV = 1;
+ OversampleH = 0; // Auto == 1 or 2 depending on size
+ OversampleV = 0; // Auto == 1
GlyphMaxAdvanceX = FLT_MAX;
RasterizerMultiply = 1.0f;
RasterizerDensity = 1.0f;
- EllipsisChar = (ImWchar)-1;
+ EllipsisChar = 0;
+}
+
+//-----------------------------------------------------------------------------
+// [SECTION] ImTextureData
+//-----------------------------------------------------------------------------
+// - ImTextureData::Create()
+// - ImTextureData::DestroyPixels()
+//-----------------------------------------------------------------------------
+
+int ImTextureDataGetFormatBytesPerPixel(ImTextureFormat format)
+{
+ switch (format)
+ {
+ case ImTextureFormat_Alpha8: return 1;
+ case ImTextureFormat_RGBA32: return 4;
+ }
+ IM_ASSERT(0);
+ return 0;
+}
+
+const char* ImTextureDataGetStatusName(ImTextureStatus status)
+{
+ switch (status)
+ {
+ case ImTextureStatus_OK: return "OK";
+ case ImTextureStatus_Destroyed: return "Destroyed";
+ case ImTextureStatus_WantCreate: return "WantCreate";
+ case ImTextureStatus_WantUpdates: return "WantUpdates";
+ case ImTextureStatus_WantDestroy: return "WantDestroy";
+ }
+ return "N/A";
}
+const char* ImTextureDataGetFormatName(ImTextureFormat format)
+{
+ switch (format)
+ {
+ case ImTextureFormat_Alpha8: return "Alpha8";
+ case ImTextureFormat_RGBA32: return "RGBA32";
+ }
+ return "N/A";
+}
+
+void ImTextureData::Create(ImTextureFormat format, int w, int h)
+{
+ IM_ASSERT(Status == ImTextureStatus_Destroyed);
+ DestroyPixels();
+ Format = format;
+ Status = ImTextureStatus_WantCreate;
+ Width = w;
+ Height = h;
+ BytesPerPixel = ImTextureDataGetFormatBytesPerPixel(format);
+ UseColors = false;
+ Pixels = (unsigned char*)IM_ALLOC(Width * Height * BytesPerPixel);
+ IM_ASSERT(Pixels != NULL);
+ memset(Pixels, 0, Width * Height * BytesPerPixel);
+ UsedRect.x = UsedRect.y = UsedRect.w = UsedRect.h = 0;
+ UpdateRect.x = UpdateRect.y = (unsigned short)~0;
+ UpdateRect.w = UpdateRect.h = 0;
+}
+
+void ImTextureData::DestroyPixels()
+{
+ if (Pixels)
+ IM_FREE(Pixels);
+ Pixels = NULL;
+ UseColors = false;
+}
+
+//-----------------------------------------------------------------------------
+// [SECTION] ImFontAtlas, ImFontAtlasBuilder
+//-----------------------------------------------------------------------------
+// - Default texture data encoded in ASCII
+// - ImFontAtlas()
+// - ImFontAtlas::Clear()
+// - ImFontAtlas::CompactCache()
+// - ImFontAtlas::ClearInputData()
+// - ImFontAtlas::ClearTexData()
+// - ImFontAtlas::ClearFonts()
+//-----------------------------------------------------------------------------
+// - ImFontAtlasUpdateNewFrame()
+// - ImFontAtlasTextureBlockConvert()
+// - ImFontAtlasTextureBlockPostProcess()
+// - ImFontAtlasTextureBlockPostProcessMultiply()
+// - ImFontAtlasTextureBlockFill()
+// - ImFontAtlasTextureBlockCopy()
+// - ImFontAtlasTextureBlockQueueUpload()
+//-----------------------------------------------------------------------------
+// - ImFontAtlas::GetTexDataAsAlpha8() [legacy]
+// - ImFontAtlas::GetTexDataAsRGBA32() [legacy]
+// - ImFontAtlas::Build() [legacy]
+//-----------------------------------------------------------------------------
+// - ImFontAtlas::AddFont()
+// - ImFontAtlas::AddFontDefault()
+// - ImFontAtlas::AddFontFromFileTTF()
+// - ImFontAtlas::AddFontFromMemoryTTF()
+// - ImFontAtlas::AddFontFromMemoryCompressedTTF()
+// - ImFontAtlas::AddFontFromMemoryCompressedBase85TTF()
+// - ImFontAtlas::RemoveFont()
+// - ImFontAtlasBuildNotifySetFont()
//-----------------------------------------------------------------------------
-// [SECTION] ImFontAtlas
+// - ImFontAtlas::AddCustomRect()
+// - ImFontAtlas::RemoveCustomRect()
+// - ImFontAtlas::GetCustomRect()
+// - ImFontAtlas::AddCustomRectFontGlyph() [legacy]
+// - ImFontAtlas::AddCustomRectFontGlyphForSize() [legacy]
+// - ImFontAtlasGetMouseCursorTexData()
+//-----------------------------------------------------------------------------
+// - ImFontAtlasBuildMain()
+// - ImFontAtlasBuildSetupFontLoader()
+// - ImFontAtlasBuildPreloadAllGlyphRanges()
+// - ImFontAtlasBuildUpdatePointers()
+// - ImFontAtlasBuildRenderBitmapFromString()
+// - ImFontAtlasBuildUpdateBasicTexData()
+// - ImFontAtlasBuildUpdateLinesTexData()
+// - ImFontAtlasBuildAddFont()
+// - ImFontAtlasBuildSetupFontBakedEllipsis()
+// - ImFontAtlasBuildSetupFontBakedBlanks()
+// - ImFontAtlasBuildSetupFontBakedFallback()
+// - ImFontAtlasBuildSetupFontSpecialGlyphs()
+// - ImFontAtlasBuildDiscardBakes()
+// - ImFontAtlasBuildDiscardFontBakedGlyph()
+// - ImFontAtlasBuildDiscardFontBaked()
+// - ImFontAtlasBuildDiscardFontBakes()
+//-----------------------------------------------------------------------------
+// - ImFontAtlasAddDrawListSharedData()
+// - ImFontAtlasRemoveDrawListSharedData()
+// - ImFontAtlasUpdateDrawListsTextures()
+// - ImFontAtlasUpdateDrawListsSharedData()
+//-----------------------------------------------------------------------------
+// - ImFontAtlasBuildSetTexture()
+// - ImFontAtlasBuildAddTexture()
+// - ImFontAtlasBuildMakeSpace()
+// - ImFontAtlasBuildRepackTexture()
+// - ImFontAtlasBuildGrowTexture()
+// - ImFontAtlasBuildRepackOrGrowTexture()
+// - ImFontAtlasBuildGetTextureSizeEstimate()
+// - ImFontAtlasBuildCompactTexture()
+// - ImFontAtlasBuildInit()
+// - ImFontAtlasBuildDestroy()
+//-----------------------------------------------------------------------------
+// - ImFontAtlasPackInit()
+// - ImFontAtlasPackAllocRectEntry()
+// - ImFontAtlasPackReuseRectEntry()
+// - ImFontAtlasPackDiscardRect()
+// - ImFontAtlasPackAddRect()
+// - ImFontAtlasPackGetRect()
+//-----------------------------------------------------------------------------
+// - ImFontBaked_BuildGrowIndex()
+// - ImFontBaked_BuildLoadGlyph()
+// - ImFontBaked_BuildLoadGlyphAdvanceX()
+// - ImFontAtlasDebugLogTextureRequests()
+//-----------------------------------------------------------------------------
+// - ImFontAtlasGetFontLoaderForStbTruetype()
//-----------------------------------------------------------------------------
// A work of art lies ahead! (. = white layer, X = black layer, others are blank)
@@ -2425,147 +2622,472 @@ static const ImVec2 FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[ImGuiMouseCursor_COUNT][3
{ ImVec2(73,0), ImVec2(17,17), ImVec2( 8, 8) }, // ImGuiMouseCursor_ResizeNESW
{ ImVec2(55,0), ImVec2(17,17), ImVec2( 8, 8) }, // ImGuiMouseCursor_ResizeNWSE
{ ImVec2(91,0), ImVec2(17,22), ImVec2( 5, 0) }, // ImGuiMouseCursor_Hand
+ { ImVec2(0,3), ImVec2(12,19), ImVec2(0, 0) }, // ImGuiMouseCursor_Wait // Arrow + custom code in ImGui::RenderMouseCursor()
+ { ImVec2(0,3), ImVec2(12,19), ImVec2(0, 0) }, // ImGuiMouseCursor_Progress // Arrow + custom code in ImGui::RenderMouseCursor()
{ ImVec2(109,0),ImVec2(13,15), ImVec2( 6, 7) }, // ImGuiMouseCursor_NotAllowed
};
+#define IM_FONTGLYPH_INDEX_UNUSED ((ImU16)-1) // 0xFFFF
+#define IM_FONTGLYPH_INDEX_NOT_FOUND ((ImU16)-2) // 0xFFFE
+
ImFontAtlas::ImFontAtlas()
{
memset(this, 0, sizeof(*this));
+ TexDesiredFormat = ImTextureFormat_RGBA32;
TexGlyphPadding = 1;
- PackIdMouseCursors = PackIdLines = -1;
+ TexMinWidth = 512;
+ TexMinHeight = 128;
+ TexMaxWidth = 8192;
+ TexMaxHeight = 8192;
+ TexRef._TexID = ImTextureID_Invalid;
+ RendererHasTextures = false; // Assumed false by default, as apps can call e.g Atlas::Build() after backend init and before ImGui can update.
+ TexNextUniqueID = 1;
+ FontNextUniqueID = 1;
+ Builder = NULL;
}
ImFontAtlas::~ImFontAtlas()
{
- IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!");
- Clear();
+ IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!");
+ RendererHasTextures = false; // Full Clear() is supported, but ClearTexData() only isn't.
+ ClearFonts();
+ ClearTexData();
+ TexList.clear_delete();
+ TexData = NULL;
+}
+
+void ImFontAtlas::Clear()
+{
+ bool backup_renderer_has_textures = RendererHasTextures;
+ RendererHasTextures = false; // Full Clear() is supported, but ClearTexData() only isn't.
+ ClearFonts();
+ ClearTexData();
+ RendererHasTextures = backup_renderer_has_textures;
}
-void ImFontAtlas::ClearInputData()
+void ImFontAtlas::CompactCache()
{
- IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!");
- for (ImFontConfig& font_cfg : ConfigData)
- if (font_cfg.FontData && font_cfg.FontDataOwnedByAtlas)
- {
- IM_FREE(font_cfg.FontData);
- font_cfg.FontData = NULL;
- }
+ ImFontAtlasTextureCompact(this);
+}
+
+void ImFontAtlas::SetFontLoader(const ImFontLoader* font_loader)
+{
+ ImFontAtlasBuildSetupFontLoader(this, font_loader);
+}
+
+void ImFontAtlas::ClearInputData()
+{
+ IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!");
- // When clearing this we lose access to the font name and other information used to build the font.
for (ImFont* font : Fonts)
- if (font->ConfigData >= ConfigData.Data && font->ConfigData < ConfigData.Data + ConfigData.Size)
+ ImFontAtlasFontDestroyOutput(this, font);
+ for (ImFontConfig& font_cfg : Sources)
+ ImFontAtlasFontDestroySourceData(this, &font_cfg);
+ for (ImFont* font : Fonts)
+ {
+ // When clearing this we lose access to the font name and other information used to build the font.
+ font->Sources.clear();
+ font->Flags |= ImFontFlags_NoLoadGlyphs;
+ }
+ Sources.clear();
+}
+
+// Clear CPU-side copy of the texture data.
+void ImFontAtlas::ClearTexData()
+{
+ IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!");
+ IM_ASSERT(RendererHasTextures == false && "Not supported for dynamic atlases, but you may call Clear().");
+ for (ImTextureData* tex : TexList)
+ tex->DestroyPixels();
+ //Locked = true; // Hoped to be able to lock this down but some reload patterns may not be happy with it.
+}
+
+void ImFontAtlas::ClearFonts()
+{
+ // FIXME-NEWATLAS: Illegal to remove currently bound font.
+ IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!");
+ ImFontAtlasBuildDestroy(this);
+ ClearInputData();
+ Fonts.clear_delete();
+ TexIsBuilt = false;
+ for (ImDrawListSharedData* shared_data : DrawListSharedDatas)
+ if (shared_data->FontAtlas == this)
{
- font->ConfigData = NULL;
- font->ConfigDataCount = 0;
+ shared_data->Font = NULL;
+ shared_data->FontScale = shared_data->FontSize = 0.0f;
}
- ConfigData.clear();
- CustomRects.clear();
- PackIdMouseCursors = PackIdLines = -1;
- // Important: we leave TexReady untouched
}
-void ImFontAtlas::ClearTexData()
+static void ImFontAtlasBuildUpdateRendererHasTexturesFromContext(ImFontAtlas* atlas)
{
- IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!");
- if (TexPixelsAlpha8)
- IM_FREE(TexPixelsAlpha8);
- if (TexPixelsRGBA32)
- IM_FREE(TexPixelsRGBA32);
- TexPixelsAlpha8 = NULL;
- TexPixelsRGBA32 = NULL;
- TexPixelsUseColors = false;
- // Important: we leave TexReady untouched
+ // [LEGACY] Copy back the ImGuiBackendFlags_RendererHasTextures flag from ImGui context.
+ // - This is the 1% exceptional case where that dependency if useful, to bypass an issue where otherwise at the
+ // time of an early call to Build(), it would be impossible for us to tell if the backend supports texture update.
+ // - Without this hack, we would have quite a pitfall as many legacy codebases have an early call to Build().
+ // Whereas conversely, the portion of people using ImDrawList without ImGui is expected to be pathologically rare.
+ for (ImDrawListSharedData* shared_data : atlas->DrawListSharedDatas)
+ if (ImGuiContext* imgui_ctx = shared_data->Context)
+ {
+ atlas->RendererHasTextures = (imgui_ctx->IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) != 0;
+ break;
+ }
}
-void ImFontAtlas::ClearFonts()
+// Called by NewFrame() for atlases owned by a context.
+// If you manually manage font atlases, you'll need to call this yourself.
+// - 'frame_count' needs to be provided because we can gc/prioritize baked fonts based on their age.
+// - 'frame_count' may not match those of all imgui contexts using this atlas, as contexts may be updated as different frequencies. But generally you can use ImGui::GetFrameCount() on one of your context.
+void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas, int frame_count, bool renderer_has_textures)
{
- IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!");
- Fonts.clear_delete();
- TexReady = false;
+ IM_ASSERT(atlas->Builder == NULL || atlas->Builder->FrameCount < frame_count); // Protection against being called twice.
+ atlas->RendererHasTextures = renderer_has_textures;
+
+ // Check that font atlas was built or backend support texture reload in which case we can build now
+ if (atlas->RendererHasTextures)
+ {
+ atlas->TexIsBuilt = true;
+ if (atlas->Builder == NULL) // This will only happen if fonts were not already loaded.
+ ImFontAtlasBuildMain(atlas);
+ }
+ // Legacy backend
+ if (!atlas->RendererHasTextures)
+ IM_ASSERT_USER_ERROR(atlas->TexIsBuilt, "Backend does not support ImGuiBackendFlags_RendererHasTextures, and font atlas is not built! Update backend OR make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8().");
+ if (atlas->TexIsBuilt && atlas->Builder->PreloadedAllGlyphsRanges)
+ IM_ASSERT_USER_ERROR(atlas->RendererHasTextures == false, "Called ImFontAtlas::Build() before ImGuiBackendFlags_RendererHasTextures got set! With new backends: you don't need to call Build().");
+
+ // Clear BakedCurrent cache, this is important because it ensure the uncached path gets taken once.
+ // We also rely on ImFontBaked* pointers never crossing frames.
+ ImFontAtlasBuilder* builder = atlas->Builder;
+ builder->FrameCount = frame_count;
+ for (ImFont* font : atlas->Fonts)
+ font->LastBaked = NULL;
+
+ // Garbage collect BakedPool
+ if (builder->BakedDiscardedCount > 0)
+ {
+ int dst_n = 0, src_n = 0;
+ for (; src_n < builder->BakedPool.Size; src_n++)
+ {
+ ImFontBaked* p_src = &builder->BakedPool[src_n];
+ if (p_src->WantDestroy)
+ continue;
+ ImFontBaked* p_dst = &builder->BakedPool[dst_n++];
+ if (p_dst == p_src)
+ continue;
+ memcpy(p_dst, p_src, sizeof(ImFontBaked));
+ builder->BakedMap.SetVoidPtr(p_dst->BakedId, p_dst);
+ }
+ IM_ASSERT(dst_n + builder->BakedDiscardedCount == src_n);
+ builder->BakedPool.Size -= builder->BakedDiscardedCount;
+ builder->BakedDiscardedCount = 0;
+ }
+
+ // Update texture status
+ for (int tex_n = 0; tex_n < atlas->TexList.Size; tex_n++)
+ {
+ ImTextureData* tex = atlas->TexList[tex_n];
+ bool remove_from_list = false;
+ if (tex->Status == ImTextureStatus_OK)
+ {
+ tex->Updates.resize(0);
+ tex->UpdateRect.x = tex->UpdateRect.y = (unsigned short)~0;
+ tex->UpdateRect.w = tex->UpdateRect.h = 0;
+ }
+ if (tex->Status == ImTextureStatus_WantCreate && atlas->RendererHasTextures)
+ IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == NULL && "Backend set texture's TexID/BackendUserData but did not update Status to OK.");
+
+ if (tex->Status == ImTextureStatus_Destroyed)
+ {
+ IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == NULL && "Backend set texture Status to Destroyed but did not clear TexID/BackendUserData!");
+ if (tex->WantDestroyNextFrame)
+ remove_from_list = true; // Destroy was scheduled by us
+ else
+ tex->Status = ImTextureStatus_WantCreate; // Destroy was done was backend (e.g. freed resources mid-run)
+ }
+ else if (tex->WantDestroyNextFrame && tex->Status != ImTextureStatus_WantDestroy)
+ {
+ // Request destroy.
+ // - Keep bool to true in order to differentiate a planned destroy vs a destroy decided by the backend.
+ // - We don't destroy pixels right away, as backend may have an in-flight copy from RAM.
+ IM_ASSERT(tex->Status == ImTextureStatus_OK || tex->Status == ImTextureStatus_WantCreate || tex->Status == ImTextureStatus_WantUpdates);
+ tex->Status = ImTextureStatus_WantDestroy;
+ }
+
+ // The backend may need defer destroying by a few frames, to handle texture used by previous in-flight rendering.
+ // We allow the texture staying in _WantDestroy state and increment a counter which the backend can use to take its decision.
+ if (tex->Status == ImTextureStatus_WantDestroy)
+ tex->UnusedFrames++;
+
+ // If a texture has never reached the backend, they don't need to know about it.
+ if (tex->Status == ImTextureStatus_WantDestroy && tex->TexID == ImTextureID_Invalid && tex->BackendUserData == NULL)
+ remove_from_list = true;
+
+ // Destroy and remove
+ if (remove_from_list)
+ {
+ tex->DestroyPixels();
+ IM_DELETE(tex);
+ atlas->TexList.erase(atlas->TexList.begin() + tex_n);
+ tex_n--;
+ }
+ }
}
-void ImFontAtlas::Clear()
+void ImFontAtlasTextureBlockConvert(const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch, unsigned char* dst_pixels, ImTextureFormat dst_fmt, int dst_pitch, int w, int h)
{
- ClearInputData();
- ClearTexData();
- ClearFonts();
+ IM_ASSERT(src_pixels != NULL && dst_pixels != NULL);
+ if (src_fmt == dst_fmt)
+ {
+ int line_sz = w * ImTextureDataGetFormatBytesPerPixel(src_fmt);
+ for (int ny = h; ny > 0; ny--, src_pixels += src_pitch, dst_pixels += dst_pitch)
+ memcpy(dst_pixels, src_pixels, line_sz);
+ }
+ else if (src_fmt == ImTextureFormat_Alpha8 && dst_fmt == ImTextureFormat_RGBA32)
+ {
+ for (int ny = h; ny > 0; ny--, src_pixels += src_pitch, dst_pixels += dst_pitch)
+ {
+ const ImU8* src_p = (const ImU8*)src_pixels;
+ ImU32* dst_p = (ImU32*)(void*)dst_pixels;
+ for (int nx = w; nx > 0; nx--)
+ *dst_p++ = IM_COL32(255, 255, 255, (unsigned int)(*src_p++));
+ }
+ }
+ else if (src_fmt == ImTextureFormat_RGBA32 && dst_fmt == ImTextureFormat_Alpha8)
+ {
+ for (int ny = h; ny > 0; ny--, src_pixels += src_pitch, dst_pixels += dst_pitch)
+ {
+ const ImU32* src_p = (const ImU32*)(void*)src_pixels;
+ ImU8* dst_p = (ImU8*)dst_pixels;
+ for (int nx = w; nx > 0; nx--)
+ *dst_p++ = ((*src_p++) >> IM_COL32_A_SHIFT) & 0xFF;
+ }
+ }
+ else
+ {
+ IM_ASSERT(0);
+ }
}
-void ImFontAtlas::GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel)
+// Source buffer may be written to (used for in-place mods).
+// Post-process hooks may eventually be added here.
+void ImFontAtlasTextureBlockPostProcess(ImFontAtlasPostProcessData* data)
{
- // Build atlas on demand
- if (TexPixelsAlpha8 == NULL)
- Build();
+ // Multiply operator (legacy)
+ if (data->FontSrc->RasterizerMultiply != 1.0f)
+ ImFontAtlasTextureBlockPostProcessMultiply(data, data->FontSrc->RasterizerMultiply);
+}
- *out_pixels = TexPixelsAlpha8;
- if (out_width) *out_width = TexWidth;
- if (out_height) *out_height = TexHeight;
- if (out_bytes_per_pixel) *out_bytes_per_pixel = 1;
+void ImFontAtlasTextureBlockPostProcessMultiply(ImFontAtlasPostProcessData* data, float multiply_factor)
+{
+ unsigned char* pixels = (unsigned char*)data->Pixels;
+ int pitch = data->Pitch;
+ if (data->Format == ImTextureFormat_Alpha8)
+ {
+ for (int ny = data->Height; ny > 0; ny--, pixels += pitch)
+ {
+ ImU8* p = (ImU8*)pixels;
+ for (int nx = data->Width; nx > 0; nx--, p++)
+ {
+ unsigned int v = ImMin((unsigned int)(*p * multiply_factor), (unsigned int)255);
+ *p = (unsigned char)v;
+ }
+ }
+ }
+ else if (data->Format == ImTextureFormat_RGBA32) //-V547
+ {
+ for (int ny = data->Height; ny > 0; ny--, pixels += pitch)
+ {
+ ImU32* p = (ImU32*)(void*)pixels;
+ for (int nx = data->Width; nx > 0; nx--, p++)
+ {
+ unsigned int a = ImMin((unsigned int)(((*p >> IM_COL32_A_SHIFT) & 0xFF) * multiply_factor), (unsigned int)255);
+ *p = IM_COL32((*p >> IM_COL32_R_SHIFT) & 0xFF, (*p >> IM_COL32_G_SHIFT) & 0xFF, (*p >> IM_COL32_B_SHIFT) & 0xFF, a);
+ }
+ }
+ }
+ else
+ {
+ IM_ASSERT(0);
+ }
}
-void ImFontAtlas::GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel)
+// Fill with single color. We don't use this directly but it is convenient for anyone working on uploading custom rects.
+void ImFontAtlasTextureBlockFill(ImTextureData* dst_tex, int dst_x, int dst_y, int w, int h, ImU32 col)
{
- // Convert to RGBA32 format on demand
- // Although it is likely to be the most commonly used format, our font rendering is 1 channel / 8 bpp
- if (!TexPixelsRGBA32)
+ if (dst_tex->Format == ImTextureFormat_Alpha8)
+ {
+ ImU8 col_a = (col >> IM_COL32_A_SHIFT) & 0xFF;
+ for (int y = 0; y < h; y++)
+ memset((ImU8*)dst_tex->GetPixelsAt(dst_x, dst_y + y), col_a, w);
+ }
+ else
{
- unsigned char* pixels = NULL;
- GetTexDataAsAlpha8(&pixels, NULL, NULL);
- if (pixels)
+ for (int y = 0; y < h; y++)
{
- TexPixelsRGBA32 = (unsigned int*)IM_ALLOC((size_t)TexWidth * (size_t)TexHeight * 4);
- const unsigned char* src = pixels;
- unsigned int* dst = TexPixelsRGBA32;
- for (int n = TexWidth * TexHeight; n > 0; n--)
- *dst++ = IM_COL32(255, 255, 255, (unsigned int)(*src++));
+ ImU32* p = (ImU32*)(void*)dst_tex->GetPixelsAt(dst_x, dst_y + y);
+ for (int x = w; x > 0; x--, p++)
+ *p = col;
}
}
+}
+
+// Copy block from one texture to another
+void ImFontAtlasTextureBlockCopy(ImTextureData* src_tex, int src_x, int src_y, ImTextureData* dst_tex, int dst_x, int dst_y, int w, int h)
+{
+ IM_ASSERT(src_tex->Pixels != NULL && dst_tex->Pixels != NULL);
+ IM_ASSERT(src_tex->Format == dst_tex->Format);
+ IM_ASSERT(src_x >= 0 && src_x + w <= src_tex->Width);
+ IM_ASSERT(src_y >= 0 && src_y + h <= src_tex->Height);
+ IM_ASSERT(dst_x >= 0 && dst_x + w <= dst_tex->Width);
+ IM_ASSERT(dst_y >= 0 && dst_y + h <= dst_tex->Height);
+ for (int y = 0; y < h; y++)
+ memcpy(dst_tex->GetPixelsAt(dst_x, dst_y + y), src_tex->GetPixelsAt(src_x, src_y + y), w * dst_tex->BytesPerPixel);
+}
+
+// Queue texture block update for renderer backend
+void ImFontAtlasTextureBlockQueueUpload(ImFontAtlas* atlas, ImTextureData* tex, int x, int y, int w, int h)
+{
+ IM_ASSERT(tex->Status != ImTextureStatus_WantDestroy && tex->Status != ImTextureStatus_Destroyed);
+ IM_ASSERT(x >= 0 && x <= 0xFFFF && y >= 0 && y <= 0xFFFF && w >= 0 && x + w <= 0x10000 && h >= 0 && y + h <= 0x10000);
+ IM_UNUSED(atlas);
+
+ ImTextureRect req = { (unsigned short)x, (unsigned short)y, (unsigned short)w, (unsigned short)h };
+ int new_x1 = ImMax(tex->UpdateRect.w == 0 ? 0 : tex->UpdateRect.x + tex->UpdateRect.w, req.x + req.w);
+ int new_y1 = ImMax(tex->UpdateRect.h == 0 ? 0 : tex->UpdateRect.y + tex->UpdateRect.h, req.y + req.h);
+ tex->UpdateRect.x = ImMin(tex->UpdateRect.x, req.x);
+ tex->UpdateRect.y = ImMin(tex->UpdateRect.y, req.y);
+ tex->UpdateRect.w = (unsigned short)(new_x1 - tex->UpdateRect.x);
+ tex->UpdateRect.h = (unsigned short)(new_y1 - tex->UpdateRect.y);
+ tex->UsedRect.x = ImMin(tex->UsedRect.x, req.x);
+ tex->UsedRect.y = ImMin(tex->UsedRect.y, req.y);
+ tex->UsedRect.w = (unsigned short)(ImMax(tex->UsedRect.x + tex->UsedRect.w, req.x + req.w) - tex->UsedRect.x);
+ tex->UsedRect.h = (unsigned short)(ImMax(tex->UsedRect.y + tex->UsedRect.h, req.y + req.h) - tex->UsedRect.y);
+ atlas->TexIsBuilt = false;
+
+ // No need to queue if status is == ImTextureStatus_WantCreate
+ if (tex->Status == ImTextureStatus_OK || tex->Status == ImTextureStatus_WantUpdates)
+ {
+ tex->Status = ImTextureStatus_WantUpdates;
+ tex->Updates.push_back(req);
+ }
+}
+
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+static void GetTexDataAsFormat(ImFontAtlas* atlas, ImTextureFormat format, unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel)
+{
+ ImTextureData* tex = atlas->TexData;
+ if (!atlas->TexIsBuilt || tex == NULL || tex->Pixels == NULL || atlas->TexDesiredFormat != format)
+ {
+ atlas->TexDesiredFormat = format;
+ atlas->Build();
+ tex = atlas->TexData;
+ }
+ if (out_pixels) { *out_pixels = (unsigned char*)tex->Pixels; };
+ if (out_width) { *out_width = tex->Width; };
+ if (out_height) { *out_height = tex->Height; };
+ if (out_bytes_per_pixel) { *out_bytes_per_pixel = tex->BytesPerPixel; }
+}
+
+void ImFontAtlas::GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel)
+{
+ GetTexDataAsFormat(this, ImTextureFormat_Alpha8, out_pixels, out_width, out_height, out_bytes_per_pixel);
+}
- *out_pixels = (unsigned char*)TexPixelsRGBA32;
- if (out_width) *out_width = TexWidth;
- if (out_height) *out_height = TexHeight;
- if (out_bytes_per_pixel) *out_bytes_per_pixel = 4;
+void ImFontAtlas::GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel)
+{
+ GetTexDataAsFormat(this, ImTextureFormat_RGBA32, out_pixels, out_width, out_height, out_bytes_per_pixel);
+}
+
+bool ImFontAtlas::Build()
+{
+ ImFontAtlasBuildMain(this);
+ return true;
}
+#endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
-ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg)
+ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg_in)
{
- IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!");
- IM_ASSERT(font_cfg->FontData != NULL && font_cfg->FontDataSize > 0);
- IM_ASSERT(font_cfg->SizePixels > 0.0f && "Is ImFontConfig struct correctly initialized?");
- IM_ASSERT(font_cfg->OversampleH > 0 && font_cfg->OversampleV > 0 && "Is ImFontConfig struct correctly initialized?");
+ // Sanity Checks
+ IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!");
+ IM_ASSERT((font_cfg_in->FontData != NULL && font_cfg_in->FontDataSize > 0) || (font_cfg_in->FontLoader != NULL));
+ //IM_ASSERT(font_cfg_in->SizePixels > 0.0f && "Is ImFontConfig struct correctly initialized?");
+ IM_ASSERT(font_cfg_in->RasterizerDensity > 0.0f && "Is ImFontConfig struct correctly initialized?");
+ if (font_cfg_in->GlyphOffset.x != 0.0f || font_cfg_in->GlyphOffset.y != 0.0f || font_cfg_in->GlyphMinAdvanceX != 0.0f || font_cfg_in->GlyphMaxAdvanceX != FLT_MAX)
+ IM_ASSERT(font_cfg_in->SizePixels != 0.0f && "Specifying glyph offset/advances requires a reference size to base it on.");
+
+ // Lazily create builder on the first call to AddFont
+ if (Builder == NULL)
+ ImFontAtlasBuildInit(this);
// Create new font
- if (!font_cfg->MergeMode)
- Fonts.push_back(IM_NEW(ImFont));
+ ImFont* font;
+ if (!font_cfg_in->MergeMode)
+ {
+ font = IM_NEW(ImFont)();
+ font->FontId = FontNextUniqueID++;
+ font->Flags = font_cfg_in->Flags;
+ font->LegacySize = font_cfg_in->SizePixels;
+ font->CurrentRasterizerDensity = font_cfg_in->RasterizerDensity;
+ Fonts.push_back(font);
+ }
else
+ {
IM_ASSERT(Fonts.Size > 0 && "Cannot use MergeMode for the first font"); // When using MergeMode make sure that a font has already been added before. You can use ImGui::GetIO().Fonts->AddFontDefault() to add the default imgui font.
+ font = font_cfg_in->DstFont ? font_cfg_in->DstFont : Fonts.back();
+ }
- ConfigData.push_back(*font_cfg);
- ImFontConfig& new_font_cfg = ConfigData.back();
- if (new_font_cfg.DstFont == NULL)
- new_font_cfg.DstFont = Fonts.back();
- if (!new_font_cfg.FontDataOwnedByAtlas)
+ // Add to list
+ Sources.push_back(*font_cfg_in);
+ ImFontConfig* font_cfg = &Sources.back();
+ if (font_cfg->DstFont == NULL)
+ font_cfg->DstFont = font;
+ font->Sources.push_back(font_cfg);
+ ImFontAtlasBuildUpdatePointers(this); // Pointers to Sources are otherwise dangling after we called Sources.push_back().
+
+ if (font_cfg->FontDataOwnedByAtlas == false)
{
- new_font_cfg.FontData = IM_ALLOC(new_font_cfg.FontDataSize);
- new_font_cfg.FontDataOwnedByAtlas = true;
- memcpy(new_font_cfg.FontData, font_cfg->FontData, (size_t)new_font_cfg.FontDataSize);
+ font_cfg->FontDataOwnedByAtlas = true;
+ font_cfg->FontData = ImMemdup(font_cfg->FontData, (size_t)font_cfg->FontDataSize);
}
- if (new_font_cfg.DstFont->EllipsisChar == (ImWchar)-1)
- new_font_cfg.DstFont->EllipsisChar = font_cfg->EllipsisChar;
+ // Sanity check
+ // We don't round cfg.SizePixels yet as relative size of merged fonts are used afterwards.
+ if (font_cfg->GlyphExcludeRanges != NULL)
+ {
+ int size = 0;
+ for (const ImWchar* p = font_cfg->GlyphExcludeRanges; p[0] != 0; p++, size++) {}
+ IM_ASSERT((size & 1) == 0 && "GlyphExcludeRanges[] size must be multiple of two!");
+ IM_ASSERT((size <= 64) && "GlyphExcludeRanges[] size must be small!");
+ font_cfg->GlyphExcludeRanges = (ImWchar*)ImMemdup(font_cfg->GlyphExcludeRanges, sizeof(font_cfg->GlyphExcludeRanges[0]) * (size + 1));
+ }
+ if (font_cfg->FontLoader != NULL)
+ {
+ IM_ASSERT(font_cfg->FontLoader->FontBakedLoadGlyph != NULL);
+ IM_ASSERT(font_cfg->FontLoader->LoaderInit == NULL && font_cfg->FontLoader->LoaderShutdown == NULL); // FIXME-NEWATLAS: Unsupported yet.
+ }
+ IM_ASSERT(font_cfg->FontLoaderData == NULL);
- ImFontAtlasUpdateConfigDataPointers(this);
+ if (!ImFontAtlasFontSourceInit(this, font_cfg))
+ {
+ // Rollback (this is a fragile/rarely exercised code-path. TestSuite's "misc_atlas_add_invalid_font" aim to test this)
+ ImFontAtlasFontDestroySourceData(this, font_cfg);
+ Sources.pop_back();
+ font->Sources.pop_back();
+ if (!font_cfg->MergeMode)
+ {
+ IM_DELETE(font);
+ Fonts.pop_back();
+ }
+ return NULL;
+ }
+ ImFontAtlasFontSourceAddToFont(this, font, font_cfg);
- // Invalidate texture
- TexReady = false;
- ClearTexData();
- return new_font_cfg.DstFont;
+ return font;
}
// Default font TTF is compressed with stb_compress then base85 encoded (see misc/fonts/binary_to_compressed_c.cpp for encoder)
static unsigned int stb_decompress_length(const unsigned char* input);
static unsigned int stb_decompress(unsigned char* output, const unsigned char* input, unsigned int length);
-static const char* GetDefaultCompressedFontDataTTFBase85();
static unsigned int Decode85Byte(char c) { return c >= '\\' ? c-36 : c-35; }
static void Decode85(const unsigned char* src, unsigned char* dst)
{
@@ -2577,10 +3099,15 @@ static void Decode85(const unsigned char* src, unsigned char* dst)
dst += 4;
}
}
+#ifndef IMGUI_DISABLE_DEFAULT_FONT
+static const char* GetDefaultCompressedFontDataTTF(int* out_size);
+#endif
// Load embedded ProggyClean.ttf at size 13, disable oversampling
+// If you want a similar font which may be better scaled, consider using ProggyVector from the same author!
ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template)
{
+#ifndef IMGUI_DISABLE_DEFAULT_FONT
ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig();
if (!font_cfg_template)
{
@@ -2590,24 +3117,32 @@ ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template)
if (font_cfg.SizePixels <= 0.0f)
font_cfg.SizePixels = 13.0f * 1.0f;
if (font_cfg.Name[0] == '\0')
- ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "ProggyClean.ttf, %dpx", (int)font_cfg.SizePixels);
+ ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "ProggyClean.ttf");
font_cfg.EllipsisChar = (ImWchar)0x0085;
- font_cfg.GlyphOffset.y = 1.0f * IM_TRUNC(font_cfg.SizePixels / 13.0f); // Add +1 offset per 13 units
+ font_cfg.GlyphOffset.y += 1.0f * IM_TRUNC(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);
- return font;
+ int ttf_compressed_size = 0;
+ const char* ttf_compressed = GetDefaultCompressedFontDataTTF(&ttf_compressed_size);
+ return AddFontFromMemoryCompressedTTF(ttf_compressed, ttf_compressed_size, font_cfg.SizePixels, &font_cfg);
+#else
+ IM_ASSERT(0 && "AddFontDefault() disabled in this build.");
+ IM_UNUSED(font_cfg_template);
+ return NULL;
+#endif // #ifndef IMGUI_DISABLE_DEFAULT_FONT
}
ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges)
{
- IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!");
+ IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!");
size_t data_size = 0;
void* data = ImFileLoadToMemory(filename, "rb", &data_size, 0);
if (!data)
{
- IM_ASSERT_USER_ERROR(0, "Could not load font file!");
+ if (font_cfg_template == NULL || (font_cfg_template->Flags & ImFontFlags_NoLoadError) == 0)
+ {
+ IMGUI_DEBUG_LOG("While loading '%s'\n", filename);
+ IM_ASSERT_USER_ERROR(0, "Could not load font file!");
+ }
return NULL;
}
ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig();
@@ -2615,8 +3150,8 @@ ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels,
{
// Store a short copy of filename into into the font name for convenience
const char* p;
- for (p = filename + strlen(filename); p > filename && p[-1] != '/' && p[-1] != '\\'; p--) {}
- ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "%s, %.0fpx", p, size_pixels);
+ for (p = filename + ImStrlen(filename); p > filename && p[-1] != '/' && p[-1] != '\\'; p--) {}
+ ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "%s", p);
}
return AddFontFromMemoryTTF(data, (int)data_size, size_pixels, &font_cfg, glyph_ranges);
}
@@ -2624,7 +3159,7 @@ ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels,
// NB: Transfer ownership of 'ttf_data' to ImFontAtlas, unless font_cfg_template->FontDataOwnedByAtlas == false. Owned TTF buffer will be deleted after Build().
ImFont* ImFontAtlas::AddFontFromMemoryTTF(void* font_data, int font_data_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges)
{
- IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!");
+ IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!");
ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig();
IM_ASSERT(font_cfg.FontData == NULL);
IM_ASSERT(font_data_size > 100 && "Incorrect value for font_data_size!"); // Heuristic to prevent accidentally passing a wrong value to font_data_size.
@@ -2650,7 +3185,7 @@ ImFont* ImFontAtlas::AddFontFromMemoryCompressedTTF(const void* compressed_ttf_d
ImFont* ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char* compressed_ttf_data_base85, float size_pixels, const ImFontConfig* font_cfg, const ImWchar* glyph_ranges)
{
- int compressed_ttf_size = (((int)strlen(compressed_ttf_data_base85) + 4) / 5) * 4;
+ int compressed_ttf_size = (((int)ImStrlen(compressed_ttf_data_base85) + 4) / 5) * 4;
void* compressed_ttf = IM_ALLOC((size_t)compressed_ttf_size);
Decode85((const unsigned char*)compressed_ttf_data_base85, (unsigned char*)compressed_ttf);
ImFont* font = AddFontFromMemoryCompressedTTF(compressed_ttf, compressed_ttf_size, size_pixels, font_cfg, glyph_ranges);
@@ -2658,649 +3193,1565 @@ ImFont* ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char* compressed
return font;
}
-int ImFontAtlas::AddCustomRectRegular(int width, int height)
+// On font removal we need to remove references (otherwise we could queue removal?)
+// We allow old_font == new_font which forces updating all values (e.g. sizes)
+static void ImFontAtlasBuildNotifySetFont(ImFontAtlas* atlas, ImFont* old_font, ImFont* new_font)
+{
+ for (ImDrawListSharedData* shared_data : atlas->DrawListSharedDatas)
+ {
+ if (shared_data->Font == old_font)
+ shared_data->Font = new_font;
+ if (ImGuiContext* ctx = shared_data->Context)
+ {
+ if (ctx->IO.FontDefault == old_font)
+ ctx->IO.FontDefault = new_font;
+ if (ctx->Font == old_font)
+ {
+ ImGuiContext* curr_ctx = ImGui::GetCurrentContext();
+ bool need_bind_ctx = ctx != curr_ctx;
+ if (need_bind_ctx)
+ ImGui::SetCurrentContext(ctx);
+ ImGui::SetCurrentFont(new_font, ctx->FontSizeBase, ctx->FontSize);
+ if (need_bind_ctx)
+ ImGui::SetCurrentContext(curr_ctx);
+ }
+ for (ImFontStackData& font_stack_data : ctx->FontStack)
+ if (font_stack_data.Font == old_font)
+ font_stack_data.Font = new_font;
+ }
+ }
+}
+
+void ImFontAtlas::RemoveFont(ImFont* font)
+{
+ IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!");
+ font->ClearOutputData();
+
+ ImFontAtlasFontDestroyOutput(this, font);
+ for (ImFontConfig* src : font->Sources)
+ ImFontAtlasFontDestroySourceData(this, src);
+ for (int src_n = 0; src_n < Sources.Size; src_n++)
+ if (Sources[src_n].DstFont == font)
+ Sources.erase(&Sources[src_n--]);
+
+ bool removed = Fonts.find_erase(font);
+ IM_ASSERT(removed);
+ IM_UNUSED(removed);
+
+ ImFontAtlasBuildUpdatePointers(this);
+
+ font->ContainerAtlas = NULL;
+ IM_DELETE(font);
+
+ // Notify external systems
+ ImFont* new_current_font = Fonts.empty() ? NULL : Fonts[0];
+ ImFontAtlasBuildNotifySetFont(this, font, new_current_font);
+}
+
+// At it is common to do an AddCustomRect() followed by a GetCustomRect(), we provide an optional 'ImFontAtlasRect* out_r = NULL' argument to retrieve the info straight away.
+ImFontAtlasRectId ImFontAtlas::AddCustomRect(int width, int height, ImFontAtlasRect* out_r)
{
IM_ASSERT(width > 0 && width <= 0xFFFF);
IM_ASSERT(height > 0 && height <= 0xFFFF);
- ImFontAtlasCustomRect r;
- r.Width = (unsigned short)width;
- r.Height = (unsigned short)height;
- CustomRects.push_back(r);
- return CustomRects.Size - 1; // Return index
+
+ if (Builder == NULL)
+ ImFontAtlasBuildInit(this);
+
+ ImFontAtlasRectId r_id = ImFontAtlasPackAddRect(this, width, height);
+ if (r_id == ImFontAtlasRectId_Invalid)
+ return ImFontAtlasRectId_Invalid;
+ if (out_r != NULL)
+ GetCustomRect(r_id, out_r);
+
+ if (RendererHasTextures)
+ {
+ ImTextureRect* r = ImFontAtlasPackGetRect(this, r_id);
+ ImFontAtlasTextureBlockQueueUpload(this, TexData, r->x, r->y, r->w, r->h);
+ }
+ return r_id;
+}
+
+void ImFontAtlas::RemoveCustomRect(ImFontAtlasRectId id)
+{
+ if (ImFontAtlasPackGetRectSafe(this, id) == NULL)
+ return;
+ ImFontAtlasPackDiscardRect(this, id);
}
-int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset)
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+// This API does not make sense anymore with scalable fonts.
+// - Prefer adding a font source (ImFontConfig) using a custom/procedural loader.
+// - You may use ImFontFlags_LockBakedSizes to limit an existing font to known baked sizes:
+// ImFont* myfont = io.Fonts->AddFontFromFileTTF(....);
+// myfont->GetFontBaked(16.0f);
+// myfont->Flags |= ImFontFlags_LockBakedSizes;
+ImFontAtlasRectId ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset)
+{
+ float font_size = font->LegacySize;
+ return AddCustomRectFontGlyphForSize(font, font_size, codepoint, width, height, advance_x, offset);
+}
+// FIXME: we automatically set glyph.Colored=true by default.
+// If you need to alter this, you can write 'font->Glyphs.back()->Colored' after calling AddCustomRectFontGlyph().
+ImFontAtlasRectId ImFontAtlas::AddCustomRectFontGlyphForSize(ImFont* font, float font_size, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset)
{
#ifdef IMGUI_USE_WCHAR32
- IM_ASSERT(id <= IM_UNICODE_CODEPOINT_MAX);
+ IM_ASSERT(codepoint <= IM_UNICODE_CODEPOINT_MAX);
#endif
IM_ASSERT(font != NULL);
IM_ASSERT(width > 0 && width <= 0xFFFF);
IM_ASSERT(height > 0 && height <= 0xFFFF);
- ImFontAtlasCustomRect r;
- r.Width = (unsigned short)width;
- r.Height = (unsigned short)height;
- r.GlyphID = id;
- r.GlyphAdvanceX = advance_x;
- r.GlyphOffset = offset;
- r.Font = font;
- CustomRects.push_back(r);
- return CustomRects.Size - 1; // Return index
-}
-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
- *out_uv_min = ImVec2((float)rect->X * TexUvScale.x, (float)rect->Y * TexUvScale.y);
- *out_uv_max = ImVec2((float)(rect->X + rect->Width) * TexUvScale.x, (float)(rect->Y + rect->Height) * TexUvScale.y);
+ ImFontBaked* baked = font->GetFontBaked(font_size);
+
+ ImFontAtlasRectId r_id = ImFontAtlasPackAddRect(this, width, height);
+ if (r_id == ImFontAtlasRectId_Invalid)
+ return ImFontAtlasRectId_Invalid;
+ ImTextureRect* r = ImFontAtlasPackGetRect(this, r_id);
+ if (RendererHasTextures)
+ ImFontAtlasTextureBlockQueueUpload(this, TexData, r->x, r->y, r->w, r->h);
+
+ if (baked->IsGlyphLoaded(codepoint))
+ ImFontAtlasBakedDiscardFontGlyph(this, font, baked, baked->FindGlyph(codepoint));
+
+ ImFontGlyph glyph;
+ glyph.Codepoint = codepoint;
+ glyph.AdvanceX = advance_x;
+ glyph.X0 = offset.x;
+ glyph.Y0 = offset.y;
+ glyph.X1 = offset.x + r->w;
+ glyph.Y1 = offset.y + r->h;
+ glyph.Visible = true;
+ glyph.Colored = true; // FIXME: Arbitrary
+ glyph.PackId = r_id;
+ ImFontAtlasBakedAddFontGlyph(this, baked, font->Sources[0], &glyph);
+ return r_id;
+}
+#endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+
+bool ImFontAtlas::GetCustomRect(ImFontAtlasRectId id, ImFontAtlasRect* out_r) const
+{
+ ImTextureRect* r = ImFontAtlasPackGetRectSafe((ImFontAtlas*)this, id);
+ if (r == NULL)
+ return false;
+ IM_ASSERT(TexData->Width > 0 && TexData->Height > 0); // Font atlas needs to be built before we can calculate UV coordinates
+ if (out_r == NULL)
+ return true;
+ out_r->x = r->x;
+ out_r->y = r->y;
+ out_r->w = r->w;
+ out_r->h = r->h;
+ out_r->uv0 = ImVec2((float)(r->x), (float)(r->y)) * TexUvScale;
+ out_r->uv1 = ImVec2((float)(r->x + r->w), (float)(r->y + r->h)) * TexUvScale;
+ return true;
}
-bool ImFontAtlas::GetMouseCursorTexData(ImGuiMouseCursor cursor_type, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2])
+bool ImFontAtlasGetMouseCursorTexData(ImFontAtlas* atlas, ImGuiMouseCursor cursor_type, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2])
{
if (cursor_type <= ImGuiMouseCursor_None || cursor_type >= ImGuiMouseCursor_COUNT)
return false;
- if (Flags & ImFontAtlasFlags_NoMouseCursors)
+ if (atlas->Flags & ImFontAtlasFlags_NoMouseCursors)
return false;
- 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);
+ ImTextureRect* r = ImFontAtlasPackGetRect(atlas, atlas->Builder->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;
+ out_uv_border[0] = (pos) * atlas->TexUvScale;
+ out_uv_border[1] = (pos + size) * atlas->TexUvScale;
pos.x += FONT_ATLAS_DEFAULT_TEX_DATA_W + 1;
- out_uv_fill[0] = (pos) * TexUvScale;
- out_uv_fill[1] = (pos + size) * TexUvScale;
+ out_uv_fill[0] = (pos) * atlas->TexUvScale;
+ out_uv_fill[1] = (pos + size) * atlas->TexUvScale;
return true;
}
-bool ImFontAtlas::Build()
+// When atlas->RendererHasTextures = true, this is only called if no font were loaded.
+void ImFontAtlasBuildMain(ImFontAtlas* atlas)
{
- IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!");
+ IM_ASSERT(!atlas->Locked && "Cannot modify a locked ImFontAtlas!");
+ if (atlas->TexData && atlas->TexData->Format != atlas->TexDesiredFormat)
+ ImFontAtlasBuildClear(atlas);
- // Default font is none are specified
- if (ConfigData.Size == 0)
- AddFontDefault();
+ if (atlas->Builder == NULL)
+ ImFontAtlasBuildInit(atlas);
- // 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
- }
+ // Default font is none are specified
+ if (atlas->Sources.Size == 0)
+ atlas->AddFontDefault();
- // Build
- return builder_io->FontBuilder_Build(this);
+ // [LEGACY] For backends not supporting RendererHasTextures: preload all glyphs
+ ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas);
+ if (atlas->RendererHasTextures == false) // ~ImGuiBackendFlags_RendererHasTextures
+ ImFontAtlasBuildLegacyPreloadAllGlyphRanges(atlas);
+ atlas->TexIsBuilt = true;
}
-void ImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256], float in_brighten_factor)
+void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, ImFontBaked* baked, int* out_oversample_h, int* out_oversample_v)
{
- for (unsigned int i = 0; i < 256; i++)
- {
- unsigned int value = (unsigned int)(i * in_brighten_factor);
- out_table[i] = value > 255 ? 255 : (value & 0xFF);
- }
+ // Automatically disable horizontal oversampling over size 36
+ const float raster_size = baked->Size * baked->RasterizerDensity * src->RasterizerDensity;
+ *out_oversample_h = (src->OversampleH != 0) ? src->OversampleH : (raster_size > 36.0f || src->PixelSnapH) ? 1 : 2;
+ *out_oversample_v = (src->OversampleV != 0) ? src->OversampleV : 1;
}
-void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsigned char* pixels, int x, int y, int w, int h, int stride)
+// Setup main font loader for the atlas
+// Every font source (ImFontConfig) will use this unless ImFontConfig::FontLoader specify a custom loader.
+void ImFontAtlasBuildSetupFontLoader(ImFontAtlas* atlas, const ImFontLoader* font_loader)
{
- IM_ASSERT_PARANOID(w <= stride);
- unsigned char* data = pixels + x + y * stride;
- for (int j = h; j > 0; j--, data += stride - w)
- for (int i = w; i > 0; i--, data++)
- *data = table[*data];
-}
+ if (atlas->FontLoader == font_loader)
+ return;
+ IM_ASSERT(!atlas->Locked && "Cannot modify a locked ImFontAtlas!");
-#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
-{
- stbtt_fontinfo FontInfo;
- stbtt_pack_range PackRange; // Hold the list of codepoints to pack (essentially points to Codepoints.Data)
- stbrp_rect* Rects; // Rectangle to pack. We first fill in their size and the packer will give us their position.
- stbtt_packedchar* PackedChars; // Output glyphs
- const ImWchar* SrcRanges; // Ranges as requested by user (user is allowed to request too much, e.g. 0x0020..0xFFFF)
- 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)
- ImBitVector GlyphsSet; // Glyph bit map (random access, 1-bit per codepoint. This will be a maximum of 8KB)
- ImVector<int> GlyphsList; // Glyph codepoints list (flattened version of GlyphsSet)
-};
+ for (ImFont* font : atlas->Fonts)
+ ImFontAtlasFontDestroyOutput(atlas, font);
+ if (atlas->Builder && atlas->FontLoader && atlas->FontLoader->LoaderShutdown)
+ atlas->FontLoader->LoaderShutdown(atlas);
-// Temporary data for one destination ImFont* (multiple source fonts can be merged into one destination ImFont)
-struct ImFontBuildDstData
-{
- int SrcCount; // Number of source fonts targeting this destination font.
- int GlyphsHighest;
- int GlyphsCount;
- ImBitVector GlyphsSet; // This is used to resolve collision when multiple sources are merged into a same destination font.
-};
+ atlas->FontLoader = font_loader;
+ atlas->FontLoaderName = font_loader ? font_loader->Name : "NULL";
+ IM_ASSERT(atlas->FontLoaderData == NULL);
-static void UnpackBitVectorToFlatIndexList(const ImBitVector* in, ImVector<int>* out)
-{
- IM_ASSERT(sizeof(in->Storage.Data[0]) == sizeof(int));
- 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));
+ if (atlas->Builder && atlas->FontLoader && atlas->FontLoader->LoaderInit)
+ atlas->FontLoader->LoaderInit(atlas);
+ for (ImFont* font : atlas->Fonts)
+ ImFontAtlasFontInitOutput(atlas, font);
+ for (ImFont* font : atlas->Fonts)
+ for (ImFontConfig* src : font->Sources)
+ ImFontAtlasFontSourceAddToFont(atlas, font, src);
}
-static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
+// Preload all glyph ranges for legacy backends.
+// This may lead to multiple texture creation which might be a little slower than before.
+void ImFontAtlasBuildLegacyPreloadAllGlyphRanges(ImFontAtlas* atlas)
{
- IM_ASSERT(atlas->ConfigData.Size > 0);
-
- ImFontAtlasBuildInit(atlas);
-
- // Clear atlas
- atlas->TexID = (ImTextureID)NULL;
- atlas->TexWidth = atlas->TexHeight = 0;
- atlas->TexUvScale = ImVec2(0.0f, 0.0f);
- atlas->TexUvWhitePixel = ImVec2(0.0f, 0.0f);
- atlas->ClearTexData();
-
- // Temporary storage for building
- ImVector<ImFontBuildSrcData> src_tmp_array;
- ImVector<ImFontBuildDstData> dst_tmp_array;
- src_tmp_array.resize(atlas->ConfigData.Size);
- dst_tmp_array.resize(atlas->Fonts.Size);
- memset(src_tmp_array.Data, 0, (size_t)src_tmp_array.size_in_bytes());
- memset(dst_tmp_array.Data, 0, (size_t)dst_tmp_array.size_in_bytes());
-
- // 1. Initialize font loading structure, check font data validity
- for (int src_i = 0; src_i < atlas->ConfigData.Size; src_i++)
- {
- ImFontBuildSrcData& src_tmp = src_tmp_array[src_i];
- ImFontConfig& cfg = atlas->ConfigData[src_i];
- IM_ASSERT(cfg.DstFont && (!cfg.DstFont->IsLoaded() || cfg.DstFont->ContainerAtlas == atlas));
-
- // Find index from cfg.DstFont (we allow the user to set cfg.DstFont. Also it makes casual debugging nicer than when storing indices)
- src_tmp.DstIndex = -1;
- 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;
- if (src_tmp.DstIndex == -1)
+ atlas->Builder->PreloadedAllGlyphsRanges = true;
+ for (ImFont* font : atlas->Fonts)
+ {
+ ImFontBaked* baked = font->GetFontBaked(font->LegacySize);
+ if (font->FallbackChar != 0)
+ baked->FindGlyph(font->FallbackChar);
+ if (font->EllipsisChar != 0)
+ baked->FindGlyph(font->EllipsisChar);
+ for (ImFontConfig* src : font->Sources)
{
- IM_ASSERT(src_tmp.DstIndex != -1); // cfg.DstFont not pointing within atlas->Fonts[] array?
- return false;
+ const ImWchar* ranges = src->GlyphRanges ? src->GlyphRanges : atlas->GetGlyphRangesDefault();
+ for (; ranges[0]; ranges += 2)
+ for (unsigned int c = ranges[0]; c <= ranges[1] && c <= IM_UNICODE_CODEPOINT_MAX; c++) //-V560
+ baked->FindGlyph((ImWchar)c);
}
- // 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.");
- if (!stbtt_InitFont(&src_tmp.FontInfo, (unsigned char*)cfg.FontData, font_offset))
+ }
+}
+
+// FIXME: May make ImFont::Sources a ImSpan<> and move ownership to ImFontAtlas
+void ImFontAtlasBuildUpdatePointers(ImFontAtlas* atlas)
+{
+ for (ImFont* font : atlas->Fonts)
+ font->Sources.resize(0);
+ for (ImFontConfig& src : atlas->Sources)
+ src.DstFont->Sources.push_back(&src);
+}
+
+// Render a white-colored bitmap encoded in a string
+void ImFontAtlasBuildRenderBitmapFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char)
+{
+ ImTextureData* tex = atlas->TexData;
+ IM_ASSERT(x >= 0 && x + w <= tex->Width);
+ IM_ASSERT(y >= 0 && y + h <= tex->Height);
+
+ switch (tex->Format)
+ {
+ case ImTextureFormat_Alpha8:
+ {
+ ImU8* out_p = (ImU8*)tex->GetPixelsAt(x, y);
+ for (int off_y = 0; off_y < h; off_y++, out_p += tex->Width, in_str += w)
+ for (int off_x = 0; off_x < w; off_x++)
+ out_p[off_x] = (in_str[off_x] == in_marker_char) ? 0xFF : 0x00;
+ break;
+ }
+ case ImTextureFormat_RGBA32:
+ {
+ ImU32* out_p = (ImU32*)tex->GetPixelsAt(x, y);
+ for (int off_y = 0; off_y < h; off_y++, out_p += tex->Width, in_str += w)
+ for (int off_x = 0; off_x < w; off_x++)
+ out_p[off_x] = (in_str[off_x] == in_marker_char) ? IM_COL32_WHITE : IM_COL32_BLACK_TRANS;
+ break;
+ }
+ }
+}
+
+static void ImFontAtlasBuildUpdateBasicTexData(ImFontAtlas* atlas)
+{
+ // Pack and store identifier so we can refresh UV coordinates on texture resize.
+ // FIXME-NEWATLAS: User/custom rects where user code wants to store UV coordinates will need to do the same thing.
+ ImFontAtlasBuilder* builder = atlas->Builder;
+ ImVec2i pack_size = (atlas->Flags & ImFontAtlasFlags_NoMouseCursors) ? ImVec2i(2, 2) : ImVec2i(FONT_ATLAS_DEFAULT_TEX_DATA_W * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H);
+
+ ImFontAtlasRect r;
+ bool add_and_draw = (atlas->GetCustomRect(builder->PackIdMouseCursors, &r) == false);
+ if (add_and_draw)
+ {
+ builder->PackIdMouseCursors = atlas->AddCustomRect(pack_size.x, pack_size.y, &r);
+ IM_ASSERT(builder->PackIdMouseCursors != ImFontAtlasRectId_Invalid);
+
+ // Draw to texture
+ if (atlas->Flags & ImFontAtlasFlags_NoMouseCursors)
{
- IM_ASSERT(0 && "stbtt_InitFont(): failed to parse FontData. It is correct and complete? Check FontDataSize.");
- return false;
+ // 2x2 white pixels
+ ImFontAtlasBuildRenderBitmapFromString(atlas, r.x, r.y, 2, 2, "XX" "XX", 'X');
}
+ else
+ {
+ // 2x2 white pixels + mouse cursors
+ const int x_for_white = r.x;
+ const int x_for_black = r.x + FONT_ATLAS_DEFAULT_TEX_DATA_W + 1;
+ ImFontAtlasBuildRenderBitmapFromString(atlas, x_for_white, r.y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, '.');
+ ImFontAtlasBuildRenderBitmapFromString(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');
+ }
+ }
+
+ // Refresh UV coordinates
+ atlas->TexUvWhitePixel = ImVec2((r.x + 0.5f) * atlas->TexUvScale.x, (r.y + 0.5f) * atlas->TexUvScale.y);
+}
+
+static void ImFontAtlasBuildUpdateLinesTexData(ImFontAtlas* atlas)
+{
+ if (atlas->Flags & ImFontAtlasFlags_NoBakedLines)
+ return;
+
+ // Pack and store identifier so we can refresh UV coordinates on texture resize.
+ ImTextureData* tex = atlas->TexData;
+ ImFontAtlasBuilder* builder = atlas->Builder;
+
+ ImFontAtlasRect r;
+ bool add_and_draw = atlas->GetCustomRect(builder->PackIdLinesTexData, &r) == false;
+ if (add_and_draw)
+ {
+ ImVec2i pack_size = ImVec2i(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1);
+ builder->PackIdLinesTexData = atlas->AddCustomRect(pack_size.x, pack_size.y, &r);
+ IM_ASSERT(builder->PackIdLinesTexData != ImFontAtlasRectId_Invalid);
+ }
- // Measure highest codepoints
- ImFontBuildDstData& dst_tmp = dst_tmp_array[src_tmp.DstIndex];
- src_tmp.SrcRanges = cfg.GlyphRanges ? cfg.GlyphRanges : atlas->GetGlyphRangesDefault();
- for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 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
+ // This generates a triangular shape in the texture, with the various line widths stacked on top of each other to allow interpolation between them
+ for (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
+ const int y = n;
+ const int line_width = n;
+ const int pad_left = (r.w - line_width) / 2;
+ const int pad_right = r.w - (pad_left + line_width);
+ IM_ASSERT(pad_left + line_width + pad_right == r.w && y < r.h); // Make sure we're inside the texture bounds before we start writing pixels
+
+ // Write each slice
+ if (add_and_draw && tex->Format == ImTextureFormat_Alpha8)
{
- // Check for valid range. This may also help detect *some* dangling pointers, because a common
- // user error is to setup ImFontConfig::GlyphRanges with a pointer to data that isn't persistent,
- // or to forget to zero-terminate the glyph range array.
- IM_ASSERT(src_range[0] <= src_range[1] && "Invalid range: is your glyph range array persistent? it is zero-terminated?");
- src_tmp.GlyphsHighest = ImMax(src_tmp.GlyphsHighest, (int)src_range[1]);
+ ImU8* write_ptr = (ImU8*)tex->GetPixelsAt(r.x, r.y + y);
+ for (int i = 0; i < pad_left; i++)
+ *(write_ptr + i) = 0x00;
+
+ for (int i = 0; i < line_width; i++)
+ *(write_ptr + pad_left + i) = 0xFF;
+
+ for (int i = 0; i < pad_right; i++)
+ *(write_ptr + pad_left + line_width + i) = 0x00;
+ }
+ else if (add_and_draw && tex->Format == ImTextureFormat_RGBA32)
+ {
+ ImU32* write_ptr = (ImU32*)(void*)tex->GetPixelsAt(r.x, r.y + y);
+ for (int i = 0; i < pad_left; i++)
+ *(write_ptr + i) = IM_COL32(255, 255, 255, 0);
+
+ for (int i = 0; i < line_width; i++)
+ *(write_ptr + pad_left + i) = IM_COL32_WHITE;
+
+ for (int i = 0; i < pad_right; i++)
+ *(write_ptr + pad_left + line_width + i) = IM_COL32(255, 255, 255, 0);
}
- dst_tmp.SrcCount++;
- dst_tmp.GlyphsHighest = ImMax(dst_tmp.GlyphsHighest, src_tmp.GlyphsHighest);
+
+ // Refresh UV coordinates
+ 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);
}
+}
+
+//-----------------------------------------------------------------------------------------------------------------------------
- // 2. For every requested codepoint, check for their presence in the font data, and handle redundancy or overlaps between source fonts to avoid unused glyphs.
- int total_glyphs_count = 0;
- for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
+// Was tempted to lazily init FontSrc but wouldn't save much + makes it more complicated to detect invalid data at AddFont()
+bool ImFontAtlasFontInitOutput(ImFontAtlas* atlas, ImFont* font)
+{
+ bool ret = true;
+ for (ImFontConfig* src : font->Sources)
+ if (!ImFontAtlasFontSourceInit(atlas, src))
+ ret = false;
+ IM_ASSERT(ret); // Unclear how to react to this meaningfully. Assume that result will be same as initial AddFont() call.
+ return ret;
+}
+
+// Keep source/input FontData
+void ImFontAtlasFontDestroyOutput(ImFontAtlas* atlas, ImFont* font)
+{
+ font->ClearOutputData();
+ for (ImFontConfig* src : font->Sources)
{
- ImFontBuildSrcData& src_tmp = src_tmp_array[src_i];
- ImFontBuildDstData& dst_tmp = dst_tmp_array[src_tmp.DstIndex];
- src_tmp.GlyphsSet.Create(src_tmp.GlyphsHighest + 1);
- if (dst_tmp.GlyphsSet.Storage.empty())
- dst_tmp.GlyphsSet.Create(dst_tmp.GlyphsHighest + 1);
+ const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader;
+ if (loader && loader->FontSrcDestroy != NULL)
+ loader->FontSrcDestroy(atlas, src);
+ }
+}
+
+//-----------------------------------------------------------------------------------------------------------------------------
- for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2)
- for (unsigned int codepoint = src_range[0]; codepoint <= src_range[1]; codepoint++)
+bool ImFontAtlasFontSourceInit(ImFontAtlas* atlas, ImFontConfig* src)
+{
+ const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader;
+ if (loader->FontSrcInit != NULL && !loader->FontSrcInit(atlas, src))
+ return false;
+ return true;
+}
+
+void ImFontAtlasFontSourceAddToFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src)
+{
+ if (src->MergeMode == false)
+ {
+ font->ClearOutputData();
+ //font->FontSize = src->SizePixels;
+ font->ContainerAtlas = atlas;
+ IM_ASSERT(font->Sources[0] == src);
+ }
+ atlas->TexIsBuilt = false; // For legacy backends
+ ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, font, src);
+}
+
+void ImFontAtlasFontDestroySourceData(ImFontAtlas* atlas, ImFontConfig* src)
+{
+ IM_UNUSED(atlas);
+ if (src->FontDataOwnedByAtlas)
+ IM_FREE(src->FontData);
+ src->FontData = NULL;
+ if (src->GlyphExcludeRanges)
+ IM_FREE((void*)src->GlyphExcludeRanges);
+ src->GlyphExcludeRanges = NULL;
+}
+
+// Create a compact, baked "..." if it doesn't exist, by using the ".".
+// This may seem overly complicated right now but the point is to exercise and improve a technique which should be increasingly used.
+// FIXME-NEWATLAS: This borrows too much from FontLoader's FontLoadGlyph() handlers and suggest that we should add further helpers.
+static ImFontGlyph* ImFontAtlasBuildSetupFontBakedEllipsis(ImFontAtlas* atlas, ImFontBaked* baked)
+{
+ ImFont* font = baked->ContainerFont;
+ IM_ASSERT(font->EllipsisChar != 0);
+
+ const ImFontGlyph* dot_glyph = baked->FindGlyphNoFallback((ImWchar)'.');
+ if (dot_glyph == NULL)
+ dot_glyph = baked->FindGlyphNoFallback((ImWchar)0xFF0E);
+ if (dot_glyph == NULL)
+ return NULL;
+ ImFontAtlasRectId dot_r_id = dot_glyph->PackId; // Deep copy to avoid invalidation of glyphs and rect pointers
+ ImTextureRect* dot_r = ImFontAtlasPackGetRect(atlas, dot_r_id);
+ const int dot_spacing = 1;
+ const float dot_step = (dot_glyph->X1 - dot_glyph->X0) + dot_spacing;
+
+ ImFontAtlasRectId pack_id = ImFontAtlasPackAddRect(atlas, (dot_r->w * 3 + dot_spacing * 2), dot_r->h);
+ ImTextureRect* r = ImFontAtlasPackGetRect(atlas, pack_id);
+
+ ImFontGlyph glyph_in = {};
+ ImFontGlyph* glyph = &glyph_in;
+ glyph->Codepoint = font->EllipsisChar;
+ glyph->AdvanceX = ImMax(dot_glyph->AdvanceX, dot_glyph->X0 + dot_step * 3.0f - dot_spacing); // FIXME: Slightly odd for normally mono-space fonts but since this is used for trailing contents.
+ glyph->X0 = dot_glyph->X0;
+ glyph->Y0 = dot_glyph->Y0;
+ glyph->X1 = dot_glyph->X0 + dot_step * 3 - dot_spacing;
+ glyph->Y1 = dot_glyph->Y1;
+ glyph->Visible = true;
+ glyph->PackId = pack_id;
+ glyph = ImFontAtlasBakedAddFontGlyph(atlas, baked, NULL, glyph);
+ dot_glyph = NULL; // Invalidated
+
+ // Copy to texture, post-process and queue update for backend
+ // FIXME-NEWATLAS-V2: Dot glyph is already post-processed as this point, so this would damage it.
+ dot_r = ImFontAtlasPackGetRect(atlas, dot_r_id);
+ ImTextureData* tex = atlas->TexData;
+ for (int n = 0; n < 3; n++)
+ ImFontAtlasTextureBlockCopy(tex, dot_r->x, dot_r->y, tex, r->x + (dot_r->w + dot_spacing) * n, r->y, dot_r->w, dot_r->h);
+ ImFontAtlasTextureBlockQueueUpload(atlas, tex, r->x, r->y, r->w, r->h);
+
+ return glyph;
+}
+
+// Load fallback in order to obtain its index
+// (this is called from in hot-path so we avoid extraneous parameters to minimize impact on code size)
+static void ImFontAtlasBuildSetupFontBakedFallback(ImFontBaked* baked)
+{
+ IM_ASSERT(baked->FallbackGlyphIndex == -1);
+ IM_ASSERT(baked->FallbackAdvanceX == 0.0f);
+ ImFont* font = baked->ContainerFont;
+ ImFontGlyph* fallback_glyph = NULL;
+ if (font->FallbackChar != 0)
+ fallback_glyph = baked->FindGlyphNoFallback(font->FallbackChar);
+ if (fallback_glyph == NULL)
+ {
+ ImFontGlyph* space_glyph = baked->FindGlyphNoFallback((ImWchar)' ');
+ ImFontGlyph glyph;
+ glyph.Codepoint = 0;
+ glyph.AdvanceX = space_glyph ? space_glyph->AdvanceX : IM_ROUND(baked->Size * 0.40f);
+ fallback_glyph = ImFontAtlasBakedAddFontGlyph(font->ContainerAtlas, baked, NULL, &glyph);
+ }
+ baked->FallbackGlyphIndex = baked->Glyphs.index_from_ptr(fallback_glyph); // Storing index avoid need to update pointer on growth and simplify inner loop code
+ baked->FallbackAdvanceX = fallback_glyph->AdvanceX;
+}
+
+static void ImFontAtlasBuildSetupFontBakedBlanks(ImFontAtlas* atlas, ImFontBaked* baked)
+{
+ // Mark space as always hidden (not strictly correct/necessary. but some e.g. icons fonts don't have a space. it tends to look neater in previews)
+ ImFontGlyph* space_glyph = baked->FindGlyphNoFallback((ImWchar)' ');
+ if (space_glyph != NULL)
+ space_glyph->Visible = false;
+
+ // Setup Tab character.
+ // FIXME: Needs proper TAB handling but it needs to be contextualized (or we could arbitrary say that each string starts at "column 0" ?)
+ if (baked->FindGlyphNoFallback('\t') == NULL && space_glyph != NULL)
+ {
+ ImFontGlyph tab_glyph;
+ tab_glyph.Codepoint = '\t';
+ tab_glyph.AdvanceX = space_glyph->AdvanceX * IM_TABSIZE;
+ ImFontAtlasBakedAddFontGlyph(atlas, baked, NULL, &tab_glyph);
+ }
+}
+
+// Load/identify special glyphs
+// (note that this is called again for fonts with MergeMode)
+void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src)
+{
+ IM_UNUSED(atlas);
+ IM_ASSERT(font->Sources.contains(src));
+
+ // Find Fallback character. Actual glyph loaded in GetFontBaked().
+ const ImWchar fallback_chars[] = { font->FallbackChar, (ImWchar)IM_UNICODE_CODEPOINT_INVALID, (ImWchar)'?', (ImWchar)' ' };
+ if (font->FallbackChar == 0)
+ for (ImWchar candidate_char : fallback_chars)
+ if (candidate_char != 0 && font->IsGlyphInFont(candidate_char))
{
- 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;
+ font->FallbackChar = (ImWchar)candidate_char;
+ break;
+ }
- // Add to avail set/counters
- src_tmp.GlyphsCount++;
- dst_tmp.GlyphsCount++;
- src_tmp.GlyphsSet.SetBit(codepoint);
- dst_tmp.GlyphsSet.SetBit(codepoint);
- total_glyphs_count++;
+ // Setup Ellipsis character. It 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: Note that 0x2026 is rarely included in our font ranges. Because of this we are more likely to use three individual dots.
+ const ImWchar ellipsis_chars[] = { src->EllipsisChar, (ImWchar)0x2026, (ImWchar)0x0085 };
+ if (font->EllipsisChar == 0)
+ for (ImWchar candidate_char : ellipsis_chars)
+ if (candidate_char != 0 && font->IsGlyphInFont(candidate_char))
+ {
+ font->EllipsisChar = candidate_char;
+ break;
}
+ if (font->EllipsisChar == 0)
+ {
+ font->EllipsisChar = 0x0085;
+ font->EllipsisAutoBake = true;
}
+}
- // 3. Unpack our bit map into a flat list (we now have all the Unicode points that we know are requested _and_ available _and_ not overlapping another)
- for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
- {
- ImFontBuildSrcData& src_tmp = src_tmp_array[src_i];
- src_tmp.GlyphsList.reserve(src_tmp.GlyphsCount);
- UnpackBitVectorToFlatIndexList(&src_tmp.GlyphsSet, &src_tmp.GlyphsList);
- src_tmp.GlyphsSet.Clear();
- IM_ASSERT(src_tmp.GlyphsList.Size == src_tmp.GlyphsCount);
- }
- for (int dst_i = 0; dst_i < dst_tmp_array.Size; dst_i++)
- dst_tmp_array[dst_i].GlyphsSet.Clear();
- dst_tmp_array.clear();
-
- // Allocate packing character data and flag packed characters buffer as non-packed (x0=y0=x1=y1=0)
- // (We technically don't need to zero-clear buf_rects, but let's do it for the sake of sanity)
- ImVector<stbrp_rect> buf_rects;
- ImVector<stbtt_packedchar> buf_packedchars;
- buf_rects.resize(total_glyphs_count);
- buf_packedchars.resize(total_glyphs_count);
- memset(buf_rects.Data, 0, (size_t)buf_rects.size_in_bytes());
- memset(buf_packedchars.Data, 0, (size_t)buf_packedchars.size_in_bytes());
-
- // 4. Gather glyphs sizes so we can pack them in our virtual canvas.
- int total_surface = 0;
- int buf_rects_out_n = 0;
- int buf_packedchars_out_n = 0;
- for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
- {
- ImFontBuildSrcData& src_tmp = src_tmp_array[src_i];
- if (src_tmp.GlyphsCount == 0)
- continue;
+void ImFontAtlasBakedDiscardFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked, ImFontGlyph* glyph)
+{
+ if (glyph->PackId != ImFontAtlasRectId_Invalid)
+ {
+ ImFontAtlasPackDiscardRect(atlas, glyph->PackId);
+ glyph->PackId = ImFontAtlasRectId_Invalid;
+ }
+ ImWchar c = (ImWchar)glyph->Codepoint;
+ IM_ASSERT(font->FallbackChar != c && font->EllipsisChar != c); // Unsupported for simplicity
+ IM_ASSERT(glyph >= baked->Glyphs.Data && glyph < baked->Glyphs.Data + baked->Glyphs.Size);
+ IM_UNUSED(font);
+ baked->IndexLookup[c] = IM_FONTGLYPH_INDEX_UNUSED;
+ baked->IndexAdvanceX[c] = baked->FallbackAdvanceX;
+}
+
+ImFontBaked* ImFontAtlasBakedAdd(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density, ImGuiID baked_id)
+{
+ IMGUI_DEBUG_LOG_FONT("[font] Created baked %.2fpx\n", font_size);
+ ImFontBaked* baked = atlas->Builder->BakedPool.push_back(ImFontBaked());
+ baked->Size = font_size;
+ baked->RasterizerDensity = font_rasterizer_density;
+ baked->BakedId = baked_id;
+ baked->ContainerFont = font;
+ baked->LastUsedFrame = atlas->Builder->FrameCount;
+
+ // Initialize backend data
+ size_t loader_data_size = 0;
+ for (ImFontConfig* src : font->Sources) // Cannot easily be cached as we allow changing backend
+ {
+ const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader;
+ loader_data_size += loader->FontBakedSrcLoaderDataSize;
+ }
+ baked->FontLoaderDatas = (loader_data_size > 0) ? IM_ALLOC(loader_data_size) : NULL;
+ char* loader_data_p = (char*)baked->FontLoaderDatas;
+ for (ImFontConfig* src : font->Sources)
+ {
+ const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader;
+ if (loader->FontBakedInit)
+ loader->FontBakedInit(atlas, src, baked, loader_data_p);
+ loader_data_p += loader->FontBakedSrcLoaderDataSize;
+ }
+
+ ImFontAtlasBuildSetupFontBakedBlanks(atlas, baked);
+ return baked;
+}
- src_tmp.Rects = &buf_rects[buf_rects_out_n];
- src_tmp.PackedChars = &buf_packedchars[buf_packedchars_out_n];
- buf_rects_out_n += src_tmp.GlyphsCount;
- buf_packedchars_out_n += src_tmp.GlyphsCount;
-
- // Convert our ranges in the format stb_truetype wants
- ImFontConfig& cfg = atlas->ConfigData[src_i];
- src_tmp.PackRange.font_size = cfg.SizePixels * cfg.RasterizerDensity;
- src_tmp.PackRange.first_unicode_codepoint_in_range = 0;
- src_tmp.PackRange.array_of_unicode_codepoints = src_tmp.GlyphsList.Data;
- src_tmp.PackRange.num_chars = src_tmp.GlyphsList.Size;
- src_tmp.PackRange.chardata_for_range = src_tmp.PackedChars;
- src_tmp.PackRange.h_oversample = (unsigned char)cfg.OversampleH;
- src_tmp.PackRange.v_oversample = (unsigned char)cfg.OversampleV;
-
- // Gather the sizes of all rectangles we will need to pack (this loop is based on stbtt_PackFontRangesGatherRects)
- const float scale = (cfg.SizePixels > 0.0f) ? stbtt_ScaleForPixelHeight(&src_tmp.FontInfo, cfg.SizePixels * cfg.RasterizerDensity) : stbtt_ScaleForMappingEmToPixels(&src_tmp.FontInfo, -cfg.SizePixels * cfg.RasterizerDensity);
- const int padding = atlas->TexGlyphPadding;
- for (int glyph_i = 0; glyph_i < src_tmp.GlyphsList.Size; glyph_i++)
+// FIXME-OPT: This is not a fast query. Adding a BakedCount field in Font might allow to take a shortcut for the most common case.
+ImFontBaked* ImFontAtlasBakedGetClosestMatch(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density)
+{
+ ImFontAtlasBuilder* builder = atlas->Builder;
+ for (int step_n = 0; step_n < 2; step_n++)
+ {
+ ImFontBaked* closest_larger_match = NULL;
+ ImFontBaked* closest_smaller_match = NULL;
+ for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++)
{
- int x0, y0, x1, y1;
- const int glyph_index_in_font = stbtt_FindGlyphIndex(&src_tmp.FontInfo, src_tmp.GlyphsList[glyph_i]);
- IM_ASSERT(glyph_index_in_font != 0);
- stbtt_GetGlyphBitmapBoxSubpixel(&src_tmp.FontInfo, glyph_index_in_font, scale * cfg.OversampleH, scale * cfg.OversampleV, 0, 0, &x0, &y0, &x1, &y1);
- src_tmp.Rects[glyph_i].w = (stbrp_coord)(x1 - x0 + padding + cfg.OversampleH - 1);
- src_tmp.Rects[glyph_i].h = (stbrp_coord)(y1 - y0 + padding + cfg.OversampleV - 1);
- total_surface += src_tmp.Rects[glyph_i].w * src_tmp.Rects[glyph_i].h;
+ ImFontBaked* baked = &builder->BakedPool[baked_n];
+ if (baked->ContainerFont != font || baked->WantDestroy)
+ continue;
+ if (step_n == 0 && baked->RasterizerDensity != font_rasterizer_density) // First try with same density
+ continue;
+ if (baked->Size > font_size && (closest_larger_match == NULL || baked->Size < closest_larger_match->Size))
+ closest_larger_match = baked;
+ if (baked->Size < font_size && (closest_smaller_match == NULL || baked->Size > closest_smaller_match->Size))
+ closest_smaller_match = baked;
}
+ if (closest_larger_match)
+ if (closest_smaller_match == NULL || (closest_larger_match->Size >= font_size * 2.0f && closest_smaller_match->Size > font_size * 0.5f))
+ return closest_larger_match;
+ if (closest_smaller_match)
+ return closest_smaller_match;
}
+ return NULL;
+}
- // We need a width for the skyline algorithm, any width!
- // The exact width doesn't really matter much, but some API/GPU have texture size limitations and increasing width can decrease height.
- // User can override TexDesiredWidth and TexGlyphPadding if they wish, otherwise we use a simple heuristic to select the width based on expected surface.
- const int surface_sqrt = (int)ImSqrt((float)total_surface) + 1;
- atlas->TexHeight = 0;
- 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;
+void ImFontAtlasBakedDiscard(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked)
+{
+ ImFontAtlasBuilder* builder = atlas->Builder;
+ IMGUI_DEBUG_LOG_FONT("[font] Discard baked %.2f for \"%s\"\n", baked->Size, font->GetDebugName());
- // 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).
- const int TEX_HEIGHT_MAX = 1024 * 32;
- stbtt_pack_context spc = {};
- stbtt_PackBegin(&spc, NULL, atlas->TexWidth, TEX_HEIGHT_MAX, 0, atlas->TexGlyphPadding, NULL);
- ImFontAtlasBuildPackCustomRects(atlas, spc.pack_info);
+ for (ImFontGlyph& glyph : baked->Glyphs)
+ if (glyph.PackId != ImFontAtlasRectId_Invalid)
+ ImFontAtlasPackDiscardRect(atlas, glyph.PackId);
- // 6. Pack each source font. No rendering yet, we are working with rectangles in an infinitely tall texture at this point.
- for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
+ char* loader_data_p = (char*)baked->FontLoaderDatas;
+ for (ImFontConfig* src : font->Sources)
{
- ImFontBuildSrcData& src_tmp = src_tmp_array[src_i];
- if (src_tmp.GlyphsCount == 0)
- continue;
+ const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader;
+ if (loader->FontBakedDestroy)
+ loader->FontBakedDestroy(atlas, src, baked, loader_data_p);
+ loader_data_p += loader->FontBakedSrcLoaderDataSize;
+ }
+ if (baked->FontLoaderDatas)
+ {
+ IM_FREE(baked->FontLoaderDatas);
+ baked->FontLoaderDatas = NULL;
+ }
+ builder->BakedMap.SetVoidPtr(baked->BakedId, NULL);
+ builder->BakedDiscardedCount++;
+ baked->ClearOutputData();
+ baked->WantDestroy = true;
+ font->LastBaked = NULL;
+}
- stbrp_pack_rects((stbrp_context*)spc.pack_info, src_tmp.Rects, src_tmp.GlyphsCount);
+// use unused_frames==0 to discard everything.
+void ImFontAtlasFontDiscardBakes(ImFontAtlas* atlas, ImFont* font, int unused_frames)
+{
+ if (ImFontAtlasBuilder* builder = atlas->Builder) // This can be called from font destructor
+ for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++)
+ {
+ ImFontBaked* baked = &builder->BakedPool[baked_n];
+ if (baked->LastUsedFrame + unused_frames > atlas->Builder->FrameCount)
+ continue;
+ if (baked->ContainerFont != font || baked->WantDestroy)
+ continue;
+ ImFontAtlasBakedDiscard(atlas, font, baked);
+ }
+}
- // Extend texture height and mark missing glyphs as non-packed so we won't render them.
- // FIXME: We are not handling packing failure here (would happen if we got off TEX_HEIGHT_MAX or if a single if larger than TexWidth?)
- for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++)
- if (src_tmp.Rects[glyph_i].was_packed)
- atlas->TexHeight = ImMax(atlas->TexHeight, src_tmp.Rects[glyph_i].y + src_tmp.Rects[glyph_i].h);
+// use unused_frames==0 to discard everything.
+void ImFontAtlasBuildDiscardBakes(ImFontAtlas* atlas, int unused_frames)
+{
+ ImFontAtlasBuilder* builder = atlas->Builder;
+ for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++)
+ {
+ ImFontBaked* baked = &builder->BakedPool[baked_n];
+ if (baked->LastUsedFrame + unused_frames > atlas->Builder->FrameCount)
+ continue;
+ if (baked->WantDestroy || (baked->ContainerFont->Flags & ImFontFlags_LockBakedSizes))
+ continue;
+ ImFontAtlasBakedDiscard(atlas, baked->ContainerFont, baked);
}
+}
- // 7. Allocate texture
- atlas->TexHeight = (atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) ? (atlas->TexHeight + 1) : ImUpperPowerOfTwo(atlas->TexHeight);
- atlas->TexUvScale = ImVec2(1.0f / atlas->TexWidth, 1.0f / atlas->TexHeight);
- atlas->TexPixelsAlpha8 = (unsigned char*)IM_ALLOC(atlas->TexWidth * atlas->TexHeight);
- memset(atlas->TexPixelsAlpha8, 0, atlas->TexWidth * atlas->TexHeight);
- spc.pixels = atlas->TexPixelsAlpha8;
- spc.height = atlas->TexHeight;
+// Those functions are designed to facilitate changing the underlying structures for ImFontAtlas to store an array of ImDrawListSharedData*
+void ImFontAtlasAddDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data)
+{
+ IM_ASSERT(!atlas->DrawListSharedDatas.contains(data));
+ atlas->DrawListSharedDatas.push_back(data);
+}
- // 8. Render/rasterize font characters into the texture
- for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
+void ImFontAtlasRemoveDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data)
+{
+ IM_ASSERT(atlas->DrawListSharedDatas.contains(data));
+ atlas->DrawListSharedDatas.find_erase(data);
+}
+
+// Update texture identifier in all active draw lists
+void ImFontAtlasUpdateDrawListsTextures(ImFontAtlas* atlas, ImTextureRef old_tex, ImTextureRef new_tex)
+{
+ for (ImDrawListSharedData* shared_data : atlas->DrawListSharedDatas)
+ for (ImDrawList* draw_list : shared_data->DrawLists)
+ {
+ // Replace in command-buffer
+ // (there is not need to replace in ImDrawListSplitter: current channel is in ImDrawList's CmdBuffer[],
+ // other channels will be on SetCurrentChannel() which already needs to compare CmdHeader anyhow)
+ if (draw_list->CmdBuffer.Size > 0 && draw_list->_CmdHeader.TexRef == old_tex)
+ draw_list->_SetTexture(new_tex);
+
+ // Replace in stack
+ for (ImTextureRef& stacked_tex : draw_list->_TextureStack)
+ if (stacked_tex == old_tex)
+ stacked_tex = new_tex;
+ }
+}
+
+// Update texture coordinates in all draw list shared context
+// FIXME-NEWATLAS FIXME-OPT: Doesn't seem necessary to update for all, only one bound to current context?
+void ImFontAtlasUpdateDrawListsSharedData(ImFontAtlas* atlas)
+{
+ for (ImDrawListSharedData* shared_data : atlas->DrawListSharedDatas)
+ if (shared_data->FontAtlas == atlas)
+ {
+ shared_data->TexUvWhitePixel = atlas->TexUvWhitePixel;
+ shared_data->TexUvLines = atlas->TexUvLines;
+ }
+}
+
+// Set current texture. This is mostly called from AddTexture() + to handle a failed resize.
+static void ImFontAtlasBuildSetTexture(ImFontAtlas* atlas, ImTextureData* tex)
+{
+ ImTextureRef old_tex_ref = atlas->TexRef;
+ atlas->TexData = tex;
+ atlas->TexUvScale = ImVec2(1.0f / tex->Width, 1.0f / tex->Height);
+ atlas->TexRef._TexData = tex;
+ //atlas->TexRef._TexID = tex->TexID; // <-- We intentionally don't do that. It would be misleading and betray promise that both fields aren't set.
+ ImFontAtlasUpdateDrawListsTextures(atlas, old_tex_ref, atlas->TexRef);
+}
+
+// Create a new texture, discard previous one
+ImTextureData* ImFontAtlasTextureAdd(ImFontAtlas* atlas, int w, int h)
+{
+ ImTextureData* old_tex = atlas->TexData;
+ ImTextureData* new_tex;
+
+ // FIXME: Cannot reuse texture because old UV may have been used already (unless we remap UV).
+ /*if (old_tex != NULL && old_tex->Status == ImTextureStatus_WantCreate)
{
- ImFontConfig& cfg = atlas->ConfigData[src_i];
- ImFontBuildSrcData& src_tmp = src_tmp_array[src_i];
- if (src_tmp.GlyphsCount == 0)
- continue;
+ // Reuse texture not yet used by backend.
+ IM_ASSERT(old_tex->TexID == ImTextureID_Invalid && old_tex->BackendUserData == NULL);
+ old_tex->DestroyPixels();
+ old_tex->Updates.clear();
+ new_tex = old_tex;
+ old_tex = NULL;
+ }
+ else*/
+ {
+ // Add new
+ new_tex = IM_NEW(ImTextureData)();
+ new_tex->UniqueID = atlas->TexNextUniqueID++;
+ atlas->TexList.push_back(new_tex);
+ }
+ if (old_tex != NULL)
+ {
+ // Queue old as to destroy next frame
+ old_tex->WantDestroyNextFrame = true;
+ IM_ASSERT(old_tex->Status == ImTextureStatus_OK || old_tex->Status == ImTextureStatus_WantCreate || old_tex->Status == ImTextureStatus_WantUpdates);
+ }
+
+ new_tex->Create(atlas->TexDesiredFormat, w, h);
+ atlas->TexIsBuilt = false;
- stbtt_PackFontRangesRenderIntoRects(&spc, &src_tmp.FontInfo, &src_tmp.PackRange, 1, src_tmp.Rects);
+ ImFontAtlasBuildSetTexture(atlas, new_tex);
- // Apply multiply operator
- if (cfg.RasterizerMultiply != 1.0f)
+ return new_tex;
+}
+
+#if 0
+#define STB_IMAGE_WRITE_IMPLEMENTATION
+#include "../stb/stb_image_write.h"
+static void ImFontAtlasDebugWriteTexToDisk(ImTextureData* tex, const char* description)
+{
+ ImGuiContext& g = *GImGui;
+ char buf[128];
+ ImFormatString(buf, IM_ARRAYSIZE(buf), "[%05d] Texture #%03d - %s.png", g.FrameCount, tex->UniqueID, description);
+ stbi_write_png(buf, tex->Width, tex->Height, tex->BytesPerPixel, tex->Pixels, tex->GetPitch()); // tex->BytesPerPixel is technically not component, but ok for the formats we support.
+}
+#endif
+
+void ImFontAtlasTextureRepack(ImFontAtlas* atlas, int w, int h)
+{
+ ImFontAtlasBuilder* builder = atlas->Builder;
+ builder->LockDisableResize = true;
+
+ ImTextureData* old_tex = atlas->TexData;
+ ImTextureData* new_tex = ImFontAtlasTextureAdd(atlas, w, h);
+ new_tex->UseColors = old_tex->UseColors;
+ IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: resize+repack %dx%d => Texture #%03d: %dx%d\n", old_tex->UniqueID, old_tex->Width, old_tex->Height, new_tex->UniqueID, new_tex->Width, new_tex->Height);
+ //for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++)
+ // IMGUI_DEBUG_LOG_FONT("[font] - Baked %.2fpx, %d glyphs, want_destroy=%d\n", builder->BakedPool[baked_n].FontSize, builder->BakedPool[baked_n].Glyphs.Size, builder->BakedPool[baked_n].WantDestroy);
+ //IMGUI_DEBUG_LOG_FONT("[font] - Old packed rects: %d, area %d px\n", builder->RectsPackedCount, builder->RectsPackedSurface);
+ //ImFontAtlasDebugWriteTexToDisk(old_tex, "Before Pack");
+
+ // Repack, lose discarded rectangle, copy pixels
+ // FIXME-NEWATLAS: This is unstable because packing order is based on RectsIndex
+ // FIXME-NEWATLAS-V2: Repacking in batch would be beneficial to packing heuristic, and fix stability.
+ // FIXME-NEWATLAS-TESTS: Test calling RepackTexture with size too small to fits existing rects.
+ ImFontAtlasPackInit(atlas);
+ ImVector<ImTextureRect> old_rects;
+ ImVector<ImFontAtlasRectEntry> old_index = builder->RectsIndex;
+ old_rects.swap(builder->Rects);
+
+ for (ImFontAtlasRectEntry& index_entry : builder->RectsIndex)
+ {
+ if (index_entry.IsUsed == false)
+ continue;
+ ImTextureRect& old_r = old_rects[index_entry.TargetIndex];
+ if (old_r.w == 0 && old_r.h == 0)
+ continue;
+ ImFontAtlasRectId new_r_id = ImFontAtlasPackAddRect(atlas, old_r.w, old_r.h, &index_entry);
+ if (new_r_id == ImFontAtlasRectId_Invalid)
{
- unsigned char multiply_table[256];
- ImFontAtlasBuildMultiplyCalcLookupTable(multiply_table, cfg.RasterizerMultiply);
- stbrp_rect* r = &src_tmp.Rects[0];
- for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++, r++)
- if (r->was_packed)
- ImFontAtlasBuildMultiplyRectAlpha8(multiply_table, atlas->TexPixelsAlpha8, r->x, r->y, r->w, r->h, atlas->TexWidth * 1);
+ // Undo, grow texture and try repacking again.
+ // FIXME-NEWATLAS-TESTS: This is a very rarely exercised path! It needs to be automatically tested properly.
+ IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: resize failed. Will grow.\n", new_tex->UniqueID);
+ new_tex->WantDestroyNextFrame = true;
+ builder->Rects.swap(old_rects);
+ builder->RectsIndex = old_index;
+ ImFontAtlasBuildSetTexture(atlas, old_tex);
+ ImFontAtlasTextureGrow(atlas, w, h); // Recurse
+ return;
}
- src_tmp.Rects = NULL;
+ IM_ASSERT(ImFontAtlasRectId_GetIndex(new_r_id) == builder->RectsIndex.index_from_ptr(&index_entry));
+ ImTextureRect* new_r = ImFontAtlasPackGetRect(atlas, new_r_id);
+ ImFontAtlasTextureBlockCopy(old_tex, old_r.x, old_r.y, new_tex, new_r->x, new_r->y, new_r->w, new_r->h);
}
+ IM_ASSERT(old_rects.Size == builder->Rects.Size + builder->RectsDiscardedCount);
+ builder->RectsDiscardedCount = 0;
+ builder->RectsDiscardedSurface = 0;
+
+ // Patch glyphs UV
+ for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++)
+ for (ImFontGlyph& glyph : builder->BakedPool[baked_n].Glyphs)
+ if (glyph.PackId != ImFontAtlasRectId_Invalid)
+ {
+ ImTextureRect* r = ImFontAtlasPackGetRect(atlas, glyph.PackId);
+ glyph.U0 = (r->x) * atlas->TexUvScale.x;
+ glyph.V0 = (r->y) * atlas->TexUvScale.y;
+ glyph.U1 = (r->x + r->w) * atlas->TexUvScale.x;
+ glyph.V1 = (r->y + r->h) * atlas->TexUvScale.y;
+ }
+
+ // Update other cached UV
+ ImFontAtlasBuildUpdateLinesTexData(atlas);
+ ImFontAtlasBuildUpdateBasicTexData(atlas);
+
+ builder->LockDisableResize = false;
+ ImFontAtlasUpdateDrawListsSharedData(atlas);
+ //ImFontAtlasDebugWriteTexToDisk(new_tex, "After Pack");
+}
+
+void ImFontAtlasTextureGrow(ImFontAtlas* atlas, int old_tex_w, int old_tex_h)
+{
+ //ImFontAtlasDebugWriteTexToDisk(atlas->TexData, "Before Grow");
+ ImFontAtlasBuilder* builder = atlas->Builder;
+ if (old_tex_w == -1)
+ old_tex_w = atlas->TexData->Width;
+ if (old_tex_h == -1)
+ old_tex_h = atlas->TexData->Height;
+
+ // FIXME-NEWATLAS-V2: What to do when reaching limits exposed by backend?
+ // FIXME-NEWATLAS-V2: Does ImFontAtlasFlags_NoPowerOfTwoHeight makes sense now? Allow 'lock' and 'compact' operations?
+ IM_ASSERT(ImIsPowerOfTwo(old_tex_w) && ImIsPowerOfTwo(old_tex_h));
+ IM_ASSERT(ImIsPowerOfTwo(atlas->TexMinWidth) && ImIsPowerOfTwo(atlas->TexMaxWidth) && ImIsPowerOfTwo(atlas->TexMinHeight) && ImIsPowerOfTwo(atlas->TexMaxHeight));
+
+ // Grow texture so it follows roughly a square.
+ // - Grow height before width, as width imply more packing nodes.
+ // - Caller should be taking account of RectsDiscardedSurface and may not need to grow.
+ int new_tex_w = (old_tex_h <= old_tex_w) ? old_tex_w : old_tex_w * 2;
+ int new_tex_h = (old_tex_h <= old_tex_w) ? old_tex_h * 2 : old_tex_h;
+
+ // Handle minimum size first (for pathologically large packed rects)
+ const int pack_padding = atlas->TexGlyphPadding;
+ new_tex_w = ImMax(new_tex_w, ImUpperPowerOfTwo(builder->MaxRectSize.x + pack_padding));
+ new_tex_h = ImMax(new_tex_h, ImUpperPowerOfTwo(builder->MaxRectSize.y + pack_padding));
+ new_tex_w = ImClamp(new_tex_w, atlas->TexMinWidth, atlas->TexMaxWidth);
+ new_tex_h = ImClamp(new_tex_h, atlas->TexMinHeight, atlas->TexMaxHeight);
+ if (new_tex_w == old_tex_w && new_tex_h == old_tex_h)
+ return;
+
+ ImFontAtlasTextureRepack(atlas, new_tex_w, new_tex_h);
+}
- // End packing
- stbtt_PackEnd(&spc);
- buf_rects.clear();
+void ImFontAtlasTextureMakeSpace(ImFontAtlas* atlas)
+{
+ // Can some baked contents be ditched?
+ //IMGUI_DEBUG_LOG_FONT("[font] ImFontAtlasBuildMakeSpace()\n");
+ ImFontAtlasBuilder* builder = atlas->Builder;
+ ImFontAtlasBuildDiscardBakes(atlas, 2);
+
+ // Currently using a heuristic for repack without growing.
+ if (builder->RectsDiscardedSurface < builder->RectsPackedSurface * 0.20f)
+ ImFontAtlasTextureGrow(atlas);
+ else
+ ImFontAtlasTextureRepack(atlas, atlas->TexData->Width, atlas->TexData->Height);
+}
- // 9. Setup ImFont and glyphs for runtime
- for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
+ImVec2i ImFontAtlasTextureGetSizeEstimate(ImFontAtlas* atlas)
+{
+ int min_w = ImUpperPowerOfTwo(atlas->TexMinWidth);
+ int min_h = ImUpperPowerOfTwo(atlas->TexMinHeight);
+ if (atlas->Builder == NULL || atlas->TexData == NULL || atlas->TexData->Status == ImTextureStatus_WantDestroy)
+ return ImVec2i(min_w, min_h);
+
+ ImFontAtlasBuilder* builder = atlas->Builder;
+ min_w = ImMax(ImUpperPowerOfTwo(builder->MaxRectSize.x), min_w);
+ min_h = ImMax(ImUpperPowerOfTwo(builder->MaxRectSize.y), min_h);
+ const int surface_approx = builder->RectsPackedSurface - builder->RectsDiscardedSurface; // Expected surface after repack
+ const int surface_sqrt = (int)sqrtf((float)surface_approx);
+
+ int new_tex_w;
+ int new_tex_h;
+ if (min_w >= min_h)
+ {
+ new_tex_w = ImMax(min_w, ImUpperPowerOfTwo(surface_sqrt));
+ new_tex_h = ImMax(min_h, (int)((surface_approx + new_tex_w - 1) / new_tex_w));
+ if ((atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) == 0)
+ new_tex_h = ImUpperPowerOfTwo(new_tex_h);
+ }
+ else
{
- // 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.
- ImFontBuildSrcData& src_tmp = src_tmp_array[src_i];
- ImFontConfig& cfg = atlas->ConfigData[src_i];
- ImFont* dst_font = cfg.DstFont;
+ new_tex_h = ImMax(min_h, ImUpperPowerOfTwo(surface_sqrt));
+ if ((atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) == 0)
+ new_tex_h = ImUpperPowerOfTwo(new_tex_h);
+ new_tex_w = ImMax(min_w, (int)((surface_approx + new_tex_h - 1) / new_tex_h));
+ }
- const float font_scale = stbtt_ScaleForPixelHeight(&src_tmp.FontInfo, cfg.SizePixels);
- int unscaled_ascent, unscaled_descent, unscaled_line_gap;
- stbtt_GetFontVMetrics(&src_tmp.FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap);
+ IM_ASSERT(ImIsPowerOfTwo(new_tex_w) && ImIsPowerOfTwo(new_tex_h));
+ return ImVec2i(new_tex_w, new_tex_h);
+}
+
+// Clear all output. Invalidates all AddCustomRect() return values!
+void ImFontAtlasBuildClear(ImFontAtlas* atlas)
+{
+ ImVec2i new_tex_size = ImFontAtlasTextureGetSizeEstimate(atlas);
+ ImFontAtlasBuildDestroy(atlas);
+ ImFontAtlasTextureAdd(atlas, new_tex_size.x, new_tex_size.y);
+ ImFontAtlasBuildInit(atlas);
+ for (ImFontConfig& src : atlas->Sources)
+ ImFontAtlasFontSourceInit(atlas, &src);
+ for (ImFont* font : atlas->Fonts)
+ for (ImFontConfig* src : font->Sources)
+ ImFontAtlasFontSourceAddToFont(atlas, font, src);
+}
+
+// You should not need to call this manually!
+// If you think you do, let us know and we can advise about policies auto-compact.
+void ImFontAtlasTextureCompact(ImFontAtlas* atlas)
+{
+ ImFontAtlasBuilder* builder = atlas->Builder;
+ ImFontAtlasBuildDiscardBakes(atlas, 1);
+
+ ImTextureData* old_tex = atlas->TexData;
+ ImVec2i old_tex_size = ImVec2i(old_tex->Width, old_tex->Height);
+ ImVec2i new_tex_size = ImFontAtlasTextureGetSizeEstimate(atlas);
+ if (builder->RectsDiscardedCount == 0 && new_tex_size.x == old_tex_size.x && new_tex_size.y == old_tex_size.y)
+ return;
+
+ ImFontAtlasTextureRepack(atlas, new_tex_size.x, new_tex_size.y);
+}
+
+// Start packing over current empty texture
+void ImFontAtlasBuildInit(ImFontAtlas* atlas)
+{
+ // Select Backend
+ // - Note that we do not reassign to atlas->FontLoader, 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 FontLoader somewhere
+ // and point to it instead of pointing directly to return value of the GetFontLoaderXXX functions.
+ if (atlas->FontLoader == NULL)
+ {
+#ifdef IMGUI_ENABLE_FREETYPE
+ atlas->SetFontLoader(ImGuiFreeType::GetFontLoader());
+#elif defined(IMGUI_ENABLE_STB_TRUETYPE)
+ atlas->SetFontLoader(ImFontAtlasGetFontLoaderForStbTruetype());
+#else
+ IM_ASSERT(0); // Invalid Build function
+#endif
+ }
+
+ // Create initial texture size
+ if (atlas->TexData == NULL || atlas->TexData->Pixels == NULL)
+ ImFontAtlasTextureAdd(atlas, ImUpperPowerOfTwo(atlas->TexMinWidth), ImUpperPowerOfTwo(atlas->TexMinHeight));
+
+ atlas->Builder = IM_NEW(ImFontAtlasBuilder)();
+ if (atlas->FontLoader->LoaderInit)
+ atlas->FontLoader->LoaderInit(atlas);
+
+ ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas);
+
+ ImFontAtlasPackInit(atlas);
+
+ // Add required texture data
+ ImFontAtlasBuildUpdateLinesTexData(atlas);
+ ImFontAtlasBuildUpdateBasicTexData(atlas);
+
+ // Register fonts
+ ImFontAtlasBuildUpdatePointers(atlas);
- const float ascent = ImCeil(unscaled_ascent * font_scale);
- const float descent = ImFloor(unscaled_descent * font_scale);
- ImFontAtlasBuildSetupFont(atlas, dst_font, &cfg, ascent, descent);
- const float font_off_x = cfg.GlyphOffset.x;
- const float font_off_y = cfg.GlyphOffset.y + IM_ROUND(dst_font->Ascent);
+ // Update UV coordinates etc. stored in bound ImDrawListSharedData instance
+ ImFontAtlasUpdateDrawListsSharedData(atlas);
- const float inv_rasterization_scale = 1.0f / cfg.RasterizerDensity;
+ //atlas->TexIsBuilt = true;
+}
+
+// Destroy builder and all cached glyphs. Do not destroy actual fonts.
+void ImFontAtlasBuildDestroy(ImFontAtlas* atlas)
+{
+ for (ImFont* font : atlas->Fonts)
+ ImFontAtlasFontDestroyOutput(atlas, font);
+ if (atlas->Builder && atlas->FontLoader && atlas->FontLoader->LoaderShutdown)
+ {
+ atlas->FontLoader->LoaderShutdown(atlas);
+ IM_ASSERT(atlas->FontLoaderData == NULL);
+ }
+ IM_DELETE(atlas->Builder);
+ atlas->Builder = NULL;
+}
+
+void ImFontAtlasPackInit(ImFontAtlas * atlas)
+{
+ ImTextureData* tex = atlas->TexData;
+ ImFontAtlasBuilder* builder = atlas->Builder;
+
+ // In theory we could decide to reduce the number of nodes, e.g. halve them, and waste a little texture space, but it doesn't seem worth it.
+ const int pack_node_count = tex->Width / 2;
+ builder->PackNodes.resize(pack_node_count);
+ IM_STATIC_ASSERT(sizeof(stbrp_context) <= sizeof(stbrp_context_opaque));
+ stbrp_init_target((stbrp_context*)(void*)&builder->PackContext, tex->Width, tex->Height, builder->PackNodes.Data, builder->PackNodes.Size);
+ builder->RectsPackedSurface = builder->RectsPackedCount = 0;
+ builder->MaxRectSize = ImVec2i(0, 0);
+ builder->MaxRectBounds = ImVec2i(0, 0);
+}
+
+// This is essentially a free-list pattern, it may be nice to wrap it into a dedicated type.
+static ImFontAtlasRectId ImFontAtlasPackAllocRectEntry(ImFontAtlas* atlas, int rect_idx)
+{
+ ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder;
+ int index_idx;
+ ImFontAtlasRectEntry* index_entry;
+ if (builder->RectsIndexFreeListStart < 0)
+ {
+ builder->RectsIndex.resize(builder->RectsIndex.Size + 1);
+ index_idx = builder->RectsIndex.Size - 1;
+ index_entry = &builder->RectsIndex[index_idx];
+ memset(index_entry, 0, sizeof(*index_entry));
+ }
+ else
+ {
+ index_idx = builder->RectsIndexFreeListStart;
+ index_entry = &builder->RectsIndex[index_idx];
+ IM_ASSERT(index_entry->IsUsed == false && index_entry->Generation > 0); // Generation is incremented during DiscardRect
+ builder->RectsIndexFreeListStart = index_entry->TargetIndex;
+ }
+ index_entry->TargetIndex = rect_idx;
+ index_entry->IsUsed = 1;
+ return ImFontAtlasRectId_Make(index_idx, index_entry->Generation);
+}
- for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++)
+// Overwrite existing entry
+static ImFontAtlasRectId ImFontAtlasPackReuseRectEntry(ImFontAtlas* atlas, ImFontAtlasRectEntry* index_entry)
+{
+ IM_ASSERT(index_entry->IsUsed);
+ index_entry->TargetIndex = atlas->Builder->Rects.Size - 1;
+ int index_idx = atlas->Builder->RectsIndex.index_from_ptr(index_entry);
+ return ImFontAtlasRectId_Make(index_idx, index_entry->Generation);
+}
+
+// This is expected to be called in batches and followed by a repack
+void ImFontAtlasPackDiscardRect(ImFontAtlas* atlas, ImFontAtlasRectId id)
+{
+ IM_ASSERT(id != ImFontAtlasRectId_Invalid);
+
+ ImTextureRect* rect = ImFontAtlasPackGetRect(atlas, id);
+ if (rect == NULL)
+ return;
+
+ ImFontAtlasBuilder* builder = atlas->Builder;
+ int index_idx = ImFontAtlasRectId_GetIndex(id);
+ ImFontAtlasRectEntry* index_entry = &builder->RectsIndex[index_idx];
+ IM_ASSERT(index_entry->IsUsed && index_entry->TargetIndex >= 0);
+ index_entry->IsUsed = false;
+ index_entry->TargetIndex = builder->RectsIndexFreeListStart;
+ index_entry->Generation++;
+ if (index_entry->Generation == 0)
+ index_entry->Generation++; // Keep non-zero on overflow
+
+ const int pack_padding = atlas->TexGlyphPadding;
+ builder->RectsIndexFreeListStart = index_idx;
+ builder->RectsDiscardedCount++;
+ builder->RectsDiscardedSurface += (rect->w + pack_padding) * (rect->h + pack_padding);
+ rect->w = rect->h = 0; // Clear rectangle so it won't be packed again
+}
+
+// Important: Calling this may recreate a new texture and therefore change atlas->TexData
+// FIXME-NEWFONTS: Expose other glyph padding settings for custom alteration (e.g. drop shadows). See #7962
+ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFontAtlasRectEntry* overwrite_entry)
+{
+ IM_ASSERT(w > 0 && w <= 0xFFFF);
+ IM_ASSERT(h > 0 && h <= 0xFFFF);
+
+ ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder;
+ const int pack_padding = atlas->TexGlyphPadding;
+ builder->MaxRectSize.x = ImMax(builder->MaxRectSize.x, w);
+ builder->MaxRectSize.y = ImMax(builder->MaxRectSize.y, h);
+
+ // Pack
+ ImTextureRect r = { 0, 0, (unsigned short)w, (unsigned short)h };
+ for (int attempts_remaining = 3; attempts_remaining >= 0; attempts_remaining--)
+ {
+ // Try packing
+ stbrp_rect pack_r = {};
+ pack_r.w = w + pack_padding;
+ pack_r.h = h + pack_padding;
+ stbrp_pack_rects((stbrp_context*)(void*)&builder->PackContext, &pack_r, 1);
+ r.x = (unsigned short)pack_r.x;
+ r.y = (unsigned short)pack_r.y;
+ if (pack_r.was_packed)
+ break;
+
+ // If we ran out of attempts, return fallback
+ if (attempts_remaining == 0 || builder->LockDisableResize)
{
- // Register glyph
- const int codepoint = src_tmp.GlyphsList[glyph_i];
- const stbtt_packedchar& pc = src_tmp.PackedChars[glyph_i];
- stbtt_aligned_quad q;
- 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);
- float x0 = q.x0 * inv_rasterization_scale + font_off_x;
- float y0 = q.y0 * inv_rasterization_scale + font_off_y;
- float x1 = q.x1 * inv_rasterization_scale + font_off_x;
- float y1 = q.y1 * inv_rasterization_scale + font_off_y;
- dst_font->AddGlyph(&cfg, (ImWchar)codepoint, x0, y0, x1, y1, q.s0, q.t0, q.s1, q.t1, pc.xadvance * inv_rasterization_scale);
+ IMGUI_DEBUG_LOG_FONT("[font] Failed packing %dx%d rectangle. Returning fallback.\n", w, h);
+ return ImFontAtlasRectId_Invalid;
}
+
+ // Resize or repack atlas! (this should be a rare event)
+ ImFontAtlasTextureMakeSpace(atlas);
}
- // Cleanup
- src_tmp_array.clear_destruct();
+ builder->MaxRectBounds.x = ImMax(builder->MaxRectBounds.x, r.x + r.w + pack_padding);
+ builder->MaxRectBounds.y = ImMax(builder->MaxRectBounds.y, r.y + r.h + pack_padding);
+ builder->RectsPackedCount++;
+ builder->RectsPackedSurface += (w + pack_padding) * (h + pack_padding);
- ImFontAtlasBuildFinish(atlas);
+ builder->Rects.push_back(r);
+ if (overwrite_entry != NULL)
+ return ImFontAtlasPackReuseRectEntry(atlas, overwrite_entry); // Write into an existing entry instead of adding one (used during repack)
+ else
+ return ImFontAtlasPackAllocRectEntry(atlas, builder->Rects.Size - 1);
+}
+
+// Generally for non-user facing functions: assert on invalid ID.
+ImTextureRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id)
+{
+ IM_ASSERT(id != ImFontAtlasRectId_Invalid);
+ int index_idx = ImFontAtlasRectId_GetIndex(id);
+ ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder;
+ ImFontAtlasRectEntry* index_entry = &builder->RectsIndex[index_idx];
+ IM_ASSERT(index_entry->Generation == ImFontAtlasRectId_GetGeneration(id));
+ IM_ASSERT(index_entry->IsUsed);
+ return &builder->Rects[index_entry->TargetIndex];
+}
+
+// For user-facing functions: return NULL on invalid ID.
+// Important: return pointer is valid until next call to AddRect(), e.g. FindGlyph(), CalcTextSize() can all potentially invalidate previous pointers.
+ImTextureRect* ImFontAtlasPackGetRectSafe(ImFontAtlas* atlas, ImFontAtlasRectId id)
+{
+ if (id == ImFontAtlasRectId_Invalid)
+ return NULL;
+ int index_idx = ImFontAtlasRectId_GetIndex(id);
+ if (atlas->Builder == NULL)
+ ImFontAtlasBuildInit(atlas);
+ ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder;
+ IM_MSVC_WARNING_SUPPRESS(28182); // Static Analysis false positive "warning C28182: Dereferencing NULL pointer 'builder'"
+ if (index_idx >= builder->RectsIndex.Size)
+ return NULL;
+ ImFontAtlasRectEntry* index_entry = &builder->RectsIndex[index_idx];
+ if (index_entry->Generation != ImFontAtlasRectId_GetGeneration(id) || !index_entry->IsUsed)
+ return NULL;
+ return &builder->Rects[index_entry->TargetIndex];
+}
+
+// Important! This assume by ImFontConfig::GlyphExcludeRanges[] is a SMALL ARRAY (e.g. <10 entries)
+// Use "Input Glyphs Overlap Detection Tool" to display a list of glyphs provided by multiple sources in order to set this array up.
+static bool ImFontAtlasBuildAcceptCodepointForSource(ImFontConfig* src, ImWchar codepoint)
+{
+ if (const ImWchar* exclude_list = src->GlyphExcludeRanges)
+ for (; exclude_list[0] != 0; exclude_list += 2)
+ if (codepoint >= exclude_list[0] && codepoint <= exclude_list[1])
+ return false;
return true;
}
-const ImFontBuilderIO* ImFontAtlasGetBuilderForStbTruetype()
+static void ImFontBaked_BuildGrowIndex(ImFontBaked* baked, int new_size)
{
- static ImFontBuilderIO io;
- io.FontBuilder_Build = ImFontAtlasBuildWithStbTruetype;
- return &io;
+ IM_ASSERT(baked->IndexAdvanceX.Size == baked->IndexLookup.Size);
+ if (new_size <= baked->IndexLookup.Size)
+ return;
+ baked->IndexAdvanceX.resize(new_size, -1.0f);
+ baked->IndexLookup.resize(new_size, IM_FONTGLYPH_INDEX_UNUSED);
}
-#endif // IMGUI_ENABLE_STB_TRUETYPE
+static void ImFontAtlas_FontHookRemapCodepoint(ImFontAtlas* atlas, ImFont* font, ImWchar* c)
+{
+ IM_UNUSED(atlas);
+ if (font->RemapPairs.Data.Size != 0)
+ *c = (ImWchar)font->RemapPairs.GetInt((ImGuiID)*c, (int)*c);
+}
-void ImFontAtlasUpdateConfigDataPointers(ImFontAtlas* atlas)
+static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codepoint, float* only_load_advance_x)
{
- for (ImFontConfig& font_cfg : atlas->ConfigData)
+ ImFont* font = baked->ContainerFont;
+ ImFontAtlas* atlas = font->ContainerAtlas;
+ if (atlas->Locked || (font->Flags & ImFontFlags_NoLoadGlyphs))
{
- ImFont* font = font_cfg.DstFont;
- if (!font_cfg.MergeMode)
+ // Lazily load fallback glyph
+ if (baked->FallbackGlyphIndex == -1 && baked->LoadNoFallback == 0)
+ ImFontAtlasBuildSetupFontBakedFallback(baked);
+ return NULL;
+ }
+
+ // User remapping hooks
+ ImWchar src_codepoint = codepoint;
+ ImFontAtlas_FontHookRemapCodepoint(atlas, font, &codepoint);
+
+ //char utf8_buf[5];
+ //IMGUI_DEBUG_LOG("[font] BuildLoadGlyph U+%04X (%s)\n", (unsigned int)codepoint, ImTextCharToUtf8(utf8_buf, (unsigned int)codepoint));
+
+ // Special hook
+ // FIXME-NEWATLAS: it would be nicer if this used a more standardized way of hooking
+ if (codepoint == font->EllipsisChar && font->EllipsisAutoBake)
+ if (ImFontGlyph* glyph = ImFontAtlasBuildSetupFontBakedEllipsis(atlas, baked))
+ return glyph;
+
+ // Call backend
+ char* loader_user_data_p = (char*)baked->FontLoaderDatas;
+ int src_n = 0;
+ for (ImFontConfig* src : font->Sources)
+ {
+ const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader;
+ if (!src->GlyphExcludeRanges || ImFontAtlasBuildAcceptCodepointForSource(src, codepoint))
{
- font->ConfigData = &font_cfg;
- font->ConfigDataCount = 0;
+ if (only_load_advance_x == NULL)
+ {
+ ImFontGlyph glyph_buf;
+ if (loader->FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint, &glyph_buf, NULL))
+ {
+ // FIXME: Add hooks for e.g. #7962
+ glyph_buf.Codepoint = src_codepoint;
+ glyph_buf.SourceIdx = src_n;
+ return ImFontAtlasBakedAddFontGlyph(atlas, baked, src, &glyph_buf);
+ }
+ }
+ else
+ {
+ // Special mode but only loading glyphs metrics. Will rasterize and pack later.
+ if (loader->FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint, NULL, only_load_advance_x))
+ {
+ ImFontAtlasBakedAddFontGlyphAdvancedX(atlas, baked, src, codepoint, *only_load_advance_x);
+ return NULL;
+ }
+ }
}
- font->ConfigDataCount++;
+ loader_user_data_p += loader->FontBakedSrcLoaderDataSize;
+ src_n++;
+ }
+
+ // Lazily load fallback glyph
+ if (baked->LoadNoFallback)
+ return NULL;
+ if (baked->FallbackGlyphIndex == -1)
+ ImFontAtlasBuildSetupFontBakedFallback(baked);
+
+ // Mark index as not found, so we don't attempt the search twice
+ ImFontBaked_BuildGrowIndex(baked, codepoint + 1);
+ baked->IndexAdvanceX[codepoint] = baked->FallbackAdvanceX;
+ baked->IndexLookup[codepoint] = IM_FONTGLYPH_INDEX_NOT_FOUND;
+ return NULL;
+}
+
+static float ImFontBaked_BuildLoadGlyphAdvanceX(ImFontBaked* baked, ImWchar codepoint)
+{
+ if (baked->Size >= IMGUI_FONT_SIZE_THRESHOLD_FOR_LOADADVANCEXONLYMODE || baked->LoadNoRenderOnLayout)
+ {
+ // First load AdvanceX value used by CalcTextSize() API then load the rest when loaded by drawing API.
+ float only_advance_x = 0.0f;
+ ImFontGlyph* glyph = ImFontBaked_BuildLoadGlyph(baked, (ImWchar)codepoint, &only_advance_x);
+ return glyph ? glyph->AdvanceX : only_advance_x;
+ }
+ else
+ {
+ ImFontGlyph* glyph = ImFontBaked_BuildLoadGlyph(baked, (ImWchar)codepoint, NULL);
+ return glyph ? glyph->AdvanceX : baked->FallbackAdvanceX;
}
}
-void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent)
+// The point of this indirection is to not be inlined in debug mode in order to not bloat inner loop.b
+IM_MSVC_RUNTIME_CHECKS_OFF
+static float BuildLoadGlyphGetAdvanceOrFallback(ImFontBaked* baked, unsigned int codepoint)
{
- if (!font_config->MergeMode)
- {
- font->ClearOutputData();
- font->FontSize = font_config->SizePixels;
- IM_ASSERT(font->ConfigData == font_config);
- font->ContainerAtlas = atlas;
- font->Ascent = ascent;
- font->Descent = descent;
- }
+ return ImFontBaked_BuildLoadGlyphAdvanceX(baked, (ImWchar)codepoint);
}
+IM_MSVC_RUNTIME_CHECKS_RESTORE
-void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opaque)
+#ifndef IMGUI_DISABLE_DEBUG_TOOLS
+void ImFontAtlasDebugLogTextureRequests(ImFontAtlas* atlas)
{
- stbrp_context* pack_context = (stbrp_context*)stbrp_context_opaque;
- IM_ASSERT(pack_context != NULL);
-
- ImVector<ImFontAtlasCustomRect>& user_rects = atlas->CustomRects;
- IM_ASSERT(user_rects.Size >= 1); // We expect at least the default custom rects to be registered, else something went wrong.
-#ifdef __GNUC__
- if (user_rects.Size < 1) { __builtin_unreachable(); } // Workaround for GCC bug if IM_ASSERT() is defined to conditionally throw (see #5343)
-#endif
-
- ImVector<stbrp_rect> pack_rects;
- pack_rects.resize(user_rects.Size);
- memset(pack_rects.Data, 0, (size_t)pack_rects.size_in_bytes());
- for (int i = 0; i < user_rects.Size; i++)
+ // [DEBUG] Log texture update requests
+ ImGuiContext& g = *GImGui;
+ IM_UNUSED(g);
+ for (ImTextureData* tex : atlas->TexList)
{
- pack_rects[i].w = user_rects[i].Width;
- pack_rects[i].h = user_rects[i].Height;
- }
- stbrp_pack_rects(pack_context, &pack_rects[0], pack_rects.Size);
- for (int i = 0; i < pack_rects.Size; i++)
- if (pack_rects[i].was_packed)
+ if ((g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0)
+ IM_ASSERT(tex->Updates.Size == 0);
+ if (tex->Status == ImTextureStatus_WantCreate)
+ IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: create %dx%d\n", tex->UniqueID, tex->Width, tex->Height);
+ else if (tex->Status == ImTextureStatus_WantDestroy)
+ IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: destroy %dx%d, texid=0x%" IM_PRIX64 ", backend_data=%p\n", tex->UniqueID, tex->Width, tex->Height, IM_TEXTUREID_TO_U64(tex->TexID), tex->BackendUserData);
+ else if (tex->Status == ImTextureStatus_WantUpdates)
{
- user_rects[i].X = (unsigned short)pack_rects[i].x;
- user_rects[i].Y = (unsigned short)pack_rects[i].y;
- IM_ASSERT(pack_rects[i].w == user_rects[i].Width && pack_rects[i].h == user_rects[i].Height);
- atlas->TexHeight = ImMax(atlas->TexHeight, pack_rects[i].y + pack_rects[i].h);
+ IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: update %d regions, texid=0x%" IM_PRIX64 ", backend_data=0x%" IM_PRIX64 "\n", tex->UniqueID, tex->Updates.Size, IM_TEXTUREID_TO_U64(tex->TexID), (ImU64)(intptr_t)tex->BackendUserData);
+ for (const ImTextureRect& r : tex->Updates)
+ {
+ IM_UNUSED(r);
+ IM_ASSERT(r.x >= 0 && r.y >= 0);
+ IM_ASSERT(r.x + r.w <= tex->Width && r.y + r.h <= tex->Height); // In theory should subtract PackPadding but it's currently part of atlas and mid-frame change would wreck assert.
+ //IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: update (% 4d..%-4d)->(% 4d..%-4d), texid=0x%" IM_PRIX64 ", backend_data=0x%" IM_PRIX64 "\n", tex->UniqueID, r.x, r.y, r.x + r.w, r.y + r.h, IM_TEXTUREID_TO_U64(tex->TexID), (ImU64)(intptr_t)tex->BackendUserData);
+ }
}
+ }
}
+#endif
-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;
-}
+//-------------------------------------------------------------------------
+// [SECTION] ImFontAtlas: backend for stb_truetype
+//-------------------------------------------------------------------------
+// (imstb_truetype.h in included near the top of this file, when IMGUI_ENABLE_STB_TRUETYPE is set)
+//-------------------------------------------------------------------------
+
+#ifdef IMGUI_ENABLE_STB_TRUETYPE
-void ImFontAtlasBuildRender32bppRectFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char, unsigned int in_marker_pixel_value)
+// One for each ConfigData
+struct ImGui_ImplStbTrueType_FontSrcData
{
- IM_ASSERT(x >= 0 && x + w <= atlas->TexWidth);
- IM_ASSERT(y >= 0 && y + h <= atlas->TexHeight);
- unsigned int* out_pixel = atlas->TexPixelsRGBA32 + 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 : IM_COL32_BLACK_TRANS;
-}
+ stbtt_fontinfo FontInfo;
+ float ScaleFactor;
+};
-static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas)
+static bool ImGui_ImplStbTrueType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* src)
{
- ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(atlas->PackIdMouseCursors);
- IM_ASSERT(r->IsPacked());
+ IM_UNUSED(atlas);
+
+ ImGui_ImplStbTrueType_FontSrcData* bd_font_data = IM_NEW(ImGui_ImplStbTrueType_FontSrcData);
+ IM_ASSERT(src->FontLoaderData == NULL);
- const int w = atlas->TexWidth;
- if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors))
+ // Initialize helper structure for font loading and verify that the TTF/OTF data is correct
+ const int font_offset = stbtt_GetFontOffsetForIndex((unsigned char*)src->FontData, src->FontNo);
+ if (font_offset < 0)
{
- // Render/copy pixels
- 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;
- if (atlas->TexPixelsAlpha8 != NULL)
- {
- 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
- {
- ImFontAtlasBuildRender32bppRectFromString(atlas, x_for_white, r->Y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, '.', IM_COL32_WHITE);
- ImFontAtlasBuildRender32bppRectFromString(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', IM_COL32_WHITE);
- }
+ IM_DELETE(bd_font_data);
+ IM_ASSERT_USER_ERROR(0, "stbtt_GetFontOffsetForIndex(): FontData is incorrect, or FontNo cannot be found.");
+ return false;
}
- else
+ if (!stbtt_InitFont(&bd_font_data->FontInfo, (unsigned char*)src->FontData, font_offset))
{
- // Render 4 white pixels
- IM_ASSERT(r->Width == 2 && r->Height == 2);
- const int offset = (int)r->X + (int)r->Y * w;
- if (atlas->TexPixelsAlpha8 != NULL)
- {
- atlas->TexPixelsAlpha8[offset] = atlas->TexPixelsAlpha8[offset + 1] = atlas->TexPixelsAlpha8[offset + w] = atlas->TexPixelsAlpha8[offset + w + 1] = 0xFF;
- }
- else
- {
- atlas->TexPixelsRGBA32[offset] = atlas->TexPixelsRGBA32[offset + 1] = atlas->TexPixelsRGBA32[offset + w] = atlas->TexPixelsRGBA32[offset + w + 1] = IM_COL32_WHITE;
- }
+ IM_DELETE(bd_font_data);
+ IM_ASSERT_USER_ERROR(0, "stbtt_InitFont(): failed to parse FontData. It is correct and complete? Check FontDataSize.");
+ return false;
}
- 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;
+ src->FontLoaderData = bd_font_data;
- // 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);
+ const float ref_size = src->DstFont->Sources[0]->SizePixels;
+ if (src->MergeMode && src->SizePixels == 0.0f)
+ src->SizePixels = ref_size;
- // 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
- if (atlas->TexPixelsAlpha8 != NULL)
- {
- unsigned char* write_ptr = &atlas->TexPixelsAlpha8[r->X + ((r->Y + y) * atlas->TexWidth)];
- for (unsigned int i = 0; i < pad_left; i++)
- *(write_ptr + i) = 0x00;
+ if (src->SizePixels >= 0.0f)
+ bd_font_data->ScaleFactor = stbtt_ScaleForPixelHeight(&bd_font_data->FontInfo, 1.0f);
+ else
+ bd_font_data->ScaleFactor = stbtt_ScaleForMappingEmToPixels(&bd_font_data->FontInfo, 1.0f);
+ if (src->MergeMode && src->SizePixels != 0.0f && ref_size != 0.0f)
+ bd_font_data->ScaleFactor *= src->SizePixels / ref_size; // FIXME-NEWATLAS: Should tidy up that a bit
- for (unsigned int i = 0; i < line_width; i++)
- *(write_ptr + pad_left + i) = 0xFF;
+ return true;
+}
- for (unsigned int i = 0; i < pad_right; i++)
- *(write_ptr + pad_left + line_width + i) = 0x00;
- }
- else
- {
- unsigned int* write_ptr = &atlas->TexPixelsRGBA32[r->X + ((r->Y + y) * atlas->TexWidth)];
- for (unsigned int i = 0; i < pad_left; i++)
- *(write_ptr + i) = IM_COL32(255, 255, 255, 0);
+static void ImGui_ImplStbTrueType_FontSrcDestroy(ImFontAtlas* atlas, ImFontConfig* src)
+{
+ IM_UNUSED(atlas);
+ ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData;
+ IM_DELETE(bd_font_data);
+ src->FontLoaderData = NULL;
+}
- for (unsigned int i = 0; i < line_width; i++)
- *(write_ptr + pad_left + i) = IM_COL32_WHITE;
+static bool ImGui_ImplStbTrueType_FontSrcContainsGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint)
+{
+ IM_UNUSED(atlas);
- for (unsigned int i = 0; i < pad_right; i++)
- *(write_ptr + pad_left + line_width + i) = IM_COL32(255, 255, 255, 0);
- }
+ ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData;
+ IM_ASSERT(bd_font_data != NULL);
- // 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);
- }
+ int glyph_index = stbtt_FindGlyphIndex(&bd_font_data->FontInfo, (int)codepoint);
+ return glyph_index != 0;
}
-// Note: this is called / shared by both the stb_truetype and the FreeType builder
-void ImFontAtlasBuildInit(ImFontAtlas* atlas)
+static bool ImGui_ImplStbTrueType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void*)
{
- // Round font size
- // - We started rounding in 1.90 WIP (18991) as our layout system currently doesn't support non-rounded font size well yet.
- // - Note that using io.FontGlobalScale or SetWindowFontScale(), with are legacy-ish, partially supported features, can still lead to unrounded sizes.
- // - We may support it better later and remove this rounding.
- for (ImFontConfig& cfg : atlas->ConfigData)
- cfg.SizePixels = ImTrunc(cfg.SizePixels);
-
- // 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);
- }
+ IM_UNUSED(atlas);
- // 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)
+ ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData;
+ if (src->MergeMode == false)
{
- if (!(atlas->Flags & ImFontAtlasFlags_NoBakedLines))
- atlas->PackIdLines = atlas->AddCustomRectRegular(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1);
+ // FIXME-NEWFONTS: reevaluate how to use sizing metrics
+ // FIXME-NEWFONTS: make use of line gap value
+ float scale_for_layout = bd_font_data->ScaleFactor * baked->Size;
+ int unscaled_ascent, unscaled_descent, unscaled_line_gap;
+ stbtt_GetFontVMetrics(&bd_font_data->FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap);
+ baked->Ascent = ImCeil(unscaled_ascent * scale_for_layout);
+ baked->Descent = ImFloor(unscaled_descent * scale_for_layout);
}
+ return true;
}
-// This is called/shared by both the stb_truetype and the FreeType builder.
-void ImFontAtlasBuildFinish(ImFontAtlas* atlas)
+static bool ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void*, ImWchar codepoint, ImFontGlyph* out_glyph, float* out_advance_x)
{
- // Render into our custom data blocks
- IM_ASSERT(atlas->TexPixelsAlpha8 != NULL || atlas->TexPixelsRGBA32 != NULL);
- ImFontAtlasBuildRenderDefaultTexData(atlas);
- ImFontAtlasBuildRenderLinesTexData(atlas);
+ // Search for first font which has the glyph
+ ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData;
+ IM_ASSERT(bd_font_data);
+ int glyph_index = stbtt_FindGlyphIndex(&bd_font_data->FontInfo, (int)codepoint);
+ if (glyph_index == 0)
+ return false;
- // Register custom rectangle glyphs
- for (int i = 0; i < atlas->CustomRects.Size; i++)
+ // Fonts unit to pixels
+ int oversample_h, oversample_v;
+ ImFontAtlasBuildGetOversampleFactors(src, baked, &oversample_h, &oversample_v);
+ const float scale_for_layout = bd_font_data->ScaleFactor * baked->Size;
+ const float rasterizer_density = src->RasterizerDensity * baked->RasterizerDensity;
+ const float scale_for_raster_x = bd_font_data->ScaleFactor * baked->Size * rasterizer_density * oversample_h;
+ const float scale_for_raster_y = bd_font_data->ScaleFactor * baked->Size * rasterizer_density * oversample_v;
+
+ // Obtain size and advance
+ int x0, y0, x1, y1;
+ int advance, lsb;
+ stbtt_GetGlyphBitmapBoxSubpixel(&bd_font_data->FontInfo, glyph_index, scale_for_raster_x, scale_for_raster_y, 0, 0, &x0, &y0, &x1, &y1);
+ stbtt_GetGlyphHMetrics(&bd_font_data->FontInfo, glyph_index, &advance, &lsb);
+
+ // Load metrics only mode
+ if (out_advance_x != NULL)
{
- const ImFontAtlasCustomRect* r = &atlas->CustomRects[i];
- if (r->Font == NULL || r->GlyphID == 0)
- continue;
+ IM_ASSERT(out_glyph == NULL);
+ *out_advance_x = advance * scale_for_layout;
+ return true;
+ }
+
+ // Prepare glyph
+ out_glyph->Codepoint = codepoint;
+ out_glyph->AdvanceX = advance * scale_for_layout;
- // 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(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);
+ // Pack and retrieve position inside texture atlas
+ // (generally based on stbtt_PackFontRangesRenderIntoRects)
+ const bool is_visible = (x0 != x1 && y0 != y1);
+ if (is_visible)
+ {
+ const int w = (x1 - x0 + oversample_h - 1);
+ const int h = (y1 - y0 + oversample_v - 1);
+ ImFontAtlasRectId pack_id = ImFontAtlasPackAddRect(atlas, w, h);
+ if (pack_id == ImFontAtlasRectId_Invalid)
+ {
+ // Pathological out of memory case (TexMaxWidth/TexMaxHeight set too small?)
+ IM_ASSERT(pack_id != ImFontAtlasRectId_Invalid && "Out of texture memory.");
+ return false;
+ }
+ ImTextureRect* r = ImFontAtlasPackGetRect(atlas, pack_id);
+
+ // Render
+ stbtt_GetGlyphBitmapBox(&bd_font_data->FontInfo, glyph_index, scale_for_raster_x, scale_for_raster_y, &x0, &y0, &x1, &y1);
+ ImFontAtlasBuilder* builder = atlas->Builder;
+ builder->TempBuffer.resize(w * h * 1);
+ unsigned char* bitmap_pixels = builder->TempBuffer.Data;
+ memset(bitmap_pixels, 0, w * h * 1);
+
+ // Render with oversampling
+ // (those functions conveniently assert if pixels are not cleared, which is another safety layer)
+ float sub_x, sub_y;
+ stbtt_MakeGlyphBitmapSubpixelPrefilter(&bd_font_data->FontInfo, bitmap_pixels, w, h, w,
+ scale_for_raster_x, scale_for_raster_y, 0, 0, oversample_h, oversample_v, &sub_x, &sub_y, glyph_index);
+
+ const float ref_size = baked->ContainerFont->Sources[0]->SizePixels;
+ const float offsets_scale = (ref_size != 0.0f) ? (baked->Size / ref_size) : 1.0f;
+ float font_off_x = (src->GlyphOffset.x * offsets_scale);
+ float font_off_y = (src->GlyphOffset.y * offsets_scale);
+ if (src->PixelSnapH) // Snap scaled offset. This is to mitigate backward compatibility issues for GlyphOffset, but a better design would be welcome.
+ font_off_x = IM_ROUND(font_off_x);
+ if (src->PixelSnapV)
+ font_off_y = IM_ROUND(font_off_y);
+ font_off_x += sub_x;
+ font_off_y += sub_y + IM_ROUND(baked->Ascent);
+ float recip_h = 1.0f / (oversample_h * rasterizer_density);
+ float recip_v = 1.0f / (oversample_v * rasterizer_density);
+
+ // Register glyph
+ // r->x r->y are coordinates inside texture (in pixels)
+ // glyph.X0, glyph.Y0 are drawing coordinates from base text position, and accounting for oversampling.
+ out_glyph->X0 = x0 * recip_h + font_off_x;
+ out_glyph->Y0 = y0 * recip_v + font_off_y;
+ out_glyph->X1 = (x0 + (int)r->w) * recip_h + font_off_x;
+ out_glyph->Y1 = (y0 + (int)r->h) * recip_v + font_off_y;
+ out_glyph->Visible = true;
+ out_glyph->PackId = pack_id;
+ ImFontAtlasBakedSetFontGlyphBitmap(atlas, baked, src, out_glyph, r, bitmap_pixels, ImTextureFormat_Alpha8, w);
}
- // Build all fonts lookup tables
- for (ImFont* font : atlas->Fonts)
- if (font->DirtyLookupTables)
- font->BuildLookupTable();
+ return true;
+}
- atlas->TexReady = true;
+const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype()
+{
+ static ImFontLoader loader;
+ loader.Name = "stb_truetype";
+ loader.FontSrcInit = ImGui_ImplStbTrueType_FontSrcInit;
+ loader.FontSrcDestroy = ImGui_ImplStbTrueType_FontSrcDestroy;
+ loader.FontSrcContainsGlyph = ImGui_ImplStbTrueType_FontSrcContainsGlyph;
+ loader.FontBakedInit = ImGui_ImplStbTrueType_FontBakedInit;
+ loader.FontBakedDestroy = NULL;
+ loader.FontBakedLoadGlyph = ImGui_ImplStbTrueType_FontBakedLoadGlyph;
+ return &loader;
}
+#endif // IMGUI_ENABLE_STB_TRUETYPE
+
+//-------------------------------------------------------------------------
+// [SECTION] ImFontAtlas: glyph ranges helpers
+//-------------------------------------------------------------------------
+// - GetGlyphRangesDefault()
+// Obsolete functions since 1.92:
+// - GetGlyphRangesGreek()
+// - GetGlyphRangesKorean()
+// - GetGlyphRangesChineseFull()
+// - GetGlyphRangesChineseSimplifiedCommon()
+// - GetGlyphRangesJapanese()
+// - GetGlyphRangesCyrillic()
+// - GetGlyphRangesThai()
+// - GetGlyphRangesVietnamese()
+//-----------------------------------------------------------------------------
+
// Retrieve list of range (2 int per range, values are inclusive)
const ImWchar* ImFontAtlas::GetGlyphRangesDefault()
{
@@ -3312,6 +4763,7 @@ const ImWchar* ImFontAtlas::GetGlyphRangesDefault()
return &ranges[0];
}
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
const ImWchar* ImFontAtlas::GetGlyphRangesGreek()
{
static const ImWchar ranges[] =
@@ -3362,10 +4814,6 @@ static void UnpackAccumulativeOffsetsIntoRanges(int base_codepoint, const short*
out_ranges[0] = 0;
}
-//-------------------------------------------------------------------------
-// [SECTION] ImFontAtlas glyph ranges helpers
-//-------------------------------------------------------------------------
-
const ImWchar* ImFontAtlas::GetGlyphRangesChineseSimplifiedCommon()
{
// Store 2500 regularly used characters for Simplified Chinese.
@@ -3565,6 +5013,7 @@ const ImWchar* ImFontAtlas::GetGlyphRangesVietnamese()
};
return &ranges[0];
}
+#endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
//-----------------------------------------------------------------------------
// [SECTION] ImFontGlyphRangesBuilder
@@ -3608,251 +5057,301 @@ void ImFontGlyphRangesBuilder::BuildRanges(ImVector<ImWchar>* out_ranges)
// [SECTION] ImFont
//-----------------------------------------------------------------------------
-ImFont::ImFont()
-{
- FontSize = 0.0f;
- FallbackAdvanceX = 0.0f;
- FallbackChar = (ImWchar)-1;
- EllipsisChar = (ImWchar)-1;
- EllipsisWidth = EllipsisCharStep = 0.0f;
- EllipsisCharCount = 0;
- FallbackGlyph = NULL;
- ContainerAtlas = NULL;
- ConfigData = NULL;
- ConfigDataCount = 0;
- DirtyLookupTables = false;
- Scale = 1.0f;
- Ascent = Descent = 0.0f;
- MetricsTotalSurface = 0;
- memset(Used4kPagesMap, 0, sizeof(Used4kPagesMap));
-}
-
-ImFont::~ImFont()
+ImFontBaked::ImFontBaked()
{
- ClearOutputData();
+ memset(this, 0, sizeof(*this));
+ FallbackGlyphIndex = -1;
}
-void ImFont::ClearOutputData()
+void ImFontBaked::ClearOutputData()
{
- FontSize = 0.0f;
FallbackAdvanceX = 0.0f;
Glyphs.clear();
IndexAdvanceX.clear();
IndexLookup.clear();
- FallbackGlyph = NULL;
- ContainerAtlas = NULL;
- DirtyLookupTables = true;
+ FallbackGlyphIndex = -1;
Ascent = Descent = 0.0f;
MetricsTotalSurface = 0;
}
-static ImWchar FindFirstExistingGlyph(ImFont* font, const ImWchar* candidate_chars, int candidate_chars_count)
+ImFont::ImFont()
{
- for (int n = 0; n < candidate_chars_count; n++)
- if (font->FindGlyphNoFallback(candidate_chars[n]) != NULL)
- return candidate_chars[n];
- return (ImWchar)-1;
+ memset(this, 0, sizeof(*this));
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ Scale = 1.0f;
+#endif
}
-void ImFont::BuildLookupTable()
+ImFont::~ImFont()
{
- int max_codepoint = 0;
- for (int i = 0; i != Glyphs.Size; i++)
- max_codepoint = ImMax(max_codepoint, (int)Glyphs[i].Codepoint);
+ ClearOutputData();
+}
- // Build lookup table
- IM_ASSERT(Glyphs.Size > 0 && "Font has not loaded glyph!");
- 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;
+void ImFont::ClearOutputData()
+{
+ if (ImFontAtlas* atlas = ContainerAtlas)
+ ImFontAtlasFontDiscardBakes(atlas, this, 0);
+ FallbackChar = EllipsisChar = 0;
+ memset(Used8kPagesMap, 0, sizeof(Used8kPagesMap));
+ LastBaked = NULL;
+}
- // Mark 4K page as used
- const int page_n = codepoint / 4096;
- Used4kPagesMap[page_n >> 3] |= 1 << (page_n & 7);
- }
+// API is designed this way to avoid exposing the 8K 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 / 8192);
+ unsigned int page_last = (c_last / 8192);
+ for (unsigned int page_n = page_begin; page_n <= page_last; page_n++)
+ if ((page_n >> 3) < sizeof(Used8kPagesMap))
+ if (Used8kPagesMap[page_n >> 3] & (1 << (page_n & 7)))
+ return false;
+ return true;
+}
- // 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)' '))
+// 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).
+// - 'src' is not necessarily == 'this->Sources' because multiple source fonts+configs can be used to build one target font.
+ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, const ImFontGlyph* in_glyph)
+{
+ int glyph_idx = baked->Glyphs.Size;
+ baked->Glyphs.push_back(*in_glyph);
+ ImFontGlyph* glyph = &baked->Glyphs[glyph_idx];
+ IM_ASSERT(baked->Glyphs.Size < 0xFFFE); // IndexLookup[] hold 16-bit values and -1/-2 are reserved.
+
+ // Set UV from packed rectangle
+ if (glyph->PackId != ImFontAtlasRectId_Invalid)
{
- 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);
+ ImTextureRect* r = ImFontAtlasPackGetRect(atlas, glyph->PackId);
+ IM_ASSERT(glyph->U0 == 0.0f && glyph->V0 == 0.0f && glyph->U1 == 0.0f && glyph->V1 == 0.0f);
+ glyph->U0 = (r->x) * atlas->TexUvScale.x;
+ glyph->V0 = (r->y) * atlas->TexUvScale.y;
+ glyph->U1 = (r->x + r->w) * atlas->TexUvScale.x;
+ glyph->V1 = (r->y + r->h) * atlas->TexUvScale.y;
+ baked->MetricsTotalSurface += r->w * r->h;
}
- // 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 Fallback character
- const ImWchar fallback_chars[] = { (ImWchar)IM_UNICODE_CODEPOINT_INVALID, (ImWchar)'?', (ImWchar)' ' };
- FallbackGlyph = FindGlyphNoFallback(FallbackChar);
- if (FallbackGlyph == NULL)
+ if (src != NULL)
{
- FallbackChar = FindFirstExistingGlyph(this, fallback_chars, IM_ARRAYSIZE(fallback_chars));
- FallbackGlyph = FindGlyphNoFallback(FallbackChar);
- if (FallbackGlyph == NULL)
+ // Clamp & recenter if needed
+ const float ref_size = baked->ContainerFont->Sources[0]->SizePixels;
+ const float offsets_scale = (ref_size != 0.0f) ? (baked->Size / ref_size) : 1.0f;
+ float advance_x = ImClamp(glyph->AdvanceX, src->GlyphMinAdvanceX * offsets_scale, src->GlyphMaxAdvanceX * offsets_scale);
+ if (advance_x != glyph->AdvanceX)
{
- FallbackGlyph = &Glyphs.back();
- FallbackChar = (ImWchar)FallbackGlyph->Codepoint;
+ float char_off_x = src->PixelSnapH ? ImTrunc((advance_x - glyph->AdvanceX) * 0.5f) : (advance_x - glyph->AdvanceX) * 0.5f;
+ glyph->X0 += char_off_x;
+ glyph->X1 += char_off_x;
}
- }
- FallbackAdvanceX = FallbackGlyph->AdvanceX;
- for (int i = 0; i < max_codepoint + 1; i++)
- if (IndexAdvanceX[i] < 0.0f)
- IndexAdvanceX[i] = FallbackAdvanceX;
- // Setup Ellipsis character. It 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: Note that 0x2026 is rarely included in our font ranges. Because of this we are more likely to use three individual dots.
- const ImWchar ellipsis_chars[] = { (ImWchar)0x2026, (ImWchar)0x0085 };
- const ImWchar dots_chars[] = { (ImWchar)'.', (ImWchar)0xFF0E };
- if (EllipsisChar == (ImWchar)-1)
- EllipsisChar = FindFirstExistingGlyph(this, ellipsis_chars, IM_ARRAYSIZE(ellipsis_chars));
- const ImWchar dot_char = FindFirstExistingGlyph(this, dots_chars, IM_ARRAYSIZE(dots_chars));
- if (EllipsisChar != (ImWchar)-1)
- {
- EllipsisCharCount = 1;
- EllipsisWidth = EllipsisCharStep = FindGlyph(EllipsisChar)->X1;
+ // Snap to pixel
+ if (src->PixelSnapH)
+ advance_x = IM_ROUND(advance_x);
+
+ // Bake spacing
+ glyph->AdvanceX = advance_x + src->GlyphExtraAdvanceX;
}
- else if (dot_char != (ImWchar)-1)
+ if (glyph->Colored)
+ atlas->TexPixelsUseColors = atlas->TexData->UseColors = true;
+
+ // Update lookup tables
+ const int codepoint = glyph->Codepoint;
+ ImFontBaked_BuildGrowIndex(baked, codepoint + 1);
+ baked->IndexAdvanceX[codepoint] = glyph->AdvanceX;
+ baked->IndexLookup[codepoint] = (ImU16)glyph_idx;
+ const int page_n = codepoint / 8192;
+ baked->ContainerFont->Used8kPagesMap[page_n >> 3] |= 1 << (page_n & 7);
+
+ return glyph;
+}
+
+// FIXME: Code is duplicated with code above.
+void ImFontAtlasBakedAddFontGlyphAdvancedX(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImWchar codepoint, float advance_x)
+{
+ IM_UNUSED(atlas);
+ if (src != NULL)
{
- const ImFontGlyph* glyph = FindGlyph(dot_char);
- EllipsisChar = dot_char;
- EllipsisCharCount = 3;
- EllipsisCharStep = (glyph->X1 - glyph->X0) + 1.0f;
- EllipsisWidth = EllipsisCharStep * 3.0f - 1.0f;
+ // Clamp & recenter if needed
+ const float ref_size = baked->ContainerFont->Sources[0]->SizePixels;
+ const float offsets_scale = (ref_size != 0.0f) ? (baked->Size / ref_size) : 1.0f;
+ advance_x = ImClamp(advance_x, src->GlyphMinAdvanceX * offsets_scale, src->GlyphMaxAdvanceX * offsets_scale);
+
+ // Snap to pixel
+ if (src->PixelSnapH)
+ advance_x = IM_ROUND(advance_x);
+
+ // Bake spacing
+ advance_x += src->GlyphExtraAdvanceX;
}
+
+ ImFontBaked_BuildGrowIndex(baked, codepoint + 1);
+ baked->IndexAdvanceX[codepoint] = advance_x;
}
-// 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)
+// Copy to texture, post-process and queue update for backend
+void ImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImFontGlyph* glyph, ImTextureRect* r, const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch)
{
- 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;
+ ImTextureData* tex = atlas->TexData;
+ IM_ASSERT(r->x + r->w <= tex->Width && r->y + r->h <= tex->Height);
+ ImFontAtlasTextureBlockConvert(src_pixels, src_fmt, src_pitch, (unsigned char*)tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), r->w, r->h);
+ ImFontAtlasPostProcessData pp_data = { atlas, baked->ContainerFont, src, baked, glyph, tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), r->w, r->h };
+ ImFontAtlasTextureBlockPostProcess(&pp_data);
+ ImFontAtlasTextureBlockQueueUpload(atlas, tex, r->x, r->y, r->w, r->h);
}
-void ImFont::SetGlyphVisible(ImWchar c, bool visible)
+void ImFont::AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint)
{
- if (ImFontGlyph* glyph = (ImFontGlyph*)(void*)FindGlyph((ImWchar)c))
- glyph->Visible = visible ? 1 : 0;
+ RemapPairs.SetInt((ImGuiID)from_codepoint, (int)to_codepoint);
}
-void ImFont::GrowIndex(int new_size)
+// Find glyph, load if necessary, return fallback if missing
+ImFontGlyph* ImFontBaked::FindGlyph(ImWchar c)
{
- IM_ASSERT(IndexAdvanceX.Size == IndexLookup.Size);
- if (new_size <= IndexLookup.Size)
- return;
- IndexAdvanceX.resize(new_size, -1.0f);
- IndexLookup.resize(new_size, (ImWchar)-1);
+ if (c < (size_t)IndexLookup.Size) IM_LIKELY
+ {
+ const int i = (int)IndexLookup.Data[c];
+ if (i == IM_FONTGLYPH_INDEX_NOT_FOUND)
+ return &Glyphs.Data[FallbackGlyphIndex];
+ if (i != IM_FONTGLYPH_INDEX_UNUSED)
+ return &Glyphs.Data[i];
+ }
+ ImFontGlyph* glyph = ImFontBaked_BuildLoadGlyph(this, c, NULL);
+ return glyph ? glyph : &Glyphs.Data[FallbackGlyphIndex];
}
-// 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).
-// '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)
+// Attempt to load but when missing, return NULL instead of FallbackGlyph
+ImFontGlyph* ImFontBaked::FindGlyphNoFallback(ImWchar c)
{
- if (cfg != NULL)
+ if (c < (size_t)IndexLookup.Size) IM_LIKELY
{
- // 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 ? ImTrunc((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 = (unsigned int)codepoint;
- glyph.Visible = (x0 != x1) && (y0 != y1);
- glyph.Colored = false;
- glyph.X0 = x0;
- glyph.Y0 = y0;
- glyph.X1 = x1;
- glyph.Y1 = y1;
- glyph.U0 = u0;
- glyph.V0 = v0;
- glyph.U1 = u1;
- glyph.V1 = v1;
- 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 + pad) * (int)((glyph.V1 - glyph.V0) * ContainerAtlas->TexHeight + pad);
+ const int i = (int)IndexLookup.Data[c];
+ if (i == IM_FONTGLYPH_INDEX_NOT_FOUND)
+ return NULL;
+ if (i != IM_FONTGLYPH_INDEX_UNUSED)
+ return &Glyphs.Data[i];
+ }
+ LoadNoFallback = true; // This is actually a rare call, not done in hot-loop, so we prioritize not adding extra cruft to ImFontBaked_BuildLoadGlyph() call sites.
+ ImFontGlyph* glyph = ImFontBaked_BuildLoadGlyph(this, c, NULL);
+ LoadNoFallback = false;
+ return glyph;
}
-void ImFont::AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst)
+bool ImFontBaked::IsGlyphLoaded(ImWchar c)
{
- IM_ASSERT(IndexLookup.Size > 0); // Currently this can only be called AFTER the font has been built, aka after calling ImFontAtlas::GetTexDataAs*() function.
- unsigned int index_size = (unsigned int)IndexLookup.Size;
+ if (c < (size_t)IndexLookup.Size) IM_LIKELY
+ {
+ const int i = (int)IndexLookup.Data[c];
+ if (i == IM_FONTGLYPH_INDEX_NOT_FOUND)
+ return false;
+ if (i != IM_FONTGLYPH_INDEX_UNUSED)
+ return true;
+ }
+ return false;
+}
- if (dst < index_size && IndexLookup.Data[dst] == (ImWchar)-1 && !overwrite_dst) // 'dst' already exists
- return;
- if (src >= index_size && dst >= index_size) // both 'dst' and 'src' don't exist -> no-op
- return;
+// This is not fast query
+bool ImFont::IsGlyphInFont(ImWchar c)
+{
+ ImFontAtlas* atlas = ContainerAtlas;
+ ImFontAtlas_FontHookRemapCodepoint(atlas, this, &c);
+ for (ImFontConfig* src : Sources)
+ {
+ const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader;
+ if (loader->FontSrcContainsGlyph != NULL && loader->FontSrcContainsGlyph(atlas, src, c))
+ return true;
+ }
+ return false;
+}
- GrowIndex(dst + 1);
- IndexLookup[dst] = (src < index_size) ? IndexLookup.Data[src] : (ImWchar)-1;
- IndexAdvanceX[dst] = (src < index_size) ? IndexAdvanceX.Data[src] : 1.0f;
+// This is manually inlined in CalcTextSizeA() and CalcWordWrapPosition(), with a non-inline call to BuildLoadGlyphGetAdvanceOrFallback().
+IM_MSVC_RUNTIME_CHECKS_OFF
+float ImFontBaked::GetCharAdvance(ImWchar c)
+{
+ if ((int)c < IndexAdvanceX.Size)
+ {
+ // Missing glyphs fitting inside index will have stored FallbackAdvanceX already.
+ const float x = IndexAdvanceX.Data[c];
+ if (x >= 0.0f)
+ return x;
+ }
+ return ImFontBaked_BuildLoadGlyphAdvanceX(this, c);
}
+IM_MSVC_RUNTIME_CHECKS_RESTORE
-const ImFontGlyph* ImFont::FindGlyph(ImWchar c) const
+ImGuiID ImFontAtlasBakedGetId(ImGuiID font_id, float baked_size, float rasterizer_density)
{
- if (c >= (size_t)IndexLookup.Size)
- return FallbackGlyph;
- const ImWchar i = IndexLookup.Data[c];
- if (i == (ImWchar)-1)
- return FallbackGlyph;
- return &Glyphs.Data[i];
+ struct { ImGuiID FontId; float BakedSize; float RasterizerDensity; } hashed_data;
+ hashed_data.FontId = font_id;
+ hashed_data.BakedSize = baked_size;
+ hashed_data.RasterizerDensity = rasterizer_density;
+ return ImHashData(&hashed_data, sizeof(hashed_data));
}
-const ImFontGlyph* ImFont::FindGlyphNoFallback(ImWchar c) const
+// ImFontBaked pointers are valid for the entire frame but shall never be kept between frames.
+ImFontBaked* ImFont::GetFontBaked(float size, float density)
{
- if (c >= (size_t)IndexLookup.Size)
- return NULL;
- const ImWchar i = IndexLookup.Data[c];
- if (i == (ImWchar)-1)
+ ImFontBaked* baked = LastBaked;
+
+ // Round font size
+ // - ImGui::PushFont() will already round, but other paths calling GetFontBaked() directly also needs it (e.g. ImFontAtlasBuildPreloadAllGlyphRanges)
+ size = ImGui::GetRoundedFontSize(size);
+
+ if (density < 0.0f)
+ density = CurrentRasterizerDensity;
+ if (baked && baked->Size == size && baked->RasterizerDensity == density)
+ return baked;
+
+ ImFontAtlas* atlas = ContainerAtlas;
+ ImFontAtlasBuilder* builder = atlas->Builder;
+ baked = ImFontAtlasBakedGetOrAdd(atlas, this, size, density);
+ if (baked == NULL)
return NULL;
- return &Glyphs.Data[i];
+ baked->LastUsedFrame = builder->FrameCount;
+ LastBaked = baked;
+ return baked;
}
-// Wrapping skips upcoming blanks
-static inline const char* CalcWordWrapNextLineStartA(const char* text, const char* text_end)
+ImFontBaked* ImFontAtlasBakedGetOrAdd(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density)
{
- while (text < text_end && ImCharIsBlankA(*text))
- text++;
+ // FIXME-NEWATLAS: Design for picking a nearest size based on some criteria?
+ // FIXME-NEWATLAS: Altering font density won't work right away.
+ IM_ASSERT(font_size > 0.0f && font_rasterizer_density > 0.0f);
+ ImGuiID baked_id = ImFontAtlasBakedGetId(font->FontId, font_size, font_rasterizer_density);
+ ImFontAtlasBuilder* builder = atlas->Builder;
+ ImFontBaked** p_baked_in_map = (ImFontBaked**)builder->BakedMap.GetVoidPtrRef(baked_id);
+ ImFontBaked* baked = *p_baked_in_map;
+ if (baked != NULL)
+ {
+ IM_ASSERT(baked->Size == font_size && baked->ContainerFont == font && baked->BakedId == baked_id);
+ return baked;
+ }
+
+ // If atlas is locked, find closest match
+ // FIXME-OPT: This is not an optimal query.
+ if ((font->Flags & ImFontFlags_LockBakedSizes) || atlas->Locked)
+ {
+ baked = ImFontAtlasBakedGetClosestMatch(atlas, font, font_size, font_rasterizer_density);
+ if (baked != NULL)
+ return baked;
+ if (atlas->Locked)
+ {
+ IM_ASSERT(!atlas->Locked && "Cannot use dynamic font size with a locked ImFontAtlas!"); // Locked because rendering backend does not support ImGuiBackendFlags_RendererHasTextures!
+ return NULL;
+ }
+ }
+
+ // Create new
+ baked = ImFontAtlasBakedAdd(atlas, font, font_size, font_rasterizer_density, baked_id);
+ *p_baked_in_map = baked; // To avoid 'builder->BakedMap.SetVoidPtr(baked_id, baked);' while we can.
+ return baked;
+}
+
+// Trim trailing space and find beginning of next line
+const char* ImTextCalcWordWrapNextLineStart(const char* text, const char* text_end, ImDrawTextFlags flags)
+{
+ if ((flags & ImDrawTextFlags_WrapKeepBlanks) == 0)
+ while (text < text_end && ImCharIsBlankA(*text))
+ text++;
if (*text == '\n')
text++;
return text;
@@ -3861,7 +5360,7 @@ static inline const char* CalcWordWrapNextLineStartA(const char* text, const cha
// Simple word-wrapping for English, not full-featured. Please submit failing cases!
// This will return the next location to wrap from. If no wrapping if necessary, this will fast-forward to e.g. text_end.
// FIXME: Much possible improvements (don't cut things like "word !", "word!!!" but cut within "word,,,,", more sensible support for punctuations, support for Unicode punctuations, etc.)
-const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const
+const char* ImFontCalcWordWrapPositionEx(ImFont* font, float size, const char* text, const char* text_end, float wrap_width, ImDrawTextFlags flags)
{
// For references, possible wrap point marked with ^
// "aaa bbb, ccc,ddd. eee fff. ggg!"
@@ -3874,6 +5373,10 @@ const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const c
// Cut words that cannot possibly fit within one line.
// e.g.: "The tropical fish" with ~5 characters worth of width --> "The tr" "opical" "fish"
+
+ ImFontBaked* baked = font->GetFontBaked(size);
+ const float scale = size / baked->Size;
+
float line_width = 0.0f;
float word_width = 0.0f;
float blank_width = 0.0f;
@@ -3897,12 +5400,7 @@ const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const c
if (c < 32)
{
if (c == '\n')
- {
- line_width = word_width = blank_width = 0.0f;
- inside_word = true;
- s = next_s;
- continue;
- }
+ return s; // Direct return, skip "Wrap_width is too small to fit anything" path.
if (c == '\r')
{
s = next_s;
@@ -3910,7 +5408,11 @@ const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const c
}
}
- const float char_width = ((int)c < IndexAdvanceX.Size ? IndexAdvanceX.Data[c] : FallbackAdvanceX);
+ // Optimized inline version of 'float char_width = GetCharAdvance((ImWchar)c);'
+ float char_width = (c < (unsigned int)baked->IndexAdvanceX.Size) ? baked->IndexAdvanceX.Data[c] : -1.0f;
+ if (char_width < 0.0f)
+ char_width = BuildLoadGlyphGetAdvanceOrFallback(baked, c);
+
if (ImCharIsBlankW(c))
{
if (inside_word)
@@ -3933,11 +5435,13 @@ const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const c
{
prev_word_end = word_end;
line_width += word_width + blank_width;
+ if ((flags & ImDrawTextFlags_WrapKeepBlanks) && line_width <= wrap_width)
+ prev_word_end = s;
word_width = blank_width = 0.0f;
}
// Allow wrapping after punctuation.
- inside_word = (c != '.' && c != ',' && c != ';' && c != '!' && c != '?' && c != '\"');
+ inside_word = (c != '.' && c != ',' && c != ';' && c != '!' && c != '?' && c != '\"' && c != 0x3001 && c != 0x3002);
}
// We ignore blank width at the end of the line (they can be skipped)
@@ -3955,17 +5459,25 @@ const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const c
// Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity.
// +1 may not be a character start point in UTF-8 but it's ok because caller loops use (text >= word_wrap_eol).
if (s == text && text < text_end)
- return s + 1;
+ return s + ImTextCountUtf8BytesFromChar(s, text_end);
return s;
}
-ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** remaining) const
+const char* ImFont::CalcWordWrapPosition(float size, const char* text, const char* text_end, float wrap_width)
+{
+ return ImFontCalcWordWrapPositionEx(this, size, text, text_end, wrap_width, ImDrawTextFlags_None);
+}
+
+ImVec2 ImFontCalcTextSizeEx(ImFont* font, float size, float max_width, float wrap_width, const char* text_begin, const char* text_end_display, const char* text_end, const char** out_remaining, ImVec2* out_offset, ImDrawTextFlags flags)
{
if (!text_end)
- text_end = text_begin + strlen(text_begin); // FIXME-OPT: Need to avoid this.
+ text_end = text_begin + ImStrlen(text_begin); // FIXME-OPT: Need to avoid this.
+ if (!text_end_display)
+ text_end_display = text_end;
+ ImFontBaked* baked = font->GetFontBaked(size);
const float line_height = size;
- const float scale = size / FontSize;
+ const float scale = line_height / baked->Size;
ImVec2 text_size = ImVec2(0, 0);
float line_width = 0.0f;
@@ -3974,13 +5486,14 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons
const char* word_wrap_eol = NULL;
const char* s = text_begin;
- while (s < text_end)
+ while (s < text_end_display)
{
+ // Word-wrapping
if (word_wrap_enabled)
{
// Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature.
if (!word_wrap_eol)
- word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - line_width);
+ word_wrap_eol = ImFontCalcWordWrapPositionEx(font, size, s, text_end, wrap_width - line_width, flags);
if (s >= word_wrap_eol)
{
@@ -3988,8 +5501,10 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons
text_size.x = line_width;
text_size.y += line_height;
line_width = 0.0f;
+ s = ImTextCalcWordWrapNextLineStart(s, text_end, flags); // Wrapping skips upcoming blanks
+ if (flags & ImDrawTextFlags_StopOnNewLine)
+ break;
word_wrap_eol = NULL;
- s = CalcWordWrapNextLineStartA(s, text_end); // Wrapping skips upcoming blanks
continue;
}
}
@@ -4002,20 +5517,24 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons
else
s += ImTextCharFromUtf8(&c, s, text_end);
- if (c < 32)
+ if (c == '\n')
{
- if (c == '\n')
- {
- text_size.x = ImMax(text_size.x, line_width);
- text_size.y += line_height;
- line_width = 0.0f;
- continue;
- }
- if (c == '\r')
- continue;
+ text_size.x = ImMax(text_size.x, line_width);
+ text_size.y += line_height;
+ line_width = 0.0f;
+ if (flags & ImDrawTextFlags_StopOnNewLine)
+ break;
+ continue;
}
+ if (c == '\r')
+ continue;
+
+ // Optimized inline version of 'float char_width = GetCharAdvance((ImWchar)c);'
+ float char_width = (c < (unsigned int)baked->IndexAdvanceX.Size) ? baked->IndexAdvanceX.Data[c] : -1.0f;
+ if (char_width < 0.0f)
+ char_width = BuildLoadGlyphGetAdvanceOrFallback(baked, c);
+ char_width *= scale;
- const float char_width = ((int)c < IndexAdvanceX.Size ? IndexAdvanceX.Data[c] : FallbackAdvanceX) * scale;
if (line_width + char_width >= max_width)
{
s = prev_s;
@@ -4028,45 +5547,81 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons
if (text_size.x < line_width)
text_size.x = line_width;
- if (line_width > 0 || text_size.y == 0.0f)
+ if (out_offset != NULL)
+ *out_offset = ImVec2(line_width, text_size.y + line_height); // offset allow for the possibility of sitting after a trailing \n
+
+ if (line_width > 0 || text_size.y == 0.0f) // whereas size.y will ignore the trailing \n
text_size.y += line_height;
- if (remaining)
- *remaining = s;
+ if (out_remaining != NULL)
+ *out_remaining = s;
return text_size;
}
+ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** out_remaining)
+{
+ return ImFontCalcTextSizeEx(this, size, max_width, wrap_width, text_begin, text_end, text_end, out_remaining, NULL, ImDrawTextFlags_None);
+}
+
// Note: as with every ImDrawList drawing function, this expects that the font atlas texture is bound.
-void ImFont::RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, ImWchar c) const
+void ImFont::RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, ImWchar c, const ImVec4* cpu_fine_clip)
{
- const ImFontGlyph* glyph = FindGlyph(c);
+ ImFontBaked* baked = GetFontBaked(size);
+ const ImFontGlyph* glyph = baked->FindGlyph(c);
if (!glyph || !glyph->Visible)
return;
if (glyph->Colored)
col |= ~IM_COL32_A_MASK;
- float scale = (size >= 0.0f) ? (size / FontSize) : 1.0f;
+ float scale = (size >= 0.0f) ? (size / baked->Size) : 1.0f;
float x = IM_TRUNC(pos.x);
float y = IM_TRUNC(pos.y);
+
+ float x1 = x + glyph->X0 * scale;
+ float x2 = x + glyph->X1 * scale;
+ if (cpu_fine_clip && (x1 > cpu_fine_clip->z || x2 < cpu_fine_clip->x))
+ return;
+ float y1 = y + glyph->Y0 * scale;
+ float y2 = y + glyph->Y1 * scale;
+ float u1 = glyph->U0;
+ float v1 = glyph->V0;
+ float u2 = glyph->U1;
+ float v2 = glyph->V1;
+
+ // Always CPU fine clip. Code extracted from RenderText().
+ // 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 != NULL)
+ {
+ if (x1 < cpu_fine_clip->x) { u1 = u1 + (1.0f - (x2 - cpu_fine_clip->x) / (x2 - x1)) * (u2 - u1); x1 = cpu_fine_clip->x; }
+ if (y1 < cpu_fine_clip->y) { v1 = v1 + (1.0f - (y2 - cpu_fine_clip->y) / (y2 - y1)) * (v2 - v1); y1 = cpu_fine_clip->y; }
+ if (x2 > cpu_fine_clip->z) { u2 = u1 + ((cpu_fine_clip->z - x1) / (x2 - x1)) * (u2 - u1); x2 = cpu_fine_clip->z; }
+ if (y2 > cpu_fine_clip->w) { v2 = v1 + ((cpu_fine_clip->w - y1) / (y2 - y1)) * (v2 - v1); y2 = cpu_fine_clip->w; }
+ if (y1 >= y2)
+ return;
+ }
draw_list->PrimReserve(6, 4);
- draw_list->PrimRectUV(ImVec2(x + glyph->X0 * scale, y + glyph->Y0 * scale), ImVec2(x + glyph->X1 * scale, y + glyph->Y1 * scale), ImVec2(glyph->U0, glyph->V0), ImVec2(glyph->U1, glyph->V1), col);
+ draw_list->PrimRectUV(ImVec2(x1, y1), ImVec2(x2, y2), ImVec2(u1, v1), ImVec2(u2, v2), col);
}
// Note: as with every ImDrawList drawing function, this expects that the font atlas texture is bound.
-void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width, bool cpu_fine_clip) const
+// DO NOT CALL DIRECTLY THIS WILL CHANGE WIDLY IN 2025-2025. Use ImDrawList::AddText().
+void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width, ImDrawTextFlags flags)
{
- if (!text_end)
- 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
+begin:
float x = IM_TRUNC(pos.x);
float y = IM_TRUNC(pos.y);
if (y > clip_rect.w)
return;
- const float start_x = x;
- const float scale = size / FontSize;
- const float line_height = FontSize * scale;
+ if (!text_end)
+ text_end = text_begin + ImStrlen(text_begin); // ImGui:: functions generally already provides a valid text_end, so this is merely to handle direct calls.
+
+ const float line_height = size;
+ ImFontBaked* baked = GetFontBaked(size);
+
+ const float scale = size / baked->Size;
+ const float origin_x = x;
const bool word_wrap_enabled = (wrap_width > 0.0f);
// Fast-forward to first visible line
@@ -4074,14 +5629,14 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, Im
if (y + line_height < clip_rect.y)
while (y + line_height < clip_rect.y && s < text_end)
{
- const char* line_end = (const char*)memchr(s, '\n', text_end - s);
+ const char* line_end = (const char*)ImMemchr(s, '\n', text_end - s);
if (word_wrap_enabled)
{
- // FIXME-OPT: This is not optimal as do first do a search for \n before calling CalcWordWrapPositionA().
- // If the specs for CalcWordWrapPositionA() were reworked to optionally return on \n we could combine both.
+ // FIXME-OPT: This is not optimal as do first do a search for \n before calling CalcWordWrapPosition().
+ // If the specs for CalcWordWrapPosition() were reworked to optionally return on \n we could combine both.
// However it is still better than nothing performing the fast-forward!
- s = CalcWordWrapPositionA(scale, s, line_end ? line_end : text_end, wrap_width);
- s = CalcWordWrapNextLineStartA(s, text_end);
+ s = ImFontCalcWordWrapPositionEx(this, size, s, line_end ? line_end : text_end, wrap_width, flags);
+ s = ImTextCalcWordWrapNextLineStart(s, text_end, flags);
}
else
{
@@ -4098,7 +5653,7 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, Im
float y_end = y;
while (y_end < clip_rect.w && s_end < text_end)
{
- s_end = (const char*)memchr(s_end, '\n', text_end - s_end);
+ s_end = (const char*)ImMemchr(s_end, '\n', text_end - s_end);
s_end = s_end ? s_end + 1 : text_end;
y_end += line_height;
}
@@ -4115,6 +5670,8 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, Im
ImDrawVert* vtx_write = draw_list->_VtxWritePtr;
ImDrawIdx* idx_write = draw_list->_IdxWritePtr;
unsigned int vtx_index = draw_list->_VtxCurrentIdx;
+ const int cmd_count = draw_list->CmdBuffer.Size;
+ const bool cpu_fine_clip = (flags & ImDrawTextFlags_CpuFineClip) != 0;
const ImU32 col_untinted = col | ~IM_COL32_A_MASK;
const char* word_wrap_eol = NULL;
@@ -4125,16 +5682,16 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, Im
{
// Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature.
if (!word_wrap_eol)
- word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - (x - start_x));
+ word_wrap_eol = ImFontCalcWordWrapPositionEx(this, size, s, text_end, wrap_width - (x - origin_x), flags);
if (s >= word_wrap_eol)
{
- x = start_x;
+ x = origin_x;
y += line_height;
if (y > clip_rect.w)
break; // break out of main loop
word_wrap_eol = NULL;
- s = CalcWordWrapNextLineStartA(s, text_end); // Wrapping skips upcoming blanks
+ s = ImTextCalcWordWrapNextLineStart(s, text_end, flags); // Wrapping skips upcoming blanks
continue;
}
}
@@ -4150,7 +5707,7 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, Im
{
if (c == '\n')
{
- x = start_x;
+ x = origin_x;
y += line_height;
if (y > clip_rect.w)
break; // break out of main loop
@@ -4160,9 +5717,9 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, Im
continue;
}
- const ImFontGlyph* glyph = FindGlyph((ImWchar)c);
- if (glyph == NULL)
- continue;
+ const ImFontGlyph* glyph = baked->FindGlyph((ImWchar)c);
+ //if (glyph == NULL)
+ // continue;
float char_width = glyph->AdvanceX * scale;
if (glyph->Visible)
@@ -4230,6 +5787,20 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, Im
x += char_width;
}
+ // Edge case: calling RenderText() with unloaded glyphs triggering texture change. It doesn't happen via ImGui:: calls because CalcTextSize() is always used.
+ if (cmd_count != draw_list->CmdBuffer.Size) //-V547
+ {
+ IM_ASSERT(draw_list->CmdBuffer[draw_list->CmdBuffer.Size - 1].ElemCount == 0);
+ draw_list->CmdBuffer.pop_back();
+ draw_list->PrimUnreserve(idx_count_max, vtx_count_max);
+ draw_list->AddDrawCmd();
+ //IMGUI_DEBUG_LOG("RenderText: cancel and retry to missing glyphs.\n"); // [DEBUG]
+ //draw_list->AddRectFilled(pos, pos + ImVec2(10, 10), IM_COL32(255, 0, 0, 255)); // [DEBUG]
+ goto begin;
+ //RenderText(draw_list, size, pos, col, clip_rect, text_begin, text_end, wrap_width, cpu_fine_clip); // FIXME-OPT: Would a 'goto begin' be better for code-gen?
+ //return;
+ }
+
// 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);
@@ -4289,8 +5860,9 @@ void ImGui::RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImU32 col, ImGuiDir d
void ImGui::RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col)
{
- // FIXME-OPT: This should be baked in font.
- draw_list->AddCircleFilled(pos, draw_list->_Data->FontSize * 0.20f, col, 8);
+ // FIXME-OPT: This should be baked in font now that it's easier.
+ float font_size = draw_list->_Data->FontSize;
+ draw_list->AddCircleFilled(pos, font_size * 0.20f, col, (font_size < 22) ? 8 : (font_size < 40) ? 12 : 0); // Hardcode optimal/nice tessellation threshold
}
void ImGui::RenderCheckMark(ImDrawList* draw_list, ImVec2 pos, ImU32 col, float sz)
@@ -4592,102 +6164,189 @@ static unsigned int stb_decompress(unsigned char *output, const unsigned char *i
// Copyright (c) 2004, 2005 Tristan Grimmer
// MIT license (see License.txt in http://www.proggyfonts.net/index.php?menu=download)
// Download and more information at http://www.proggyfonts.net or http://upperboundsinteractive.com/fonts.php
+// If you want a similar font which may be better scaled, consider using ProggyVector from the same author!
//-----------------------------------------------------------------------------
+
+#ifndef IMGUI_DISABLE_DEFAULT_FONT
+
// File: 'ProggyClean.ttf' (41208 bytes)
-// 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] =
- "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^`IWM9<Lh2TlS+f-s$o6Q<BWH`YiU.xfLq$N;$0iR/GX:U(jcW2p/W*q?-qmnUCI;jHSAiFWM.R*kU@C=GH?a9wp8f$e.-4^Qg1)Q-GL(lf(r/7GrRgwV%MS=C#"
- "`8ND>Qo#t'X#(v#Y9w0#1D$CIf;W'#pWUPXOuxXuU(H9M(1<q-UE31#^-V'8IRUo7Qf./L>=Ke$$'5F%)]0^#0X@U.a<r:QLtFsLcL6##lOj)#.Y5<-R&KgLwqJfLgN&;Q?gI^#DY2uL"
- "i@^rMl9t=cWq6##weg>$FBjVQTSDgEKnIS7EM9>ZY9w0#L;>>#Mx&4Mvt//L[MkA#W@lK.N'[0#7RL_&#w+F%HtG9M#XL`N&.,GM4Pg;-<nLENhvx>-VsM.M0rJfLH2eTM`*oJMHRC`N"
- "kfimM2J,W-jXS:)r0wK#@Fge$U>`w'N7G#$#fB#$E^$#:9:hk+eOe--6x)F7*E%?76%^GMHePW-Z5l'&GiF#$956:rS?dA#fiK:)Yr+`&#0j@'DbG&#^$PG.Ll+DNa<XCMKEV*N)LN/N"
- "*b=%Q6pia-Xg8I$<MR&,VdJe$<(7G;Ckl'&hF;;$<_=X(b.RS%%)###MPBuuE1V:v&cX&#2m#(&cV]`k9OhLMbn%s$G2,B$BfD3X*sp5#l,$R#]x_X1xKX%b5U*[r5iMfUo9U`N99hG)"
- "tm+/Us9pG)XPu`<0s-)WTt(gCRxIg(%6sfh=ktMKn3j)<6<b5Sk_/0(^]AaN#(p/L>&VZ>1i%h1S9u5o@YaaW$e+b<TWFn/Z:Oh(Cx2$lNEoN^e)#CFY@@I;BOQ*sRwZtZxRcU7uW6CX"
- "ow0i(?$Q[cjOd[P4d)]>ROPOpxTO7Stwi1::iB1q)C_=dV26J;2,]7op$]uQr@_V7$q^%lQwtuHY]=DX,n3L#0PHDO4f9>dC@O>HBuKPpP*E,N+b3L#lpR/MrTEH.IAQk.a>D[.e;mc."
- "x]Ip.PH^'/aqUO/$1WxLoW0[iLA<QT;5HKD+@qQ'NQ(3_PLhE48R.qAPSwQ0/WK?Z,[x?-J;jQTWA0X@KJ(_Y8N-:/M74:/-ZpKrUss?d#dZq]DAbkU*JqkL+nwX@@47`5>w=4h(9.`G"
- "CRUxHPeR`5Mjol(dUWxZa(>STrPkrJiWx`5U7F#.g*jrohGg`cg:lSTvEY/EV_7H4Q9[Z%cnv;JQYZ5q.l7Zeas:HOIZOB?G<Nald$qs]@]L<J7bR*>gv:[7MI2k).'2($5FNP&EQ(,)"
- "U]W]+fh18.vsai00);D3@4ku5P?DP8aJt+;qUM]=+b'8@;mViBKx0DE[-auGl8:PJ&Dj+M6OC]O^((##]`0i)drT;-7X`=-H3[igUnPG-NZlo.#k@h#=Ork$m>a>$-?Tm$UV(?#P6YY#"
- "'/###xe7q.73rI3*pP/$1>s9)W,JrM7SN]'/4C#v$U`0#V.[0>xQsH$fEmPMgY2u7Kh(G%siIfLSoS+MK2eTM$=5,M8p`A.;_R%#u[K#$x4AG8.kK/HSB==-'Ie/QTtG?-.*^N-4B/ZM"
- "_3YlQC7(p7q)&](`6_c)$/*JL(L-^(]$wIM`dPtOdGA,U3:w2M-0<q-]L_?^)1vw'.,MRsqVr.L;aN&#/EgJ)PBc[-f>+WomX2u7lqM2iEumMTcsF?-aT=Z-97UEnXglEn1K-bnEO`gu"
- "Ft(c%=;Am_Qs@jLooI&NX;]0#j4#F14;gl8-GQpgwhrq8'=l_f-b49'UOqkLu7-##oDY2L(te+Mch&gLYtJ,MEtJfLh'x'M=$CS-ZZ%P]8bZ>#S?YY#%Q&q'3^Fw&?D)UDNrocM3A76/"
- "/oL?#h7gl85[qW/NDOk%16ij;+:1a'iNIdb-ou8.P*w,v5#EI$TWS>Pot-R*H'-SEpA:g)f+O$%%`kA#G=8RMmG1&O`>to8bC]T&$,n.LoO>29sp3dt-52U%VM#q7'DHpg+#Z9%H[K<L"
- "%a2E-grWVM3@2=-k22tL]4$##6We'8UJCKE[d_=%wI;'6X-GsLX4j^SgJ$##R*w,vP3wK#iiW&#*h^D&R?jp7+/u&#(AP##XU8c$fSYW-J95_-Dp[g9wcO&#M-h1OcJlc-*vpw0xUX&#"
- "OQFKNX@QI'IoPp7nb,QU//MQ&ZDkKP)X<WSVL(68uVl&#c'[0#(s1X&xm$Y%B7*K:eDA323j998GXbA#pwMs-jgD$9QISB-A_(aN4xoFM^@C58D0+Q+q3n0#3U1InDjF682-SjMXJK)("
- "h$hxua_K]ul92%'BOU&#BRRh-slg8KDlr:%L71Ka:.A;%YULjDPmL<LYs8i#XwJOYaKPKc1h:'9Ke,g)b),78=I39B;xiY$bgGw-&.Zi9InXDuYa%G*f2Bq7mn9^#p1vv%#(Wi-;/Z5h"
- "o;#2:;%d&#x9v68C5g?ntX0X)pT`;%pB3q7mgGN)3%(P8nTd5L7GeA-GL@+%J3u2:(Yf>et`e;)f#Km8&+DC$I46>#Kr]]u-[=99tts1.qb#q72g1WJO81q+eN'03'eM>&1XxY-caEnO"
- "j%2n8)),?ILR5^.Ibn<-X-Mq7[a82Lq:F&#ce+S9wsCK*x`569E8ew'He]h:sI[2LM$[guka3ZRd6:t%IG:;$%YiJ:Nq=?eAw;/:nnDq0(CYcMpG)qLN4$##&J<j$UpK<Q4a1]MupW^-"
- "sj_$%[HK%'F####QRZJ::Y3EGl4'@%FkiAOg#p[##O`gukTfBHagL<LHw%q&OV0##F=6/:chIm0@eCP8X]:kFI%hl8hgO@RcBhS-@Qb$%+m=hPDLg*%K8ln(wcf3/'DW-$.lR?n[nCH-"
- "eXOONTJlh:.RYF%3'p6sq:UIMA945&^HFS87@$EP2iG<-lCO$%c`uKGD3rC$x0BL8aFn--`ke%#HMP'vh1/R&O_J9'um,.<tx[@%wsJk&bUT2`0uMv7gg#qp/ij.L56'hl;.s5CUrxjO"
- "M7-##.l+Au'A&O:-T72L]P`&=;ctp'XScX*rU.>-XTt,%OVU4)S1+R-#dg0/Nn?Ku1^0f$B*P:Rowwm-`0PKjYDDM'3]d39VZHEl4,.j']Pk-M.h^&:0FACm$maq-&sgw0t7/6(^xtk%"
- "LuH88Fj-ekm>GA#_>568x6(OFRl-IZp`&b,_P'$M<Jnq79VsJW/mWS*PUiq76;]/NM_>hLbxfc$mj`,O;&%W2m`Zh:/)Uetw:aJ%]K9h:TcF]u_-Sj9,VK3M.*'&0D[Ca]J9gp8,kAW]"
- "%(?A%R$f<->Zts'^kn=-^@c4%-pY6qI%J%1IGxfLU9CP8cbPlXv);C=b),<2mOvP8up,UVf3839acAWAW-W?#ao/^#%KYo8fRULNd2.>%m]UK:n%r$'sw]J;5pAoO_#2mO3n,'=H5(et"
- "Hg*`+RLgv>=4U8guD$I%D:W>-r5V*%j*W:Kvej.Lp$<M-SGZ':+Q_k+uvOSLiEo(<aD/K<CCc`'Lx>'?;++O'>()jLR-^u68PHm8ZFWe+ej8h:9r6L*0//c&iH&R8pRbA#Kjm%upV1g:"
- "a_#Ur7FuA#(tRh#.Y5K+@?3<-8m0$PEn;J:rh6?I6uG<-`wMU'ircp0LaE_OtlMb&1#6T.#FDKu#1Lw%u%+GM+X'e?YLfjM[VO0MbuFp7;>Q&#WIo)0@F%q7c#4XAXN-U&VB<HFF*qL("
- "$/V,;(kXZejWO`<[5?\?ewY(*9=%wDc;,u<'9t3W-(H1th3+G]ucQ]kLs7df($/*JL]@*t7Bu_G3_7mp7<iaQjO@.kLg;x3B0lqp7Hf,^Ze7-##@/c58Mo(3;knp0%)A7?-W+eI'o8)b<"
- "nKnw'Ho8C=Y>pqB>0ie&jhZ[?iLR@@_AvA-iQC(=ksRZRVp7`.=+NpBC%rh&3]R:8XDmE5^V8O(x<<aG/1N$#FX$0V5Y6x'aErI3I$7x%E`v<-BY,)%-?Psf*l?%C3.mM(=/M0:JxG'?"
- "7WhH%o'a<-80g0NBxoO(GH<dM]n.+%q@jH?f.UsJ2Ggs&4<-e47&Kl+f//9@`b+?.TeN_&B8Ss?v;^Trk;f#YvJkl&w$]>-+k?'(<S:68tq*WoDfZu';mM?8X[ma8W%*`-=;D.(nc7/;"
- ")g:T1=^J$&BRV(-lTmNB6xqB[@0*o.erM*<SWF]u2=st-*(6v>^](H.aREZSi,#1:[IXaZFOm<-ui#qUq2$##Ri;u75OK#(RtaW-K-F`S+cF]uN`-KMQ%rP/Xri.LRcB##=YL3BgM/3M"
- "D?@f&1'BW-)Ju<L25gl8uhVm1hL$##*8###'A3/LkKW+(^rWX?5W_8g)a(m&K8P>#bmmWCMkk&#TR`C,5d>g)F;t,4:@_l8G/5h4vUd%&%950:VXD'QdWoY-F$BtUwmfe$YqL'8(PWX("
- "P?^@Po3$##`MSs?DWBZ/S>+4%>fX,VWv/w'KD`LP5IbH;rTV>n3cEK8U#bX]l-/V+^lj3;vlMb&[5YQ8#pekX9JP3XUC72L,,?+Ni&co7ApnO*5NK,((W-i:$,kp'UDAO(G0Sq7MVjJs"
- "bIu)'Z,*[>br5fX^:FPAWr-m2KgL<LUN098kTF&#lvo58=/vjDo;.;)Ka*hLR#/k=rKbxuV`>Q_nN6'8uTG&#1T5g)uLv:873UpTLgH+#FgpH'_o1780Ph8KmxQJ8#H72L4@768@Tm&Q"
- "h4CB/5OvmA&,Q&QbUoi$a_%3M01H)4x7I^&KQVgtFnV+;[Pc>[m4k//,]1?#`VY[Jr*3&&slRfLiVZJ:]?=K3Sw=[$=uRB?3xk48@aeg<Z'<$#4H)6,>e0jT6'N#(q%.O=?2S]u*(m<-"
- "V8J'(1)G][68hW$5'q[GC&5j`TE?m'esFGNRM)j,ffZ?-qx8;->g4t*:CIP/[Qap7/9'#(1sao7w-.qNUdkJ)tCF&#B^;xGvn2r9FEPFFFcL@.iFNkTve$m%#QvQS8U@)2Z+3K:AKM5i"
- "sZ88+dKQ)W6>J%CL<KE>`.d*(B`-n8D9oK<Up]c$X$(,)M8Zt7/[rdkqTgl-0cuGMv'?>-XV1q['-5k'cAZ69e;D_?$ZPP&s^+7])$*$#@QYi9,5P&#9r+$%CE=68>K8r0=dSC%%(@p7"
- ".m7jilQ02'0-VWAg<a/''3u.=4L$Y)6k/K:_[3=&jvL<L0C/2'v:^;-DIBW,B4E68:kZ;%?8(Q8BH=kO65BW?xSG&#@uU,DS*,?.+(o(#1vCS8#CHF>TlGW'b)Tq7VT9q^*^$$.:&N@@"
- "$&)WHtPm*5_rO0&e%K&#-30j(E4#'Zb.o/(Tpm$>K'f@[PvFl,hfINTNU6u'0pao7%XUp9]5.>%h`8_=VYbxuel.NTSsJfLacFu3B'lQSu/m6-Oqem8T+oE--$0a/k]uj9EwsG>%veR*"
- "hv^BFpQj:K'#SJ,sB-'#](j.Lg92rTw-*n%@/;39rrJF,l#qV%OrtBeC6/,;qB3ebNW[?,Hqj2L.1NP&GjUR=1D8QaS3Up&@*9wP?+lo7b?@%'k4`p0Z$22%K3+iCZj?XJN4Nm&+YF]u"
- "@-W$U%VEQ/,,>>#)D<h#`)h0:<Q6909ua+&VU%n2:cG3FJ-%@Bj-DgLr`Hw&HAKjKjseK</xKT*)B,N9X3]krc12t'pgTV(Lv-tL[xg_%=M_q7a^x?7Ubd>#%8cY#YZ?=,`Wdxu/ae&#"
- "w6)R89tI#6@s'(6Bf7a&?S=^ZI_kS&ai`&=tE72L_D,;^R)7[$s<Eh#c&)q.MXI%#v9ROa5FZO%sF7q7Nwb&#ptUJ:aqJe$Sl68%.D###EC><?-aF&#RNQv>o8lKN%5/$(vdfq7+ebA#"
- "u1p]ovUKW&Y%q]'>$1@-[xfn$7ZTp7mM,G,Ko7a&Gu%G[RMxJs[0MM%wci.LFDK)(<c`Q8N)jEIF*+?P2a8g%)$q]o2aH8C&<SibC/q,(e:v;-b#6[$NtDZ84Je2KNvB#$P5?tQ3nt(0"
- "d=j.LQf./Ll33+(;q3L-w=8dX$#WF&uIJ@-bfI>%:_i2B5CsR8&9Z&#=mPEnm0f`<&c)QL5uJ#%u%lJj+D-r;BoF&#4DoS97h5g)E#o:&S4weDF,9^Hoe`h*L+_a*NrLW-1pG_&2UdB8"
- "6e%B/:=>)N4xeW.*wft-;$'58-ESqr<b?UI(_%@[P46>#U`'6AQ]m&6/`Z>#S?YY#Vc;r7U2&326d=w&H####?TZ`*4?&.MK?LP8Vxg>$[QXc%QJv92.(Db*B)gb*BM9dM*hJMAo*c&#"
- "b0v=Pjer]$gG&JXDf->'StvU7505l9$AFvgYRI^&<^b68?j#q9QX4SM'RO#&sL1IM.rJfLUAj221]d##DW=m83u5;'bYx,*Sl0hL(W;;$doB&O/TQ:(Z^xBdLjL<Lni;''X.`$#8+1GD"
- ":k$YUWsbn8ogh6rxZ2Z9]%nd+>V#*8U_72Lh+2Q8Cj0i:6hp&$C/:p(HK>T8Y[gHQ4`4)'$Ab(Nof%V'8hL&#<NEdtg(n'=S1A(Q1/I&4([%dM`,Iu'1:_hL>SfD07&6D<fp8dHM7/g+"
- "tlPN9J*rKaPct&?'uBCem^jn%9_K)<,C5K3s=5g&GmJb*[SYq7K;TRLGCsM-$$;S%:Y@r7AK0pprpL<Lrh,q7e/%KWK:50I^+m'vi`3?%Zp+<-d+$L-Sv:@.o19n$s0&39;kn;S%BSq*"
- "$3WoJSCLweV[aZ'MQIjO<7;X-X;&+dMLvu#^UsGEC9WEc[X(wI7#2.(F0jV*eZf<-Qv3J-c+J5AlrB#$p(H68LvEA'q3n0#m,[`*8Ft)FcYgEud]CWfm68,(aLA$@EFTgLXoBq/UPlp7"
- ":d[/;r_ix=:TF`S5H-b<LI&HY(K=h#)]Lk$K14lVfm:x$H<3^Ql<M`$OhapBnkup'D#L$Pb_`N*g]2e;X/Dtg,bsj&K#2[-:iYr'_wgH)NUIR8a1n#S?Yej'h8^58UbZd+^FKD*T@;6A"
- "7aQC[K8d-(v6GI$x:T<&'Gp5Uf>@M.*J:;$-rv29'M]8qMv-tLp,'886iaC=Hb*YJoKJ,(j%K=H`K.v9HggqBIiZu'QvBT.#=)0ukruV&.)3=(^1`o*Pj4<-<aN((^7('#Z0wK#5GX@7"
- "u][`*S^43933A4rl][`*O4CgLEl]v$1Q3AeF37dbXk,.)vj#x'd`;qgbQR%FW,2(?LO=s%Sc68%NP'##Aotl8x=BE#j1UD([3$M(]UI2LX3RpKN@;/#f'f/&_mt&F)XdF<9t4)Qa.*kT"
- "LwQ'(TTB9.xH'>#MJ+gLq9-##@HuZPN0]u:h7.T..G:;$/Usj(T7`Q8tT72LnYl<-qx8;-HV7Q-&Xdx%1a,hC=0u+HlsV>nuIQL-5<N?)NBS)QN*_I,?&)2'IM%L3I)X((e/dl2&8'<M"
- ":^#M*Q+[T.Xri.LYS3v%fF`68h;b-X[/En'CR.q7E)p'/kle2HM,u;^%OKC-N+Ll%F9CF<Nf'^#t2L,;27W:0O@6##U6W7:$rJfLWHj$#)woqBefIZ.PK<b*t7ed;p*_m;4ExK#h@&]>"
- "_>@kXQtMacfD.m-VAb8;IReM3$wf0''hra*so568'Ip&vRs849'MRYSp%:t:h5qSgwpEr$B>Q,;s(C#$)`svQuF$##-D,##,g68@2[T;.XSdN9Qe)rpt._K-#5wF)sP'##p#C0c%-Gb%"
- "hd+<-j'Ai*x&&HMkT]C'OSl##5RG[JXaHN;d'uA#x._U;.`PU@(Z3dt4r152@:v,'R.Sj'w#0<-;kPI)FfJ&#AYJ&#//)>-k=m=*XnK$>=)72L]0I%>.G690a:$##<,);?;72#?x9+d;"
- "^V'9;jY@;)br#q^YQpx:X#Te$Z^'=-=bGhLf:D6&bNwZ9-ZD#n^9HhLMr5G;']d&6'wYmTFmL<LD)F^%[tC'8;+9E#C$g%#5Y>q9wI>P(9mI[>kC-ekLC/R&CH+s'B;K-M6$EB%is00:"
- "+A4[7xks.LrNk0&E)wILYF@2L'0Nb$+pv<(2.768/FrY&h$^3i&@+G%JT'<-,v`3;_)I9M^AE]CN?Cl2AZg+%4iTpT3<n-&%H%b<FDj2M<hH=&Eh<2Len$b*aTX=-8QxN)k11IM1c^j%"
- "9s<L<NFSo)B?+<-(GxsF,^-Eh@$4dXhN$+#rxK8'je'D7k`e;)2pYwPA'_p9&@^18ml1^[@g4t*[JOa*[=Qp7(qJ_oOL^('7fB&Hq-:sf,sNj8xq^>$U4O]GKx'm9)b@p7YsvK3w^YR-"
- "CdQ*:Ir<($u&)#(&?L9Rg3H)4fiEp^iI9O8KnTj,]H?D*r7'M;PwZ9K0E^k&-cpI;.p/6_vwoFMV<->#%Xi.LxVnrU(4&8/P+:hLSKj$#U%]49t'I:rgMi'FL@a:0Y-uA[39',(vbma*"
- "hU%<-SRF`Tt:542R_VV$p@[p8DV[A,?1839FWdF<TddF<9Ah-6&9tWoDlh]&1SpGMq>Ti1O*H&#(AL8[_P%.M>v^-))qOT*F5Cq0`Ye%+$B6i:7@0IX<N+T+0MlMBPQ*Vj>SsD<U4JHY"
- "8kD2)2fU/M#$e.)T4,_=8hLim[&);?UkK'-x?'(:siIfL<$pFM`i<?%W(mGDHM%>iWP,##P`%/L<eXi:@Z9C.7o=@(pXdAO/NLQ8lPl+HPOQa8wD8=^GlPa8TKI1CjhsCTSLJM'/Wl>-"
- "S(qw%sf/@%#B6;/U7K]uZbi^Oc^2n<bhPmUkMw>%t<)'mEVE''n`WnJra$^TKvX5B>;_aSEK',(hwa0:i4G?.Bci.(X[?b*($,=-n<.Q%`(X=?+@Am*Js0&=3bh8K]mL<LoNs'6,'85`"
- "0?t/'_U59@]ddF<#LdF<eWdF<OuN/45rY<-L@&#+fm>69=Lb,OcZV/);TTm8VI;?%OtJ<(b4mq7M6:u?KRdF<gR@2L=FNU-<b[(9c/ML3m;Z[$oF3g)GAWqpARc=<ROu7cL5l;-[A]%/"
- "+fsd;l#SafT/f*W]0=O'$(Tb<[)*@e775R-:Yob%g*>l*:xP?Yb.5)%w_I?7uk5JC+FS(m#i'k.'a0i)9<7b'fs'59hq$*5Uhv##pi^8+hIEBF`nvo`;'l0.^S1<-wUK2/Coh58KKhLj"
- "M=SO*rfO`+qC`W-On.=AJ56>>i2@2LH6A:&5q`?9I3@@'04&p2/LVa*T-4<-i3;M9UvZd+N7>b*eIwg:CC)c<>nO&#<IGe;__.thjZl<%w(Wk2xmp4Q@I#I9,DF]u7-P=.-_:YJ]aS@V"
- "?6*C()dOp7:WL,b&3Rg/.cmM9&r^>$(>.Z-I&J(Q0Hd5Q%7Co-b`-c<N(6r@ip+AurK<m86QIth*#v;-OBqi+L7wDE-Ir8K['m+DDSLwK&/.?-V%U_%3:qKNu$_b*B-kp7NaD'QdWQPK"
- "Yq[@>P)hI;*_F]u`Rb[.j8_Q/<&>uu+VsH$sM9TA%?)(vmJ80),P7E>)tjD%2L=-t#fK[%`v=Q8<FfNkgg^oIbah*#8/Qt$F&:K*-(N/'+1vMB,u()-a.VUU*#[e%gAAO(S>WlA2);Sa"
- ">gXm8YB`1d@K#n]76-a$U,mF<fX]idqd)<3,]J7JmW4`6]uks=4-72L(jEk+:bJ0M^q-8Dm_Z?0olP1C9Sa&H[d&c$ooQUj]Exd*3ZM@-WGW2%s',B-_M%>%Ul:#/'xoFM9QX-$.QN'>"
- "[%$Z$uF6pA6Ki2O5:8w*vP1<-1`[G,)-m#>0`P&#eb#.3i)rtB61(o'$?X3B</R90;eZ]%Ncq;-Tl]#F>2Qft^ae_5tKL9MUe9b*sLEQ95C&`=G?@Mj=wh*'3E>=-<)Gt*Iw)'QG:`@I"
- "wOf7&]1i'S01B+Ev/Nac#9S;=;YQpg_6U`*kVY39xK,[/6Aj7:'1Bm-_1EYfa1+o&o4hp7KN_Q(OlIo@S%;jVdn0'1<Vc52=u`3^o-n1'g4v58Hj&6_t7$##?M)c<$bgQ_'SY((-xkA#"
- "Y(,p'H9rIVY-b,'%bCPF7.J<Up^,(dU1VY*5#WkTU>h19w,WQhLI)3S#f$2(eb,jr*b;3Vw]*7NH%$c4Vs,eD9>XW8?N]o+(*pgC%/72LV-u<Hp,3@e^9UB1J+ak9-TN/mhKPg+AJYd$"
- "MlvAF_jCK*.O-^(63adMT->W%iewS8W6m2rtCpo'RS1R84=@paTKt)>=%&1[)*vp'u+x,VrwN;&]kuO9JDbg=pO$J*.jVe;u'm0dr9l,<*wMK*Oe=g8lV_KEBFkO'oU]^=[-792#ok,)"
- "i]lR8qQ2oA8wcRCZ^7w/Njh;?.stX?Q1>S1q4Bn$)K1<-rGdO'$Wr.Lc.CG)$/*JL4tNR/,SVO3,aUw'DJN:)Ss;wGn9A32ijw%FL+Z0Fn.U9;reSq)bmI32U==5ALuG&#Vf1398/pVo"
- "1*c-(aY168o<`JsSbk-,1N;$>0:OUas(3:8Z972LSfF8eb=c-;>SPw7.6hn3m`9^Xkn(r.qS[0;T%&Qc=+STRxX'q1BNk3&*eu2;&8q$&x>Q#Q7^Tf+6<(d%ZVmj2bDi%.3L2n+4W'$P"
- "iDDG)g,r%+?,$@?uou5tSe2aN_AQU*<h`e-GI7)?OK2A.d7_c)?wQ5AS@DL3r#7fSkgl6-++D:'A,uq7SvlB$pcpH'q3n0#_%dY#xCpr-l<F0NR@-##FEV6NTF6##$l84N1w?AO>'IAO"
- "URQ##V^Fv-XFbGM7Fl(N<3DhLGF%q.1rC$#:T__&Pi68%0xi_&[qFJ(77j_&JWoF.V735&T,[R*:xFR*K5>>#`bW-?4Ne_&6Ne_&6Ne_&n`kr-#GJcM6X;uM6X;uM(.a..^2TkL%oR(#"
- ";u.T%fAr%4tJ8&><1=GHZ_+m9/#H1F^R#SC#*N=BA9(D?v[UiFY>>^8p,KKF.W]L29uLkLlu/+4T<XoIB&hx=T1PcDaB&;HH+-AFr?(m9HZV)FKS8JCw;SD=6[^/DZUL`EUDf]GGlG&>"
- "w$)F./^n3+rlo+DB;5sIYGNk+i1t-69Jg--0pao7Sm#K)pdHW&;LuDNH@H>#/X-TI(;P>#,Gc>#0Su>#4`1?#8lC?#<xU?#@.i?#D:%@#HF7@#LRI@#P_[@#Tkn@#Xw*A#]-=A#a9OA#"
- "d<F&#*;G##.GY##2Sl##6`($#:l:$#>xL$#B.`$#F:r$#JF.%#NR@%#R_R%#Vke%#Zww%#_-4&#3^Rh%Sflr-k'MS.o?.5/sWel/wpEM0%3'/1)K^f1-d>G21&v(35>V`39V7A4=onx4"
- "A1OY5EI0;6Ibgr6M$HS7Q<)58C5w,;WoA*#[%T*#`1g*#d=#+#hI5+#lUG+#pbY+#tnl+#x$),#&1;,#*=M,#.I`,#2Ur,#6b.-#;w[H#iQtA#m^0B#qjBB#uvTB##-hB#'9$C#+E6C#"
- "/QHC#3^ZC#7jmC#;v)D#?,<D#C8ND#GDaD#KPsD#O]/E#g1A5#KA*1#gC17#MGd;#8(02#L-d3#rWM4#Hga1#,<w0#T.j<#O#'2#CYN1#qa^:#_4m3#o@/=#eG8=#t8J5#`+78#4uI-#"
- "m3B2#SB[8#Q0@8#i[*9#iOn8#1Nm;#^sN9#qh<9#:=x-#P;K2#$%X9#bC+.#Rg;<#mN=.#MTF.#RZO.#2?)4#Y#(/#[)1/#b;L/#dAU/#0Sv;#lY$0#n`-0#sf60#(F24#wrH0#%/e0#"
- "TmD<#%JSMFove:CTBEXI:<eh2g)B,3h2^G3i;#d3jD>)4kMYD4lVu`4m`:&5niUA5@(A5BA1]PBB:xlBCC=2CDLXMCEUtiCf&0g2'tN?PGT4CPGT4CPGT4CPGT4CPGT4CPGT4CPGT4CP"
- "GT4CPGT4CPGT4CPGT4CPGT4CPGT4CP-qekC`.9kEg^+F$kwViFJTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5o,^<-28ZI'O?;xp"
- "O?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xp;7q-#lLYI:xvD=#";
-
-static const char* GetDefaultCompressedFontDataTTFBase85()
-{
- return proggy_clean_ttf_compressed_data_base85;
+// Exported using binary_to_compressed_c.exe -u8 "ProggyClean.ttf" proggy_clean_ttf
+static const unsigned int proggy_clean_ttf_compressed_size = 9583;
+static const unsigned char proggy_clean_ttf_compressed_data[9583] =
+{
+ 87,188,0,0,0,0,0,0,0,0,160,248,0,4,0,0,55,0,1,0,0,0,12,0,128,0,3,0,64,79,83,47,50,136,235,116,144,0,0,1,72,130,21,44,78,99,109,97,112,2,18,35,117,0,0,3,160,130,19,36,82,99,118,116,
+ 32,130,23,130,2,33,4,252,130,4,56,2,103,108,121,102,18,175,137,86,0,0,7,4,0,0,146,128,104,101,97,100,215,145,102,211,130,27,32,204,130,3,33,54,104,130,16,39,8,66,1,195,0,0,1,4,130,
+ 15,59,36,104,109,116,120,138,0,126,128,0,0,1,152,0,0,2,6,108,111,99,97,140,115,176,216,0,0,5,130,30,41,2,4,109,97,120,112,1,174,0,218,130,31,32,40,130,16,44,32,110,97,109,101,37,89,
+ 187,150,0,0,153,132,130,19,44,158,112,111,115,116,166,172,131,239,0,0,155,36,130,51,44,210,112,114,101,112,105,2,1,18,0,0,4,244,130,47,32,8,132,203,46,1,0,0,60,85,233,213,95,15,60,
+ 245,0,3,8,0,131,0,34,183,103,119,130,63,43,0,0,189,146,166,215,0,0,254,128,3,128,131,111,130,241,33,2,0,133,0,32,1,130,65,38,192,254,64,0,0,3,128,131,16,130,5,32,1,131,7,138,3,33,2,
+ 0,130,17,36,1,1,0,144,0,130,121,130,23,38,2,0,8,0,64,0,10,130,9,32,118,130,9,130,6,32,0,130,59,33,1,144,131,200,35,2,188,2,138,130,16,32,143,133,7,37,1,197,0,50,2,0,131,0,33,4,9,131,
+ 5,145,3,43,65,108,116,115,0,64,0,0,32,172,8,0,131,0,35,5,0,1,128,131,77,131,3,33,3,128,191,1,33,1,128,130,184,35,0,0,128,0,130,3,131,11,32,1,130,7,33,0,128,131,1,32,1,136,9,32,0,132,
+ 15,135,5,32,1,131,13,135,27,144,35,32,1,149,25,131,21,32,0,130,0,32,128,132,103,130,35,132,39,32,0,136,45,136,97,133,17,130,5,33,0,0,136,19,34,0,128,1,133,13,133,5,32,128,130,15,132,
+ 131,32,3,130,5,32,3,132,27,144,71,32,0,133,27,130,29,130,31,136,29,131,63,131,3,65,63,5,132,5,132,205,130,9,33,0,0,131,9,137,119,32,3,132,19,138,243,130,55,32,1,132,35,135,19,131,201,
+ 136,11,132,143,137,13,130,41,32,0,131,3,144,35,33,128,0,135,1,131,223,131,3,141,17,134,13,136,63,134,15,136,53,143,15,130,96,33,0,3,131,4,130,3,34,28,0,1,130,5,34,0,0,76,130,17,131,
+ 9,36,28,0,4,0,48,130,17,46,8,0,8,0,2,0,0,0,127,0,255,32,172,255,255,130,9,34,0,0,129,132,9,130,102,33,223,213,134,53,132,22,33,1,6,132,6,64,4,215,32,129,165,216,39,177,0,1,141,184,
+ 1,255,133,134,45,33,198,0,193,1,8,190,244,1,28,1,158,2,20,2,136,2,252,3,20,3,88,3,156,3,222,4,20,4,50,4,80,4,98,4,162,5,22,5,102,5,188,6,18,6,116,6,214,7,56,7,126,7,236,8,78,8,108,
+ 8,150,8,208,9,16,9,74,9,136,10,22,10,128,11,4,11,86,11,200,12,46,12,130,12,234,13,94,13,164,13,234,14,80,14,150,15,40,15,176,16,18,16,116,16,224,17,82,17,182,18,4,18,110,18,196,19,
+ 76,19,172,19,246,20,88,20,174,20,234,21,64,21,128,21,166,21,184,22,18,22,126,22,198,23,52,23,142,23,224,24,86,24,186,24,238,25,54,25,150,25,212,26,72,26,156,26,240,27,92,27,200,28,
+ 4,28,76,28,150,28,234,29,42,29,146,29,210,30,64,30,142,30,224,31,36,31,118,31,166,31,166,32,16,130,1,52,46,32,138,32,178,32,200,33,20,33,116,33,152,33,238,34,98,34,134,35,12,130,1,
+ 33,128,35,131,1,60,152,35,176,35,216,36,0,36,74,36,104,36,144,36,174,37,6,37,96,37,130,37,248,37,248,38,88,38,170,130,1,8,190,216,39,64,39,154,40,10,40,104,40,168,41,14,41,32,41,184,
+ 41,248,42,54,42,96,42,96,43,2,43,42,43,94,43,172,43,230,44,32,44,52,44,154,45,40,45,92,45,120,45,170,45,232,46,38,46,166,47,38,47,182,47,244,48,94,48,200,49,62,49,180,50,30,50,158,
+ 51,30,51,130,51,238,52,92,52,206,53,58,53,134,53,212,54,38,54,114,54,230,55,118,55,216,56,58,56,166,57,18,57,116,57,174,58,46,58,154,59,6,59,124,59,232,60,58,60,150,61,34,61,134,61,
+ 236,62,86,62,198,63,42,63,154,64,18,64,106,64,208,65,54,65,162,66,8,66,64,66,122,66,184,66,240,67,98,67,204,68,42,68,138,68,238,69,88,69,182,69,226,70,84,70,180,71,20,71,122,71,218,
+ 72,84,72,198,73,64,0,36,70,21,8,8,77,3,0,7,0,11,0,15,0,19,0,23,0,27,0,31,0,35,0,39,0,43,0,47,0,51,0,55,0,59,0,63,0,67,0,71,0,75,0,79,0,83,0,87,0,91,0,95,0,99,0,103,0,107,0,111,0,115,
+ 0,119,0,123,0,127,0,131,0,135,0,139,0,143,0,0,17,53,51,21,49,150,3,32,5,130,23,32,33,130,3,211,7,151,115,32,128,133,0,37,252,128,128,2,128,128,190,5,133,74,32,4,133,6,206,5,42,0,7,
+ 1,128,0,0,2,0,4,0,0,65,139,13,37,0,1,53,51,21,7,146,3,32,3,130,19,32,1,141,133,32,3,141,14,131,13,38,255,0,128,128,0,6,1,130,84,35,2,128,4,128,140,91,132,89,32,51,65,143,6,139,7,33,
+ 1,0,130,57,32,254,130,3,32,128,132,4,32,4,131,14,138,89,35,0,0,24,0,130,0,33,3,128,144,171,66,55,33,148,115,65,187,19,32,5,130,151,143,155,163,39,32,1,136,182,32,253,134,178,132,7,
+ 132,200,145,17,32,3,65,48,17,165,17,39,0,0,21,0,128,255,128,3,65,175,17,65,3,27,132,253,131,217,139,201,155,233,155,27,131,67,131,31,130,241,33,255,0,131,181,137,232,132,15,132,4,138,
+ 247,34,255,0,128,179,238,32,0,130,0,32,20,65,239,48,33,0,19,67,235,10,32,51,65,203,14,65,215,11,32,7,154,27,135,39,32,33,130,35,33,128,128,130,231,32,253,132,231,32,128,132,232,34,
+ 128,128,254,133,13,136,8,32,253,65,186,5,130,36,130,42,176,234,133,231,34,128,0,0,66,215,44,33,0,1,68,235,6,68,211,19,32,49,68,239,14,139,207,139,47,66,13,7,32,51,130,47,33,1,0,130,
+ 207,35,128,128,1,0,131,222,131,5,130,212,130,6,131,212,32,0,130,10,133,220,130,233,130,226,32,254,133,255,178,233,39,3,1,128,3,0,2,0,4,68,15,7,68,99,12,130,89,130,104,33,128,4,133,
+ 93,130,10,38,0,0,11,1,0,255,0,68,63,16,70,39,9,66,215,8,32,7,68,77,6,68,175,14,32,29,68,195,6,132,7,35,2,0,128,255,131,91,132,4,65,178,5,141,111,67,129,23,165,135,140,107,142,135,33,
+ 21,5,69,71,6,131,7,33,1,0,140,104,132,142,130,4,137,247,140,30,68,255,12,39,11,0,128,0,128,3,0,3,69,171,15,67,251,7,65,15,8,66,249,11,65,229,7,67,211,7,66,13,7,35,1,128,128,254,133,
+ 93,32,254,131,145,132,4,132,18,32,2,151,128,130,23,34,0,0,9,154,131,65,207,8,68,107,15,68,51,7,32,7,70,59,7,135,121,130,82,32,128,151,111,41,0,0,4,0,128,255,0,1,128,1,137,239,33,0,
+ 37,70,145,10,65,77,10,65,212,14,37,0,0,0,5,0,128,66,109,5,70,123,10,33,0,19,72,33,18,133,237,70,209,11,33,0,2,130,113,137,119,136,115,33,1,0,133,43,130,5,34,0,0,10,69,135,6,70,219,
+ 13,66,155,7,65,9,12,66,157,11,66,9,11,32,7,130,141,132,252,66,151,9,137,9,66,15,30,36,0,20,0,128,0,130,218,71,11,42,68,51,8,65,141,7,73,19,15,69,47,23,143,39,66,81,7,32,1,66,55,6,34,
+ 1,128,128,68,25,5,69,32,6,137,6,136,25,32,254,131,42,32,3,66,88,26,148,26,32,0,130,0,32,14,164,231,70,225,12,66,233,7,67,133,19,71,203,15,130,161,32,255,130,155,32,254,139,127,134,
+ 12,164,174,33,0,15,164,159,33,59,0,65,125,20,66,25,7,32,5,68,191,6,66,29,7,144,165,65,105,9,35,128,128,255,0,137,2,133,182,164,169,33,128,128,197,171,130,155,68,235,7,32,21,70,77,19,
+ 66,21,10,68,97,8,66,30,5,66,4,43,34,0,17,0,71,19,41,65,253,20,71,25,23,65,91,15,65,115,7,34,2,128,128,66,9,8,130,169,33,1,0,66,212,13,132,28,72,201,43,35,0,0,0,18,66,27,38,76,231,5,
+ 68,157,20,135,157,32,7,68,185,13,65,129,28,66,20,5,32,253,66,210,11,65,128,49,133,61,32,0,65,135,6,74,111,37,72,149,12,66,203,19,65,147,19,68,93,7,68,85,8,76,4,5,33,255,0,133,129,34,
+ 254,0,128,68,69,8,181,197,34,0,0,12,65,135,32,65,123,20,69,183,27,133,156,66,50,5,72,87,10,67,137,32,33,0,19,160,139,78,251,13,68,55,20,67,119,19,65,91,36,69,177,15,32,254,143,16,65,
+ 98,53,32,128,130,0,32,0,66,43,54,70,141,23,66,23,15,131,39,69,47,11,131,15,70,129,19,74,161,9,36,128,255,0,128,254,130,153,65,148,32,67,41,9,34,0,0,4,79,15,5,73,99,10,71,203,8,32,3,
+ 72,123,6,72,43,8,32,2,133,56,131,99,130,9,34,0,0,6,72,175,5,73,159,14,144,63,135,197,132,189,133,66,33,255,0,73,6,7,70,137,12,35,0,0,0,10,130,3,73,243,25,67,113,12,65,73,7,69,161,7,
+ 138,7,37,21,2,0,128,128,254,134,3,73,116,27,33,128,128,130,111,39,12,0,128,1,0,3,128,2,72,219,21,35,43,0,47,0,67,47,20,130,111,33,21,1,68,167,13,81,147,8,133,230,32,128,77,73,6,32,
+ 128,131,142,134,18,130,6,32,255,75,18,12,131,243,37,128,0,128,3,128,3,74,231,21,135,123,32,29,134,107,135,7,32,21,74,117,7,135,7,134,96,135,246,74,103,23,132,242,33,0,10,67,151,28,
+ 67,133,20,66,141,11,131,11,32,3,77,71,6,32,128,130,113,32,1,81,4,6,134,218,66,130,24,131,31,34,0,26,0,130,0,77,255,44,83,15,11,148,155,68,13,7,32,49,78,231,18,79,7,11,73,243,11,32,
+ 33,65,187,10,130,63,65,87,8,73,239,19,35,0,128,1,0,131,226,32,252,65,100,6,32,128,139,8,33,1,0,130,21,32,253,72,155,44,73,255,20,32,128,71,67,8,81,243,39,67,15,20,74,191,23,68,121,
+ 27,32,1,66,150,6,32,254,79,19,11,131,214,32,128,130,215,37,2,0,128,253,0,128,136,5,65,220,24,147,212,130,210,33,0,24,72,219,42,84,255,13,67,119,16,69,245,19,72,225,19,65,3,15,69,93,
+ 19,131,55,132,178,71,115,14,81,228,6,142,245,33,253,0,132,43,172,252,65,16,11,75,219,8,65,219,31,66,223,24,75,223,10,33,29,1,80,243,10,66,175,8,131,110,134,203,133,172,130,16,70,30,
+ 7,164,183,130,163,32,20,65,171,48,65,163,36,65,143,23,65,151,19,65,147,13,65,134,17,133,17,130,216,67,114,5,164,217,65,137,12,72,147,48,79,71,19,74,169,22,80,251,8,65,173,7,66,157,
+ 15,74,173,15,32,254,65,170,8,71,186,45,72,131,6,77,143,40,187,195,152,179,65,123,38,68,215,57,68,179,15,65,85,7,69,187,14,32,21,66,95,15,67,19,25,32,1,83,223,6,32,2,76,240,7,77,166,
+ 43,65,8,5,130,206,32,0,67,39,54,143,167,66,255,19,82,193,11,151,47,85,171,5,67,27,17,132,160,69,172,11,69,184,56,66,95,6,33,12,1,130,237,32,2,68,179,27,68,175,16,80,135,15,72,55,7,
+ 71,87,12,73,3,12,132,12,66,75,32,76,215,5,169,139,147,135,148,139,81,12,12,81,185,36,75,251,7,65,23,27,76,215,9,87,165,12,65,209,15,72,157,7,65,245,31,32,128,71,128,6,32,1,82,125,5,
+ 34,0,128,254,131,169,32,254,131,187,71,180,9,132,27,32,2,88,129,44,32,0,78,47,40,65,79,23,79,171,14,32,21,71,87,8,72,15,14,65,224,33,130,139,74,27,62,93,23,7,68,31,7,75,27,7,139,15,
+ 74,3,7,74,23,27,65,165,11,65,177,15,67,123,5,32,1,130,221,32,252,71,96,5,74,12,12,133,244,130,25,34,1,0,128,130,2,139,8,93,26,8,65,9,32,65,57,14,140,14,32,0,73,79,67,68,119,11,135,
+ 11,32,51,90,75,14,139,247,65,43,7,131,19,139,11,69,159,11,65,247,6,36,1,128,128,253,0,90,71,9,33,1,0,132,14,32,128,89,93,14,69,133,6,130,44,131,30,131,6,65,20,56,33,0,16,72,179,40,
+ 75,47,12,65,215,19,74,95,19,65,43,11,131,168,67,110,5,75,23,17,69,106,6,75,65,5,71,204,43,32,0,80,75,47,71,203,15,159,181,68,91,11,67,197,7,73,101,13,68,85,6,33,128,128,130,214,130,
+ 25,32,254,74,236,48,130,194,37,0,18,0,128,255,128,77,215,40,65,139,64,32,51,80,159,10,65,147,39,130,219,84,212,43,130,46,75,19,97,74,33,11,65,201,23,65,173,31,33,1,0,79,133,6,66,150,
+ 5,67,75,48,85,187,6,70,207,37,32,71,87,221,13,73,163,14,80,167,15,132,15,83,193,19,82,209,8,78,99,9,72,190,11,77,110,49,89,63,5,80,91,35,99,63,32,70,235,23,81,99,10,69,148,10,65,110,
+ 36,32,0,65,99,47,95,219,11,68,171,51,66,87,7,72,57,7,74,45,17,143,17,65,114,50,33,14,0,65,111,40,159,195,98,135,15,35,7,53,51,21,100,78,9,95,146,16,32,254,82,114,6,32,128,67,208,37,
+ 130,166,99,79,58,32,17,96,99,14,72,31,19,72,87,31,82,155,7,67,47,14,32,21,131,75,134,231,72,51,17,72,78,8,133,8,80,133,6,33,253,128,88,37,9,66,124,36,72,65,12,134,12,71,55,43,66,139,
+ 27,85,135,10,91,33,12,65,35,11,66,131,11,71,32,8,90,127,6,130,244,71,76,11,168,207,33,0,12,66,123,32,32,0,65,183,15,68,135,11,66,111,7,67,235,11,66,111,15,32,254,97,66,12,160,154,67,
+ 227,52,80,33,15,87,249,15,93,45,31,75,111,12,93,45,11,77,99,9,160,184,81,31,12,32,15,98,135,30,104,175,7,77,249,36,69,73,15,78,5,12,32,254,66,151,19,34,128,128,4,87,32,12,149,35,133,
+ 21,96,151,31,32,19,72,35,5,98,173,15,143,15,32,21,143,99,158,129,33,0,0,65,35,52,65,11,15,147,15,98,75,11,33,1,0,143,151,132,15,32,254,99,200,37,132,43,130,4,39,0,10,0,128,1,128,3,
+ 0,104,151,14,97,187,20,69,131,15,67,195,11,87,227,7,33,128,128,132,128,33,254,0,68,131,9,65,46,26,42,0,0,0,7,0,0,255,128,3,128,0,88,223,15,33,0,21,89,61,22,66,209,12,65,2,12,37,0,2,
+ 1,0,3,128,101,83,8,36,0,1,53,51,29,130,3,34,21,1,0,66,53,8,32,0,68,215,6,100,55,25,107,111,9,66,193,11,72,167,8,73,143,31,139,31,33,1,0,131,158,32,254,132,5,33,253,128,65,16,9,133,
+ 17,89,130,25,141,212,33,0,0,93,39,8,90,131,25,93,39,14,66,217,6,106,179,8,159,181,71,125,15,139,47,138,141,87,11,14,76,23,14,65,231,26,140,209,66,122,8,81,179,5,101,195,26,32,47,74,
+ 75,13,69,159,11,83,235,11,67,21,16,136,167,131,106,130,165,130,15,32,128,101,90,24,134,142,32,0,65,103,51,108,23,11,101,231,15,75,173,23,74,237,23,66,15,6,66,46,17,66,58,17,65,105,
+ 49,66,247,55,71,179,12,70,139,15,86,229,7,84,167,15,32,1,95,72,12,89,49,6,33,128,128,65,136,38,66,30,9,32,0,100,239,7,66,247,29,70,105,20,65,141,19,69,81,15,130,144,32,128,83,41,5,
+ 32,255,131,177,68,185,5,133,126,65,97,37,32,0,130,0,33,21,0,130,55,66,195,28,67,155,13,34,79,0,83,66,213,13,73,241,19,66,59,19,65,125,11,135,201,66,249,16,32,128,66,44,11,66,56,17,
+ 68,143,8,68,124,38,67,183,12,96,211,9,65,143,29,112,171,5,32,0,68,131,63,34,33,53,51,71,121,11,32,254,98,251,16,32,253,74,231,10,65,175,37,133,206,37,0,0,8,1,0,0,107,123,11,113,115,
+ 9,33,0,1,130,117,131,3,73,103,7,66,51,18,66,44,5,133,75,70,88,5,32,254,65,39,12,68,80,9,34,12,0,128,107,179,28,68,223,6,155,111,86,147,15,32,2,131,82,141,110,33,254,0,130,15,32,4,103,
+ 184,15,141,35,87,176,5,83,11,5,71,235,23,114,107,11,65,189,16,70,33,15,86,153,31,135,126,86,145,30,65,183,41,32,0,130,0,32,10,65,183,24,34,35,0,39,67,85,9,65,179,15,143,15,33,1,0,65,
+ 28,17,157,136,130,123,32,20,130,3,32,0,97,135,24,115,167,19,80,71,12,32,51,110,163,14,78,35,19,131,19,155,23,77,229,8,78,9,17,151,17,67,231,46,94,135,8,73,31,31,93,215,56,82,171,25,
+ 72,77,8,162,179,169,167,99,131,11,69,85,19,66,215,15,76,129,13,68,115,22,72,79,35,67,113,5,34,0,0,19,70,31,46,65,89,52,73,223,15,85,199,33,95,33,8,132,203,73,29,32,67,48,16,177,215,
+ 101,13,15,65,141,43,69,141,15,75,89,5,70,0,11,70,235,21,178,215,36,10,0,128,0,0,71,207,24,33,0,19,100,67,6,80,215,11,66,67,7,80,43,12,71,106,7,80,192,5,65,63,5,66,217,26,33,0,13,156,
+ 119,68,95,5,72,233,12,134,129,85,81,11,76,165,20,65,43,8,73,136,8,75,10,31,38,128,128,0,0,0,13,1,130,4,32,3,106,235,29,114,179,12,66,131,23,32,7,77,133,6,67,89,12,131,139,116,60,9,
+ 89,15,37,32,0,74,15,7,103,11,22,65,35,5,33,55,0,93,81,28,67,239,23,78,85,5,107,93,14,66,84,17,65,193,26,74,183,10,66,67,34,143,135,79,91,15,32,7,117,111,8,75,56,9,84,212,9,154,134,
+ 32,0,130,0,32,18,130,3,70,171,41,83,7,16,70,131,19,84,191,15,84,175,19,84,167,30,84,158,12,154,193,68,107,15,33,0,0,65,79,42,65,71,7,73,55,7,118,191,16,83,180,9,32,255,76,166,9,154,
+ 141,32,0,130,0,69,195,52,65,225,15,151,15,75,215,31,80,56,10,68,240,17,100,32,9,70,147,39,65,93,12,71,71,41,92,85,15,84,135,23,78,35,15,110,27,10,84,125,8,107,115,29,136,160,38,0,0,
+ 14,0,128,255,0,82,155,24,67,239,8,119,255,11,69,131,11,77,29,6,112,31,8,134,27,105,203,8,32,2,75,51,11,75,195,12,74,13,29,136,161,37,128,0,0,0,11,1,130,163,82,115,8,125,191,17,69,35,
+ 12,74,137,15,143,15,32,1,65,157,12,136,12,161,142,65,43,40,65,199,6,65,19,24,102,185,11,76,123,11,99,6,12,135,12,32,254,130,8,161,155,101,23,9,39,8,0,0,1,128,3,128,2,78,63,17,72,245,
+ 12,67,41,11,90,167,9,32,128,97,49,9,32,128,109,51,14,132,97,81,191,8,130,97,125,99,12,121,35,9,127,75,15,71,79,12,81,151,23,87,97,7,70,223,15,80,245,16,105,97,15,32,254,113,17,6,32,
+ 128,130,8,105,105,8,76,122,18,65,243,21,74,63,7,38,4,1,0,255,0,2,0,119,247,28,133,65,32,255,141,91,35,0,0,0,16,67,63,36,34,59,0,63,77,59,9,119,147,11,143,241,66,173,15,66,31,11,67,
+ 75,8,81,74,16,32,128,131,255,87,181,42,127,43,5,34,255,128,2,120,235,11,37,19,0,23,0,0,37,109,191,14,118,219,7,127,43,14,65,79,14,35,0,0,0,3,73,91,5,130,5,38,3,0,7,0,11,0,0,70,205,
+ 11,88,221,12,32,0,73,135,7,87,15,22,73,135,10,79,153,15,97,71,19,65,49,11,32,1,131,104,121,235,11,80,65,11,142,179,144,14,81,123,46,32,1,88,217,5,112,5,8,65,201,15,83,29,15,122,147,
+ 11,135,179,142,175,143,185,67,247,39,66,199,7,35,5,0,128,3,69,203,15,123,163,12,67,127,7,130,119,71,153,10,141,102,70,175,8,32,128,121,235,30,136,89,100,191,11,116,195,11,111,235,15,
+ 72,39,7,32,2,97,43,5,132,5,94,67,8,131,8,125,253,10,32,3,65,158,16,146,16,130,170,40,0,21,0,128,0,0,3,128,5,88,219,15,24,64,159,32,135,141,65,167,15,68,163,10,97,73,49,32,255,82,58,
+ 7,93,80,8,97,81,16,24,67,87,52,34,0,0,5,130,231,33,128,2,80,51,13,65,129,8,113,61,6,132,175,65,219,5,130,136,77,152,17,32,0,95,131,61,70,215,6,33,21,51,90,53,10,78,97,23,105,77,31,
+ 65,117,7,139,75,24,68,195,9,24,64,22,9,33,0,128,130,11,33,128,128,66,25,5,121,38,5,134,5,134,45,66,40,36,66,59,18,34,128,0,0,66,59,81,135,245,123,103,19,120,159,19,77,175,12,33,255,
+ 0,87,29,10,94,70,21,66,59,54,39,3,1,128,3,0,2,128,4,24,65,7,15,66,47,7,72,98,12,37,0,0,0,3,1,0,24,65,55,21,131,195,32,1,67,178,6,33,4,0,77,141,8,32,6,131,47,74,67,16,24,69,3,20,24,
+ 65,251,7,133,234,130,229,94,108,17,35,0,0,6,0,141,175,86,59,5,162,79,85,166,8,70,112,13,32,13,24,64,67,26,24,71,255,7,123,211,12,80,121,11,69,215,15,66,217,11,69,71,10,131,113,132,
+ 126,119,90,9,66,117,19,132,19,32,0,130,0,24,64,47,59,33,7,0,73,227,5,68,243,15,85,13,12,76,37,22,74,254,15,130,138,33,0,4,65,111,6,137,79,65,107,16,32,1,77,200,6,34,128,128,3,75,154,
+ 12,37,0,16,0,0,2,0,104,115,36,140,157,68,67,19,68,51,15,106,243,15,134,120,70,37,10,68,27,10,140,152,65,121,24,32,128,94,155,7,67,11,8,24,74,11,25,65,3,12,83,89,18,82,21,37,67,200,
+ 5,130,144,24,64,172,12,33,4,0,134,162,74,80,14,145,184,32,0,130,0,69,251,20,32,19,81,243,5,82,143,8,33,5,53,89,203,5,133,112,79,109,15,33,0,21,130,71,80,175,41,36,75,0,79,0,83,121,
+ 117,9,87,89,27,66,103,11,70,13,15,75,191,11,135,67,87,97,20,109,203,5,69,246,8,108,171,5,78,195,38,65,51,13,107,203,11,77,3,17,24,75,239,17,65,229,28,79,129,39,130,175,32,128,123,253,
+ 7,132,142,24,65,51,15,65,239,41,36,128,128,0,0,13,65,171,5,66,163,28,136,183,118,137,11,80,255,15,67,65,7,74,111,8,32,0,130,157,32,253,24,76,35,10,103,212,5,81,175,9,69,141,7,66,150,
+ 29,131,158,24,75,199,28,124,185,7,76,205,15,68,124,14,32,3,123,139,16,130,16,33,128,128,108,199,6,33,0,3,65,191,35,107,11,6,73,197,11,24,70,121,15,83,247,15,24,70,173,23,69,205,14,
+ 32,253,131,140,32,254,136,4,94,198,9,32,3,78,4,13,66,127,13,143,13,32,0,130,0,33,16,0,24,69,59,39,109,147,12,76,253,19,24,69,207,15,69,229,15,130,195,71,90,10,139,10,130,152,73,43,
+ 40,91,139,10,65,131,37,35,75,0,79,0,84,227,12,143,151,68,25,15,80,9,23,95,169,11,34,128,2,128,112,186,5,130,6,83,161,19,76,50,6,130,37,65,145,44,110,83,5,32,16,67,99,6,71,67,15,76,
+ 55,17,140,215,67,97,23,76,69,15,77,237,11,104,211,23,77,238,11,65,154,43,33,0,10,83,15,28,83,13,20,67,145,19,67,141,14,97,149,21,68,9,15,86,251,5,66,207,5,66,27,37,82,1,23,127,71,12,
+ 94,235,10,110,175,24,98,243,15,132,154,132,4,24,66,69,10,32,4,67,156,43,130,198,35,2,1,0,4,75,27,9,69,85,9,95,240,7,32,128,130,35,32,28,66,43,40,24,82,63,23,83,123,12,72,231,15,127,
+ 59,23,116,23,19,117,71,7,24,77,99,15,67,111,15,71,101,8,36,2,128,128,252,128,127,60,11,32,1,132,16,130,18,141,24,67,107,9,32,3,68,194,15,175,15,38,0,11,0,128,1,128,2,80,63,25,32,0,
+ 24,65,73,11,69,185,15,83,243,16,32,0,24,81,165,8,130,86,77,35,6,155,163,88,203,5,24,66,195,30,70,19,19,24,80,133,15,32,1,75,211,8,32,254,108,133,8,79,87,20,65,32,9,41,0,0,7,0,128,0,
+ 0,2,128,2,68,87,15,66,1,16,92,201,16,24,76,24,17,133,17,34,128,0,30,66,127,64,34,115,0,119,73,205,9,66,43,11,109,143,15,24,79,203,11,90,143,15,131,15,155,31,65,185,15,86,87,11,35,128,
+ 128,253,0,69,7,6,130,213,33,1,0,119,178,15,142,17,66,141,74,83,28,6,36,7,0,0,4,128,82,39,18,76,149,12,67,69,21,32,128,79,118,15,32,0,130,0,32,8,131,206,32,2,79,83,9,100,223,14,102,
+ 113,23,115,115,7,24,65,231,12,130,162,32,4,68,182,19,130,102,93,143,8,69,107,29,24,77,255,12,143,197,72,51,7,76,195,15,132,139,85,49,15,130,152,131,18,71,81,23,70,14,11,36,0,10,0,128,
+ 2,69,59,9,89,151,15,66,241,11,76,165,12,71,43,15,75,49,13,65,12,23,132,37,32,0,179,115,130,231,95,181,16,132,77,32,254,67,224,8,65,126,20,79,171,8,32,2,89,81,5,75,143,6,80,41,8,34,
+ 2,0,128,24,81,72,9,32,0,130,0,35,17,0,0,255,77,99,39,95,65,36,67,109,15,24,69,93,11,77,239,5,95,77,23,35,128,1,0,128,24,86,7,8,132,167,32,2,69,198,41,130,202,33,0,26,120,75,44,24,89,
+ 51,15,71,243,12,70,239,11,24,84,3,11,66,7,11,71,255,10,32,21,69,155,35,88,151,12,32,128,74,38,10,65,210,8,74,251,5,65,226,5,75,201,13,32,3,65,9,41,146,41,40,0,0,0,9,1,0,1,0,2,91,99,
+ 19,32,35,106,119,13,70,219,15,83,239,12,137,154,32,2,67,252,19,36,128,0,0,4,1,130,196,32,2,130,8,91,107,8,32,0,135,81,24,73,211,8,132,161,73,164,13,36,0,8,0,128,2,105,123,26,139,67,
+ 76,99,15,34,1,0,128,135,76,83,156,20,92,104,8,67,251,30,24,86,47,27,123,207,12,24,86,7,15,71,227,8,32,4,65,20,20,131,127,32,0,130,123,32,0,71,223,26,32,19,90,195,22,71,223,15,84,200,
+ 6,32,128,133,241,24,84,149,9,67,41,25,36,0,0,0,22,0,88,111,49,32,87,66,21,5,77,3,27,123,75,7,71,143,19,135,183,71,183,19,130,171,74,252,5,131,5,89,87,17,32,1,132,18,130,232,68,11,10,
+ 33,1,128,70,208,16,66,230,18,147,18,130,254,223,255,75,27,23,65,59,15,135,39,155,255,34,128,128,254,104,92,8,33,0,128,65,32,11,65,1,58,33,26,0,130,0,72,71,18,78,55,17,76,11,19,86,101,
+ 12,75,223,11,89,15,11,24,76,87,15,75,235,15,131,15,72,95,7,85,71,11,72,115,11,73,64,6,34,1,128,128,66,215,9,34,128,254,128,134,14,33,128,255,67,102,5,32,0,130,16,70,38,11,66,26,57,
+ 88,11,8,24,76,215,34,78,139,7,95,245,7,32,7,24,73,75,23,32,128,131,167,130,170,101,158,9,82,49,22,118,139,6,32,18,67,155,44,116,187,9,108,55,14,80,155,23,66,131,15,93,77,10,131,168,
+ 32,128,73,211,12,24,75,187,22,32,4,96,71,20,67,108,19,132,19,120,207,8,32,5,76,79,15,66,111,21,66,95,8,32,3,190,211,111,3,8,211,212,32,20,65,167,44,34,75,0,79,97,59,13,32,33,112,63,
+ 10,65,147,19,69,39,19,143,39,24,66,71,9,130,224,65,185,43,94,176,12,65,183,24,71,38,8,24,72,167,7,65,191,38,136,235,24,96,167,12,65,203,62,115,131,13,65,208,42,175,235,67,127,6,32,
+ 4,76,171,29,114,187,5,32,71,65,211,5,65,203,68,72,51,8,164,219,32,0,172,214,71,239,58,78,3,27,66,143,15,77,19,15,147,31,35,33,53,51,21,66,183,10,173,245,66,170,30,150,30,34,0,0,23,
+ 80,123,54,76,1,16,73,125,15,82,245,11,167,253,24,76,85,12,70,184,5,32,254,131,185,37,254,0,128,1,0,128,133,16,117,158,18,92,27,38,65,3,17,130,251,35,17,0,128,254,24,69,83,39,140,243,
+ 121,73,19,109,167,7,81,41,15,24,95,175,12,102,227,15,121,96,11,24,95,189,7,32,3,145,171,154,17,24,77,47,9,33,0,5,70,71,37,68,135,7,32,29,117,171,11,69,87,15,24,79,97,19,24,79,149,23,
+ 131,59,32,1,75,235,5,72,115,11,72,143,7,132,188,71,27,46,131,51,32,0,69,95,6,175,215,32,21,131,167,81,15,19,151,191,151,23,131,215,71,43,5,32,254,24,79,164,24,74,109,8,77,166,13,65,
+ 176,26,88,162,5,98,159,6,171,219,120,247,6,79,29,8,99,169,10,103,59,19,65,209,35,131,35,91,25,19,112,94,15,83,36,8,173,229,33,20,0,88,75,43,71,31,12,65,191,71,33,1,0,130,203,32,254,
+ 131,4,68,66,7,67,130,6,104,61,13,173,215,38,13,1,0,0,0,2,128,67,111,28,74,129,16,104,35,19,79,161,16,87,14,7,138,143,132,10,67,62,36,114,115,5,162,151,67,33,16,108,181,15,143,151,67,
+ 5,5,24,100,242,15,170,153,34,0,0,14,65,51,34,32,55,79,75,9,32,51,74,7,10,65,57,38,132,142,32,254,72,0,14,139,163,32,128,80,254,8,67,158,21,65,63,7,32,4,72,227,27,95,155,12,67,119,19,
+ 124,91,24,149,154,72,177,34,97,223,8,155,151,24,108,227,15,88,147,16,72,117,19,68,35,11,92,253,15,70,199,15,24,87,209,17,32,2,87,233,7,32,1,24,88,195,10,119,24,8,32,3,81,227,24,65,
+ 125,21,35,128,128,0,25,76,59,48,24,90,187,9,97,235,12,66,61,11,91,105,19,24,79,141,11,24,79,117,15,24,79,129,27,90,53,13,130,13,32,253,131,228,24,79,133,40,69,70,8,66,137,31,65,33,
+ 19,96,107,8,68,119,29,66,7,5,68,125,16,65,253,19,65,241,27,24,90,179,13,24,79,143,18,33,128,128,130,246,32,254,130,168,68,154,36,77,51,9,97,47,5,167,195,32,21,131,183,78,239,27,155,
+ 195,78,231,14,201,196,77,11,6,32,5,73,111,37,97,247,12,77,19,31,155,207,78,215,19,162,212,69,17,14,66,91,19,80,143,57,78,203,39,159,215,32,128,93,134,8,24,80,109,24,66,113,15,169,215,
+ 66,115,6,32,4,69,63,33,32,0,101,113,7,86,227,35,143,211,36,49,53,51,21,1,77,185,14,65,159,28,69,251,34,67,56,8,33,9,0,24,107,175,25,90,111,12,110,251,11,119,189,24,119,187,34,87,15,
+ 9,32,4,66,231,37,90,39,7,66,239,8,84,219,15,69,105,23,24,85,27,27,87,31,11,33,1,128,76,94,6,32,1,85,241,7,33,128,128,106,48,10,33,128,128,69,136,11,133,13,24,79,116,49,84,236,8,24,
+ 91,87,9,32,5,165,255,69,115,12,66,27,15,159,15,24,72,247,12,74,178,5,24,80,64,15,33,0,128,143,17,77,89,51,130,214,24,81,43,7,170,215,74,49,8,159,199,143,31,139,215,69,143,5,32,254,
+ 24,81,50,35,181,217,84,123,70,143,195,159,15,65,187,16,66,123,7,65,175,15,65,193,29,68,207,39,79,27,5,70,131,6,32,4,68,211,33,33,67,0,83,143,14,159,207,143,31,140,223,33,0,128,24,80,
+ 82,14,24,93,16,23,32,253,65,195,5,68,227,40,133,214,107,31,7,32,5,67,115,27,87,9,8,107,31,43,66,125,6,32,0,103,177,23,131,127,72,203,36,32,0,110,103,8,155,163,73,135,6,32,19,24,112,
+ 99,10,65,71,11,73,143,19,143,31,126,195,5,24,85,21,9,24,76,47,14,32,254,24,93,77,36,68,207,11,39,25,0,0,255,128,3,128,4,66,51,37,95,247,13,82,255,24,76,39,19,147,221,66,85,27,24,118,
+ 7,8,24,74,249,12,76,74,8,91,234,8,67,80,17,131,222,33,253,0,121,30,44,73,0,16,69,15,6,32,0,65,23,38,69,231,12,65,179,6,98,131,16,86,31,27,24,108,157,14,80,160,8,24,65,46,17,33,4,0,
+ 96,2,18,144,191,65,226,8,68,19,5,171,199,80,9,15,180,199,67,89,5,32,255,24,79,173,28,174,201,24,79,179,50,32,1,24,122,5,10,82,61,10,180,209,83,19,8,32,128,24,80,129,27,111,248,43,131,
+ 71,24,115,103,8,67,127,41,78,213,24,100,247,19,66,115,39,75,107,5,32,254,165,219,78,170,40,24,112,163,49,32,1,97,203,6,65,173,64,32,0,83,54,7,133,217,88,37,12,32,254,131,28,33,128,
+ 3,67,71,44,84,183,6,32,5,69,223,33,96,7,7,123,137,16,192,211,24,112,14,9,32,255,67,88,29,68,14,10,84,197,38,33,0,22,116,47,50,32,87,106,99,9,116,49,15,89,225,15,97,231,23,70,41,19,
+ 82,85,8,93,167,6,32,253,132,236,108,190,7,89,251,5,116,49,58,33,128,128,131,234,32,15,24,74,67,38,70,227,24,24,83,45,23,89,219,12,70,187,12,89,216,19,32,2,69,185,24,141,24,70,143,66,
+ 24,82,119,56,78,24,10,32,253,133,149,132,6,24,106,233,7,69,198,48,178,203,81,243,12,68,211,15,106,255,23,66,91,15,69,193,7,100,39,10,24,83,72,16,176,204,33,19,0,88,207,45,68,21,12,
+ 68,17,10,65,157,53,68,17,6,32,254,92,67,10,65,161,25,69,182,43,24,118,91,47,69,183,18,181,209,111,253,12,89,159,8,66,112,12,69,184,45,35,0,0,0,9,24,80,227,26,73,185,16,118,195,15,131,
+ 15,33,1,0,65,59,15,66,39,27,160,111,66,205,12,148,111,143,110,33,128,128,156,112,24,81,199,8,75,199,23,66,117,20,155,121,32,254,68,126,12,72,213,29,134,239,149,123,89,27,16,148,117,
+ 65,245,8,24,71,159,14,141,134,134,28,73,51,55,109,77,15,105,131,11,68,67,11,76,169,27,107,209,12,102,174,8,32,128,72,100,18,116,163,56,79,203,11,75,183,44,85,119,19,71,119,23,151,227,
+ 32,1,93,27,8,65,122,5,77,102,8,110,120,20,66,23,8,66,175,17,66,63,12,133,12,79,35,8,74,235,33,67,149,16,69,243,15,78,57,15,69,235,16,67,177,7,151,192,130,23,67,84,29,141,192,174,187,
+ 77,67,15,69,11,12,159,187,77,59,10,199,189,24,70,235,50,96,83,19,66,53,23,105,65,19,77,47,12,163,199,66,67,37,78,207,50,67,23,23,174,205,67,228,6,71,107,13,67,22,14,66,85,11,83,187,
+ 38,124,47,49,95,7,19,66,83,23,67,23,19,24,96,78,17,80,101,16,71,98,40,33,0,7,88,131,22,24,89,245,12,84,45,12,102,213,5,123,12,9,32,2,126,21,14,43,255,0,128,128,0,0,20,0,128,255,128,
+ 3,126,19,39,32,75,106,51,7,113,129,15,24,110,135,19,126,47,15,115,117,11,69,47,11,32,2,109,76,9,102,109,9,32,128,75,2,10,130,21,32,254,69,47,6,32,3,94,217,47,32,0,65,247,10,69,15,46,
+ 65,235,31,65,243,15,101,139,10,66,174,14,65,247,16,72,102,28,69,17,14,84,243,9,165,191,88,47,48,66,53,12,32,128,71,108,6,203,193,32,17,75,187,42,73,65,16,65,133,52,114,123,9,167,199,
+ 69,21,37,86,127,44,75,171,11,180,197,78,213,12,148,200,81,97,46,24,95,243,9,32,4,66,75,33,113,103,9,87,243,36,143,225,24,84,27,31,90,145,8,148,216,67,49,5,24,84,34,14,75,155,27,67,
+ 52,13,140,13,36,0,20,0,128,255,24,135,99,46,88,59,43,155,249,80,165,7,136,144,71,161,23,32,253,132,33,32,254,88,87,44,136,84,35,128,0,0,21,81,103,5,94,47,44,76,51,12,143,197,151,15,
+ 65,215,31,24,64,77,13,65,220,20,65,214,14,71,4,40,65,213,13,32,0,130,0,35,21,1,2,0,135,0,34,36,0,72,134,10,36,1,0,26,0,130,134,11,36,2,0,14,0,108,134,11,32,3,138,23,32,4,138,11,34,
+ 5,0,20,134,33,34,0,0,6,132,23,32,1,134,15,32,18,130,25,133,11,37,1,0,13,0,49,0,133,11,36,2,0,7,0,38,134,11,36,3,0,17,0,45,134,11,32,4,138,35,36,5,0,10,0,62,134,23,32,6,132,23,36,3,
+ 0,1,4,9,130,87,131,167,133,11,133,167,133,11,133,167,133,11,37,3,0,34,0,122,0,133,11,133,167,133,11,133,167,133,11,133,167,34,50,0,48,130,1,34,52,0,47,134,5,8,49,49,0,53,98,121,32,
+ 84,114,105,115,116,97,110,32,71,114,105,109,109,101,114,82,101,103,117,108,97,114,84,84,88,32,80,114,111,103,103,121,67,108,101,97,110,84,84,50,48,48,52,47,130,2,53,49,53,0,98,0,121,
+ 0,32,0,84,0,114,0,105,0,115,0,116,0,97,0,110,130,15,32,71,132,15,36,109,0,109,0,101,130,9,32,82,130,5,36,103,0,117,0,108,130,29,32,114,130,43,34,84,0,88,130,35,32,80,130,25,34,111,
+ 0,103,130,1,34,121,0,67,130,27,32,101,132,59,32,84,130,31,33,0,0,65,155,9,34,20,0,0,65,11,6,130,8,135,2,33,1,1,130,9,8,120,1,1,2,1,3,1,4,1,5,1,6,1,7,1,8,1,9,1,10,1,11,1,12,1,13,1,14,
+ 1,15,1,16,1,17,1,18,1,19,1,20,1,21,1,22,1,23,1,24,1,25,1,26,1,27,1,28,1,29,1,30,1,31,1,32,0,3,0,4,0,5,0,6,0,7,0,8,0,9,0,10,0,11,0,12,0,13,0,14,0,15,0,16,0,17,0,18,0,19,0,20,0,21,0,
+ 22,0,23,0,24,0,25,0,26,0,27,0,28,0,29,0,30,0,31,130,187,8,66,33,0,34,0,35,0,36,0,37,0,38,0,39,0,40,0,41,0,42,0,43,0,44,0,45,0,46,0,47,0,48,0,49,0,50,0,51,0,52,0,53,0,54,0,55,0,56,0,
+ 57,0,58,0,59,0,60,0,61,0,62,0,63,0,64,0,65,0,66,130,243,9,75,68,0,69,0,70,0,71,0,72,0,73,0,74,0,75,0,76,0,77,0,78,0,79,0,80,0,81,0,82,0,83,0,84,0,85,0,86,0,87,0,88,0,89,0,90,0,91,0,
+ 92,0,93,0,94,0,95,0,96,0,97,1,33,1,34,1,35,1,36,1,37,1,38,1,39,1,40,1,41,1,42,1,43,1,44,1,45,1,46,1,47,1,48,1,49,1,50,1,51,1,52,1,53,1,54,1,55,1,56,1,57,1,58,1,59,1,60,1,61,1,62,1,
+ 63,1,64,1,65,0,172,0,163,0,132,0,133,0,189,0,150,0,232,0,134,0,142,0,139,0,157,0,169,0,164,0,239,0,138,0,218,0,131,0,147,0,242,0,243,0,141,0,151,0,136,0,195,0,222,0,241,0,158,0,170,
+ 0,245,0,244,0,246,0,162,0,173,0,201,0,199,0,174,0,98,0,99,0,144,0,100,0,203,0,101,0,200,0,202,0,207,0,204,0,205,0,206,0,233,0,102,0,211,0,208,0,209,0,175,0,103,0,240,0,145,0,214,0,
+ 212,0,213,0,104,0,235,0,237,0,137,0,106,0,105,0,107,0,109,0,108,0,110,0,160,0,111,0,113,0,112,0,114,0,115,0,117,0,116,0,118,0,119,0,234,0,120,0,122,0,121,0,123,0,125,0,124,0,184,0,
+ 161,0,127,0,126,0,128,0,129,0,236,0,238,0,186,14,117,110,105,99,111,100,101,35,48,120,48,48,48,49,141,14,32,50,141,14,32,51,141,14,32,52,141,14,32,53,141,14,32,54,141,14,32,55,141,
+ 14,32,56,141,14,32,57,141,14,32,97,141,14,32,98,141,14,32,99,141,14,32,100,141,14,32,101,141,14,32,102,140,14,33,49,48,141,14,141,239,32,49,141,239,32,49,141,239,32,49,141,239,32,49,
+ 141,239,32,49,141,239,32,49,141,239,32,49,141,239,32,49,141,239,32,49,141,239,32,49,141,239,32,49,141,239,32,49,141,239,32,49,141,239,45,49,102,6,100,101,108,101,116,101,4,69,117,114,
+ 111,140,236,32,56,141,236,32,56,141,236,32,56,141,236,32,56,141,236,32,56,141,236,32,56,141,236,32,56,141,236,32,56,141,236,32,56,141,236,32,56,141,236,32,56,141,236,32,56,141,236,
+ 32,56,141,236,32,56,141,236,32,56,65,220,13,32,57,65,220,13,32,57,141,239,32,57,141,239,32,57,141,239,32,57,141,239,32,57,141,239,32,57,141,239,32,57,141,239,32,57,141,239,32,57,141,
+ 239,32,57,141,239,32,57,141,239,32,57,141,239,32,57,141,239,32,57,141,239,35,57,102,0,0,5,250,72,249,98,247,
+};
+
+static const char* GetDefaultCompressedFontDataTTF(int* out_size)
+{
+ *out_size = proggy_clean_ttf_compressed_size;
+ return (const char*)proggy_clean_ttf_compressed_data;
}
+#endif // #ifndef IMGUI_DISABLE_DEFAULT_FONT
#endif // #ifndef IMGUI_DISABLE
diff --git a/source/code/Libs/imgui/imgui_internal.h b/source/code/Libs/imgui/imgui_internal.h index 8e17ec3..aa2b239 100644 --- a/source/code/Libs/imgui/imgui_internal.h +++ b/source/code/Libs/imgui/imgui_internal.h
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.4
+// dear imgui, v1.92.3
// (internal structures/api)
// You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility.
@@ -14,6 +14,7 @@ Index of this file:
// [SECTION] Macros
// [SECTION] Generic helpers
// [SECTION] ImDrawList support
+// [SECTION] Style support
// [SECTION] Data types support
// [SECTION] Widgets support: flags, enums, data structures
// [SECTION] Popup support
@@ -36,6 +37,7 @@ Index of this file:
// [SECTION] Tab bar, Tab item support
// [SECTION] Table support
// [SECTION] ImGui internal API
+// [SECTION] ImFontLoader
// [SECTION] ImFontAtlas internal API
// [SECTION] Test Engine specific hooks (imgui_test_engine)
@@ -61,14 +63,22 @@ Index of this file:
#if (defined __SSE__ || defined __x86_64__ || defined _M_X64 || (defined(_M_IX86_FP) && (_M_IX86_FP >= 1))) && !defined(IMGUI_DISABLE_SSE)
#define IMGUI_ENABLE_SSE
#include <immintrin.h>
+#if (defined __AVX__ || defined __SSE4_2__)
+#define IMGUI_ENABLE_SSE4_2
+#include <nmmintrin.h>
+#endif
+#endif
+// Emscripten has partial SSE 4.2 support where _mm_crc32_u32 is not available. See https://emscripten.org/docs/porting/simd.html#id11 and #8213
+#if defined(IMGUI_ENABLE_SSE4_2) && !defined(IMGUI_USE_LEGACY_CRC32_ADLER) && !defined(__EMSCRIPTEN__)
+#define IMGUI_ENABLE_SSE4_2_CRC
#endif
// Visual Studio warnings
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable: 4251) // class 'xxx' needs to have dll-interface to be used by clients of struct 'xxx' // when IMGUI_API is set to__declspec(dllexport)
-#pragma warning (disable: 26812) // The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3). [MSVC Static Analyzer)
#pragma warning (disable: 26495) // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
+#pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
#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
@@ -82,18 +92,18 @@ Index of this file:
#endif
#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
#pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants ok, for ImFloor()
-#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"
-#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
-#pragma clang diagnostic ignored "-Wdouble-promotion"
+#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast
+#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant
+#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
#pragma clang diagnostic ignored "-Wmissing-noreturn" // warning: function 'xxx' could be declared with attribute 'noreturn'
#pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion"// warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated
#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access
+#pragma clang diagnostic ignored "-Wnontrivial-memaccess" // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
#elif defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
+#pragma GCC diagnostic ignored "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe
#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 "-Wdeprecated-enum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated
#endif
@@ -122,16 +132,26 @@ Index of this file:
// [SECTION] Forward declarations
//-----------------------------------------------------------------------------
+// Utilities
+// (other types which are not forwarded declared are: ImBitArray<>, ImSpan<>, ImSpanAllocator<>, ImStableVector<>, ImPool<>, ImChunkStream<>)
struct ImBitVector; // Store 1-bit per value
struct ImRect; // An axis-aligned rectangle (2 points)
+struct ImGuiTextIndex; // Maintain a line index for a text buffer.
+
+// ImDrawList/ImFontAtlas
struct ImDrawDataBuilder; // Helper to build a ImDrawData instance
struct ImDrawListSharedData; // Data shared between all ImDrawList instances
+struct ImFontAtlasBuilder; // Internal storage for incrementally packing and building a ImFontAtlas
+struct ImFontAtlasPostProcessData; // Data available to potential texture post-processing functions
+struct ImFontAtlasRectEntry; // Packed rectangle lookup entry
+
+// ImGui
struct ImGuiBoxSelectState; // Box-selection state (currently used by multi-selection, could potentially be used by others)
struct ImGuiColorMod; // Stacked color modifier, backup of modified data so we can restore it
struct ImGuiContext; // Main Dear ImGui context
struct ImGuiContextHook; // Hook for extensions like ImGuiTestEngine
-struct ImGuiDataVarInfo; // Variable information (e.g. to access style variables from an enum)
struct ImGuiDataTypeInfo; // Type information associated to a ImGuiDataType enum
+struct ImGuiDeactivatedItemData; // Data for IsItemDeactivated()/IsItemDeactivatedAfterEdit() function.
struct ImGuiDockContext; // Docking system context
struct ImGuiDockRequest; // Docking system dock/undock queued request
struct ImGuiDockNode; // Docking system node (hold a list of Windows OR two child dock nodes)
@@ -154,6 +174,7 @@ struct ImGuiOldColumns; // Storage data for a columns set for legacy
struct ImGuiPopupData; // Storage for current popup stack
struct ImGuiSettingsHandler; // Storage for one type registered in the .ini file
struct ImGuiStyleMod; // Stacked style modifier, backup of modified data so we can restore it
+struct ImGuiStyleVarInfo; // Style variable information (e.g. to access style variables from an enum)
struct ImGuiTabBar; // Storage for a tab bar
struct ImGuiTabItem; // Storage for a tab item (within a tab bar)
struct ImGuiTable; // Storage for a table
@@ -178,11 +199,13 @@ typedef int ImGuiDataAuthority; // -> enum ImGuiDataAuthority_ // E
typedef int ImGuiLayoutType; // -> enum ImGuiLayoutType_ // Enum: Horizontal or vertical
// Flags
+typedef int ImDrawTextFlags; // -> enum ImDrawTextFlags_ // Flags: for ImTextCalcWordWrapPositionEx()
typedef int ImGuiActivateFlags; // -> enum ImGuiActivateFlags_ // Flags: for navigation/focus function (will be for ActivateItem() later)
typedef int ImGuiDebugLogFlags; // -> enum ImGuiDebugLogFlags_ // Flags: for ShowDebugLogWindow(), g.DebugLogFlags
typedef int ImGuiFocusRequestFlags; // -> enum ImGuiFocusRequestFlags_ // Flags: for FocusWindow()
typedef int ImGuiItemStatusFlags; // -> enum ImGuiItemStatusFlags_ // Flags: for g.LastItemData.StatusFlags
typedef int ImGuiOldColumnFlags; // -> enum ImGuiOldColumnFlags_ // Flags: for BeginColumns()
+typedef int ImGuiLogFlags; // -> enum ImGuiLogFlags_ // Flags: for LogBegin() text capturing function
typedef int ImGuiNavRenderCursorFlags; // -> enum ImGuiNavRenderCursorFlags_//Flags: for RenderNavCursor()
typedef int ImGuiNavMoveFlags; // -> enum ImGuiNavMoveFlags_ // Flags: for navigation requests
typedef int ImGuiNextItemDataFlags; // -> enum ImGuiNextItemDataFlags_ // Flags: for SetNextItemXXX() functions
@@ -194,6 +217,10 @@ typedef int ImGuiTooltipFlags; // -> enum ImGuiTooltipFlags_ // F
typedef int ImGuiTypingSelectFlags; // -> enum ImGuiTypingSelectFlags_ // Flags: for GetTypingSelectRequest()
typedef int ImGuiWindowRefreshFlags; // -> enum ImGuiWindowRefreshFlags_ // Flags: for SetNextWindowRefreshPolicy()
+// Table column indexing
+typedef ImS16 ImGuiTableColumnIdx;
+typedef ImU16 ImGuiTableDrawChannelIdx;
+
//-----------------------------------------------------------------------------
// [SECTION] Context pointer
// See implementation of this variable in imgui.cpp for comments and details.
@@ -221,12 +248,7 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer
#endif
// Debug Logging for ShowDebugLogWindow(). This is designed for relatively rare events so please don't spam.
-#ifndef IMGUI_DISABLE_DEBUG_TOOLS
-#define IMGUI_DEBUG_LOG(...) ImGui::DebugLog(__VA_ARGS__)
-#else
-#define IMGUI_DEBUG_LOG(...) ((void)0)
-#endif
-#define IMGUI_DEBUG_LOG_ERROR(...) do { ImGuiContext& g2 = *GImGui; if (g2.DebugLogFlags & ImGuiDebugLogFlags_EventError) IMGUI_DEBUG_LOG(__VA_ARGS__); else g2.DebugLogSkippedErrors++; } while (0)
+#define IMGUI_DEBUG_LOG_ERROR(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventError) IMGUI_DEBUG_LOG(__VA_ARGS__); else g.DebugLogSkippedErrors++; } while (0)
#define IMGUI_DEBUG_LOG_ACTIVEID(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventActiveId) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0)
#define IMGUI_DEBUG_LOG_FOCUS(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventFocus) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0)
#define IMGUI_DEBUG_LOG_POPUP(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventPopup) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0)
@@ -234,6 +256,7 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer
#define IMGUI_DEBUG_LOG_SELECTION(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventSelection) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0)
#define IMGUI_DEBUG_LOG_CLIPPER(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventClipper) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0)
#define IMGUI_DEBUG_LOG_IO(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0)
+#define IMGUI_DEBUG_LOG_FONT(...) do { ImGuiContext* g2 = GImGui; if (g2 && g2->DebugLogFlags & ImGuiDebugLogFlags_EventFont) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) // Called from ImFontAtlas function which may operate without a context.
#define IMGUI_DEBUG_LOG_INPUTROUTING(...) do{if (g.DebugLogFlags & ImGuiDebugLogFlags_EventInputRouting)IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0)
#define IMGUI_DEBUG_LOG_DOCKING(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventDocking) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0)
#define IMGUI_DEBUG_LOG_VIEWPORT(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventViewport) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0)
@@ -271,6 +294,15 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer
#define IM_FLOOR IM_TRUNC
#endif
+// Hint for branch prediction
+#if (defined(__cplusplus) && (__cplusplus >= 202002L)) || (defined(_MSVC_LANG) && (_MSVC_LANG >= 202002L))
+#define IM_LIKELY [[likely]]
+#define IM_UNLIKELY [[unlikely]]
+#else
+#define IM_LIKELY
+#define IM_UNLIKELY
+#endif
+
// Enforce cdecl calling convention for functions called by the standard library, in case compilation settings changed the default to e.g. __vectorcall
#ifdef _MSC_VER
#define IMGUI_CDECL __cdecl
@@ -315,6 +347,7 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer
#define IM_PRIu64 "llu"
#define IM_PRIX64 "llX"
#endif
+#define IM_TEXTUREID_TO_U64(_TEXID) ((ImU64)(intptr_t)(_TEXID))
//-----------------------------------------------------------------------------
// [SECTION] Generic helpers
@@ -336,6 +369,7 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer
// - Helper: ImBitArray
// - Helper: ImBitVector
// - Helper: ImSpan<>, ImSpanAllocator<>
+// - Helper: ImStableVector<>
// - Helper: ImPool<>
// - Helper: ImChunkStream<>
// - Helper: ImGuiTextIndex
@@ -345,25 +379,30 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer
// Helpers: Hashing
IMGUI_API ImGuiID ImHashData(const void* data, size_t data_size, ImGuiID seed = 0);
IMGUI_API ImGuiID ImHashStr(const char* data, size_t data_size = 0, ImGuiID seed = 0);
+IMGUI_API const char* ImHashSkipUncontributingPrefix(const char* label);
// Helpers: Sorting
#ifndef ImQsort
-static inline void ImQsort(void* base, size_t count, size_t size_of_element, int(IMGUI_CDECL *compare_func)(void const*, void const*)) { if (count > 1) qsort(base, count, size_of_element, compare_func); }
+inline void ImQsort(void* base, size_t count, size_t size_of_element, int(IMGUI_CDECL *compare_func)(void const*, void const*)) { if (count > 1) qsort(base, count, size_of_element, compare_func); }
#endif
// 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; }
+inline bool ImIsPowerOfTwo(int v) { return v != 0 && (v & (v - 1)) == 0; }
+inline bool ImIsPowerOfTwo(ImU64 v) { return v != 0 && (v & (v - 1)) == 0; }
+inline int ImUpperPowerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; }
+inline unsigned int ImCountSetBits(unsigned int v) { unsigned int count = 0; while (v > 0) { v = v & (v - 1); count++; } return count; }
// Helpers: String
+#define ImStrlen strlen
+#define ImMemchr memchr
IMGUI_API int ImStricmp(const char* str1, const char* str2); // Case insensitive compare.
IMGUI_API int ImStrnicmp(const char* str1, const char* str2, size_t count); // Case insensitive compare to a certain count.
IMGUI_API void ImStrncpy(char* dst, const char* src, size_t count); // Copy to a certain count and always zero terminate (strncpy doesn't).
IMGUI_API char* ImStrdup(const char* str); // Duplicate a string.
+IMGUI_API void* ImMemdup(const void* src, size_t size); // Duplicate a chunk of memory.
IMGUI_API char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* str); // Copy in provided buffer, recreate buffer if needed.
IMGUI_API const char* ImStrchrRange(const char* str_begin, const char* str_end, char c); // Find first occurrence of 'c' in string range.
IMGUI_API const char* ImStreolRange(const char* str, const char* str_end); // End end-of-line
@@ -373,10 +412,10 @@ IMGUI_API const char* ImStrSkipBlank(const char* str);
IMGUI_API int ImStrlenW(const ImWchar* str); // Computer string length (ImWchar string)
IMGUI_API const char* ImStrbol(const char* buf_mid_line, const char* buf_begin); // Find beginning-of-line
IM_MSVC_RUNTIME_CHECKS_OFF
-static inline char ImToUpper(char c) { return (c >= 'a' && c <= 'z') ? c &= ~32 : c; }
-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 ImCharIsXdigitA(char c) { return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'); }
+inline char ImToUpper(char c) { return (c >= 'a' && c <= 'z') ? c &= ~32 : c; }
+inline bool ImCharIsBlankA(char c) { return c == ' ' || c == '\t'; }
+inline bool ImCharIsBlankW(unsigned int c) { return c == ' ' || c == '\t' || c == 0x3000; }
+inline bool ImCharIsXdigitA(char c) { return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'); }
IM_MSVC_RUNTIME_CHECKS_RESTORE
// Helpers: Formatting
@@ -392,7 +431,7 @@ IMGUI_API const char* ImParseFormatSanitizeForScanning(const char* fmt_in, cha
IMGUI_API int ImParseFormatPrecision(const char* format, int default_value);
// Helpers: UTF-8 <> wchar conversions
-IMGUI_API const char* ImTextCharToUtf8(char out_buf[5], unsigned int c); // return out_buf
+IMGUI_API int ImTextCharToUtf8(char out_buf[5], unsigned int c); // return output UTF-8 bytes count
IMGUI_API int ImTextStrToUtf8(char* out_buf, int out_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* out_buf, int out_buf_size, const char* in_text, const char* in_text_end, const char** in_remaining = NULL); // return input UTF-8 bytes count
@@ -402,15 +441,27 @@ IMGUI_API int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, cons
IMGUI_API const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_text_curr); // return previous UTF-8 code-point.
IMGUI_API int ImTextCountLines(const char* in_text, const char* in_text_end); // return number of lines taken by text. trailing carriage return doesn't count as an extra line.
+// Helpers: High-level text functions (DO NOT USE!!! THIS IS A MINIMAL SUBSET OF LARGER UPCOMING CHANGES)
+enum ImDrawTextFlags_
+{
+ ImDrawTextFlags_None = 0,
+ ImDrawTextFlags_CpuFineClip = 1 << 0, // Must be == 1/true for legacy with 'bool cpu_fine_clip' arg to RenderText()
+ ImDrawTextFlags_WrapKeepBlanks = 1 << 1,
+ ImDrawTextFlags_StopOnNewLine = 1 << 2,
+};
+IMGUI_API ImVec2 ImFontCalcTextSizeEx(ImFont* font, float size, float max_width, float wrap_width, const char* text_begin, const char* text_end_display, const char* text_end, const char** out_remaining, ImVec2* out_offset, ImDrawTextFlags flags);
+IMGUI_API const char* ImFontCalcWordWrapPositionEx(ImFont* font, float size, const char* text, const char* text_end, float wrap_width, ImDrawTextFlags flags = 0);
+IMGUI_API const char* ImTextCalcWordWrapNextLineStart(const char* text, const char* text_end, ImDrawTextFlags flags = 0); // trim trailing space and find beginning of next line
+
// 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; }
+inline ImFileHandle ImFileOpen(const char*, const char*) { return NULL; }
+inline bool ImFileClose(ImFileHandle) { return false; }
+inline ImU64 ImFileGetSize(ImFileHandle) { return (ImU64)-1; }
+inline ImU64 ImFileRead(void*, ImU64, ImU64, ImFileHandle) { return 0; }
+inline ImU64 ImFileWrite(const void*, ImU64, ImU64, ImFileHandle) { return 0; }
#endif
#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
typedef FILE* ImFileHandle;
@@ -437,54 +488,56 @@ IM_MSVC_RUNTIME_CHECKS_OFF
#define ImAtan2(Y, X) atan2f((Y), (X))
#define ImAtof(STR) atof(STR)
#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 int ImAbs(int x) { return x < 0 ? -x : 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; }
+inline float ImPow(float x, float y) { return powf(x, y); } // DragBehaviorT/SliderBehaviorT uses ImPow with either float/double and need the precision
+inline double ImPow(double x, double y) { return pow(x, y); }
+inline float ImLog(float x) { return logf(x); } // DragBehaviorT/SliderBehaviorT uses ImLog with either float/double and need the precision
+inline double ImLog(double x) { return log(x); }
+inline int ImAbs(int x) { return x < 0 ? -x : x; }
+inline float ImAbs(float x) { return fabsf(x); }
+inline double ImAbs(double x) { return fabs(x); }
+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
+inline double ImSign(double x) { return (x < 0.0) ? -1.0 : (x > 0.0) ? 1.0 : 0.0; }
#ifdef IMGUI_ENABLE_SSE
-static inline float ImRsqrt(float x) { return _mm_cvtss_f32(_mm_rsqrt_ss(_mm_set_ss(x))); }
+inline float ImRsqrt(float x) { return _mm_cvtss_f32(_mm_rsqrt_ss(_mm_set_ss(x))); }
#else
-static inline float ImRsqrt(float x) { return 1.0f / sqrtf(x); }
+inline float ImRsqrt(float x) { return 1.0f / sqrtf(x); }
#endif
-static inline double ImRsqrt(double x) { return 1.0 / sqrt(x); }
+inline double ImRsqrt(double x) { return 1.0 / sqrt(x); }
#endif
// - 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<typename T> static inline T ImMin(T lhs, T rhs) { return lhs < rhs ? lhs : rhs; }
-template<typename T> static inline T ImMax(T lhs, T rhs) { return lhs >= rhs ? lhs : rhs; }
-template<typename T> static inline T ImClamp(T v, T mn, T mx) { return (v < mn) ? mn : (v > mx) ? mx : v; }
-template<typename T> static inline T ImLerp(T a, T b, float t) { return (T)(a + (b - a) * t); }
-template<typename T> static inline void ImSwap(T& a, T& b) { T tmp = a; a = b; b = tmp; }
-template<typename T> static inline T ImAddClampOverflow(T a, T b, T mn, T mx) { if (b < 0 && (a < mn - b)) return mn; if (b > 0 && (a > mx - b)) return mx; return a + b; }
-template<typename T> static inline T ImSubClampOverflow(T a, T b, T mn, T mx) { if (b > 0 && (a < mn + b)) return mn; if (b < 0 && (a > mx + b)) return mx; return a - b; }
+template<typename T> T ImMin(T lhs, T rhs) { return lhs < rhs ? lhs : rhs; }
+template<typename T> T ImMax(T lhs, T rhs) { return lhs >= rhs ? lhs : rhs; }
+template<typename T> T ImClamp(T v, T mn, T mx) { return (v < mn) ? mn : (v > mx) ? mx : v; }
+template<typename T> T ImLerp(T a, T b, float t) { return (T)(a + (b - a) * t); }
+template<typename T> void ImSwap(T& a, T& b) { T tmp = a; a = b; b = tmp; }
+template<typename T> T ImAddClampOverflow(T a, T b, T mn, T mx) { if (b < 0 && (a < mn - b)) return mn; if (b > 0 && (a > mx - b)) return mx; return a + b; }
+template<typename T> T ImSubClampOverflow(T a, T b, T mn, T mx) { if (b > 0 && (a < mn + b)) return mn; if (b < 0 && (a > mx + b)) return mx; return a - b; }
// - Misc maths helpers
-static inline ImVec2 ImMin(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x < rhs.x ? lhs.x : rhs.x, lhs.y < rhs.y ? lhs.y : rhs.y); }
-static inline ImVec2 ImMax(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x >= rhs.x ? lhs.x : rhs.x, lhs.y >= rhs.y ? lhs.y : rhs.y); }
-static inline ImVec2 ImClamp(const ImVec2& v, const ImVec2&mn, const ImVec2&mx) { return ImVec2((v.x < mn.x) ? mn.x : (v.x > mx.x) ? mx.x : v.x, (v.y < mn.y) ? mn.y : (v.y > mx.y) ? mx.y : v.y); }
-static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, float t) { return ImVec2(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * 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 ImRsqrt(d); return fail_value; }
-static inline float ImTrunc(float f) { return (float)(int)(f); }
-static inline ImVec2 ImTrunc(const ImVec2& v) { return ImVec2((float)(int)(v.x), (float)(int)(v.y)); }
-static inline float ImFloor(float f) { return (float)((f >= 0 || (float)(int)f == f) ? (int)f : (int)f - 1); } // Decent replacement for floorf()
-static inline ImVec2 ImFloor(const ImVec2& v) { return ImVec2(ImFloor(v.x), ImFloor(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 float ImLinearRemapClamp(float s0, float s1, float d0, float d1, float x) { return ImSaturate((x - s0) / (s1 - s0)) * (d1 - d0) + d0; }
-static inline ImVec2 ImMul(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); }
-static inline bool ImIsFloatAboveGuaranteedIntegerPrecision(float f) { return f <= -16777216 || f >= 16777216; }
-static inline float ImExponentialMovingAverage(float avg, float sample, int n) { avg -= avg / n; avg += sample / n; return avg; }
+inline ImVec2 ImMin(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x < rhs.x ? lhs.x : rhs.x, lhs.y < rhs.y ? lhs.y : rhs.y); }
+inline ImVec2 ImMax(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x >= rhs.x ? lhs.x : rhs.x, lhs.y >= rhs.y ? lhs.y : rhs.y); }
+inline ImVec2 ImClamp(const ImVec2& v, const ImVec2&mn, const ImVec2&mx){ return ImVec2((v.x < mn.x) ? mn.x : (v.x > mx.x) ? mx.x : v.x, (v.y < mn.y) ? mn.y : (v.y > mx.y) ? mx.y : v.y); }
+inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, float t) { return ImVec2(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t); }
+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); }
+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); }
+inline float ImSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f : f; }
+inline float ImLengthSqr(const ImVec2& lhs) { return (lhs.x * lhs.x) + (lhs.y * lhs.y); }
+inline float ImLengthSqr(const ImVec4& lhs) { return (lhs.x * lhs.x) + (lhs.y * lhs.y) + (lhs.z * lhs.z) + (lhs.w * lhs.w); }
+inline float ImInvLength(const ImVec2& lhs, float fail_value) { float d = (lhs.x * lhs.x) + (lhs.y * lhs.y); if (d > 0.0f) return ImRsqrt(d); return fail_value; }
+inline float ImTrunc(float f) { return (float)(int)(f); }
+inline ImVec2 ImTrunc(const ImVec2& v) { return ImVec2((float)(int)(v.x), (float)(int)(v.y)); }
+inline float ImFloor(float f) { return (float)((f >= 0 || (float)(int)f == f) ? (int)f : (int)f - 1); } // Decent replacement for floorf()
+inline ImVec2 ImFloor(const ImVec2& v) { return ImVec2(ImFloor(v.x), ImFloor(v.y)); }
+inline float ImTrunc64(float f) { return (float)(ImS64)(f); }
+inline float ImRound64(float f) { return (float)(ImS64)(f + 0.5f); }
+inline int ImModPositive(int a, int b) { return (a + b) % b; }
+inline float ImDot(const ImVec2& a, const ImVec2& b) { return a.x * b.x + a.y * b.y; }
+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); }
+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; }
+inline float ImLinearRemapClamp(float s0, float s1, float d0, float d1, float x) { return ImSaturate((x - s0) / (s1 - s0)) * (d1 - d0) + d0; }
+inline ImVec2 ImMul(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); }
+inline bool ImIsFloatAboveGuaranteedIntegerPrecision(float f) { return f <= -16777216 || f >= 16777216; }
+inline float ImExponentialMovingAverage(float avg, float sample, int n){ avg -= avg / n; avg += sample / n; return avg; }
IM_MSVC_RUNTIME_CHECKS_RESTORE
// Helpers: Geometry
@@ -509,6 +562,14 @@ struct ImVec1
constexpr ImVec1(float _x) : x(_x) { }
};
+// Helper: ImVec2i (2D vector, integer)
+struct ImVec2i
+{
+ int x, y;
+ constexpr ImVec2i() : x(0), y(0) {}
+ constexpr ImVec2i(int _x, int _y) : x(_x), y(_y) {}
+};
+
// Helper: ImVec2ih (2D vector, half-size integer, for long-term packed storage)
struct ImVec2ih
{
@@ -555,6 +616,7 @@ struct IMGUI_API ImRect
void Floor() { Min.x = IM_TRUNC(Min.x); Min.y = IM_TRUNC(Min.y); Max.x = IM_TRUNC(Max.x); Max.y = IM_TRUNC(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); }
+ const ImVec4& AsVec4() const { return *(const ImVec4*)&Min.x; }
};
// Helper: ImBitArray
@@ -660,6 +722,39 @@ struct ImSpanAllocator
inline void GetSpan(int n, ImSpan<T>* span) { span->set((T*)GetSpanPtrBegin(n), (T*)GetSpanPtrEnd(n)); }
};
+// Helper: ImStableVector<>
+// Allocating chunks of BLOCK_SIZE items. Objects pointers are never invalidated when growing, only by clear().
+// Important: does not destruct anything!
+// Implemented only the minimum set of functions we need for it.
+template<typename T, int BLOCK_SIZE>
+struct ImStableVector
+{
+ int Size = 0;
+ int Capacity = 0;
+ ImVector<T*> Blocks;
+
+ // Functions
+ inline ~ImStableVector() { for (T* block : Blocks) IM_FREE(block); }
+
+ inline void clear() { Size = Capacity = 0; Blocks.clear_delete(); }
+ inline void resize(int new_size) { if (new_size > Capacity) reserve(new_size); Size = new_size; }
+ inline void reserve(int new_cap)
+ {
+ new_cap = IM_MEMALIGN(new_cap, BLOCK_SIZE);
+ int old_count = Capacity / BLOCK_SIZE;
+ int new_count = new_cap / BLOCK_SIZE;
+ if (new_count <= old_count)
+ return;
+ Blocks.resize(new_count);
+ for (int n = old_count; n < new_count; n++)
+ Blocks[n] = (T*)IM_ALLOC(sizeof(T) * BLOCK_SIZE);
+ Capacity = new_cap;
+ }
+ inline T& operator[](int i) { IM_ASSERT(i >= 0 && i < Size); return Blocks[i / BLOCK_SIZE][i % BLOCK_SIZE]; }
+ inline const T& operator[](int i) const { IM_ASSERT(i >= 0 && i < Size); return Blocks[i / BLOCK_SIZE][i % BLOCK_SIZE]; }
+ inline T* push_back(const T& v) { int i = Size; IM_ASSERT(i >= 0); if (Size == Capacity) reserve(Capacity + BLOCK_SIZE); void* ptr = &Blocks[i / BLOCK_SIZE][i % BLOCK_SIZE]; memcpy(ptr, &v, sizeof(v)); Size++; return (T*)ptr; }
+};
+
// 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.
@@ -720,18 +815,19 @@ struct ImChunkStream
// Maintain a line index for a text buffer. This is a strong candidate to be moved into the public API.
struct ImGuiTextIndex
{
- ImVector<int> LineOffsets;
+ ImVector<int> Offsets;
int EndOffset = 0; // Because we don't own text buffer we need to maintain EndOffset (may bake in LineOffsets?)
- void clear() { LineOffsets.clear(); EndOffset = 0; }
- int size() { return LineOffsets.Size; }
- const char* get_line_begin(const char* base, int n) { return base + LineOffsets[n]; }
- const char* get_line_end(const char* base, int n) { return base + (n + 1 < LineOffsets.Size ? (LineOffsets[n + 1] - 1) : EndOffset); }
+ void clear() { Offsets.clear(); EndOffset = 0; }
+ int size() { return Offsets.Size; }
+ const char* get_line_begin(const char* base, int n) { return base + (Offsets.Size != 0 ? Offsets[n] : 0); }
+ const char* get_line_end(const char* base, int n) { return base + (n + 1 < Offsets.Size ? (Offsets[n + 1] - 1) : EndOffset); }
void append(const char* base, int old_size, int new_size);
};
// Helper: ImGuiStorage
IMGUI_API ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStoragePair* in_end, ImGuiID key);
+
//-----------------------------------------------------------------------------
// [SECTION] ImDrawList support
//-----------------------------------------------------------------------------
@@ -762,28 +858,33 @@ IMGUI_API ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStorag
#define IM_DRAWLIST_ARCFAST_SAMPLE_MAX IM_DRAWLIST_ARCFAST_TABLE_SIZE // Sample index _PathArcToFastEx() for 360 angle.
// 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.
+// Conceptually this could have been called e.g. ImDrawListSharedContext
+// Typically one ImGui context would create and maintain one of this.
+// You may want to create your own instance of you try to ImDrawList completely without ImGui. In that case, watch out for future changes to this structure.
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 FontScale; // Current/default font scale (== FontSize / Font->FontSize)
+ ImVec2 TexUvWhitePixel; // UV of white pixel in the atlas (== FontAtlas->TexUvWhitePixel)
+ const ImVec4* TexUvLines; // UV of anti-aliased lines in the atlas (== FontAtlas->TexUvLines)
+ ImFontAtlas* FontAtlas; // Current font atlas
+ ImFont* Font; // Current font (used for simplified AddText overload)
+ float FontSize; // Current font size (used for for simplified AddText overload)
+ float FontScale; // Current font scale (== FontSize / Font->FontSize)
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()
+ float InitialFringeScale; // Initial scale to apply to AA fringe
ImDrawListFlags InitialFlags; // Initial flags at the beginning of the frame (it is possible to alter flags on a per-drawlist basis afterwards)
+ ImVec4 ClipRectFullscreen; // Value for PushClipRectFullscreen()
+ ImVector<ImVec2> TempBuffer; // Temporary write buffer
+ ImVector<ImDrawList*> DrawLists; // All draw lists associated to this ImDrawListSharedData
+ ImGuiContext* Context; // [OPTIONAL] Link to Dear ImGui context. 99% of ImDrawList/ImFontAtlas can function without an ImGui context, but this facilitate handling one legacy edge case.
- // [Internal] Temp write buffer
- ImVector<ImVec2> TempBuffer;
-
- // [Internal] Lookup tables
+ // Lookup tables
ImVec2 ArcFastVtx[IM_DRAWLIST_ARCFAST_TABLE_SIZE]; // Sample points on the quarter of the circle.
float ArcFastRadiusCutoff; // Cutoff radius after which arc drawing will fallback to slower PathArcTo()
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();
+ ~ImDrawListSharedData();
void SetCircleTessellationMaxError(float max_error);
};
@@ -795,18 +896,46 @@ struct ImDrawDataBuilder
ImDrawDataBuilder() { memset(this, 0, sizeof(*this)); }
};
+struct ImFontStackData
+{
+ ImFont* Font;
+ float FontSizeBeforeScaling; // ~~ style.FontSizeBase
+ float FontSizeAfterScaling; // ~~ g.FontSize
+};
+
//-----------------------------------------------------------------------------
-// [SECTION] Data types support
+// [SECTION] Style support
//-----------------------------------------------------------------------------
-struct ImGuiDataVarInfo
+struct ImGuiStyleVarInfo
{
- ImGuiDataType Type;
- ImU32 Count; // 1+
- ImU32 Offset; // Offset in parent structure
+ ImU32 Count : 8; // 1+
+ ImGuiDataType DataType : 8;
+ ImU32 Offset : 16; // Offset in parent structure
void* GetVarPtr(void* parent) const { return (void*)((unsigned char*)parent + Offset); }
};
+// Stacked color modifier, backup of modified data so we can restore it
+struct ImGuiColorMod
+{
+ ImGuiCol Col;
+ ImVec4 BackupValue;
+};
+
+// Stacked style modifier, backup of modified data so we can restore it. Data type inferred from the variable.
+struct ImGuiStyleMod
+{
+ ImGuiStyleVar VarIdx;
+ union { int BackupInt[2]; float BackupFloat[2]; };
+ ImGuiStyleMod(ImGuiStyleVar idx, int v) { VarIdx = idx; BackupInt[0] = v; }
+ ImGuiStyleMod(ImGuiStyleVar idx, float v) { VarIdx = idx; BackupFloat[0] = v; }
+ ImGuiStyleMod(ImGuiStyleVar idx, ImVec2 v) { VarIdx = idx; BackupFloat[0] = v.x; BackupFloat[1] = v.y; }
+};
+
+//-----------------------------------------------------------------------------
+// [SECTION] Data types support
+//-----------------------------------------------------------------------------
+
struct ImGuiDataTypeStorage
{
ImU8 Data[8]; // Opaque storage to fit any data up to ImGuiDataType_COUNT
@@ -824,8 +953,7 @@ struct ImGuiDataTypeInfo
// Extend ImGuiDataType_
enum ImGuiDataTypePrivate_
{
- ImGuiDataType_String = ImGuiDataType_COUNT + 1,
- ImGuiDataType_Pointer,
+ ImGuiDataType_Pointer = ImGuiDataType_COUNT,
ImGuiDataType_ID,
};
@@ -846,6 +974,7 @@ enum ImGuiItemFlagsPrivate_
ImGuiItemFlags_AllowOverlap = 1 << 14, // false // Allow being overlapped by another widget. Not-hovered to Hovered transition deferred by a frame.
ImGuiItemFlags_NoNavDisableMouseHover = 1 << 15, // false // Nav keyboard/gamepad mode doesn't disable hover highlight (behave as if NavHighlightItemUnderNav==false).
ImGuiItemFlags_NoMarkEdited = 1 << 16, // false // Skip calling MarkItemEdited()
+ ImGuiItemFlags_NoFocus = 1 << 17, // false // [EXPERIMENTAL: Not very well specced] Clicking doesn't take focus. Automatically sets ImGuiButtonFlags_NoFocus + ImGuiButtonFlags_NoNavFocus in ButtonBehavior().
// Controlled by widget code
ImGuiItemFlags_Inputable = 1 << 20, // false // [WIP] Auto-activate input mode when tab focused. Currently only used and supported by a few items before it becomes a generic feature.
@@ -874,6 +1003,7 @@ enum ImGuiItemStatusFlags_
ImGuiItemStatusFlags_Visible = 1 << 8, // [WIP] Set when item is overlapping the current clipping rectangle (Used internally. Please don't use yet: API/system will change as we refactor Itemadd()).
ImGuiItemStatusFlags_HasClipRect = 1 << 9, // g.LastItemData.ClipRect is valid.
ImGuiItemStatusFlags_HasShortcut = 1 << 10, // g.LastItemData.Shortcut valid. Set by SetNextItemShortcut() -> ItemAdd().
+ //ImGuiItemStatusFlags_FocusedByTabbing = 1 << 8, // Removed IN 1.90.1 (Dec 2023). The trigger is part of g.NavActivateId. See commit 54c1bdeceb.
// Additional status + semantic for ImGuiTestEngine
#ifdef IMGUI_ENABLE_TEST_ENGINE
@@ -911,7 +1041,7 @@ enum ImGuiButtonFlagsPrivate_
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_Repeat = 1 << 10, // hold to repeat -> use ImGuiItemFlags_ButtonRepeat instead.
ImGuiButtonFlags_FlattenChildren = 1 << 11, // allow interactions even if a child window is overlapping
ImGuiButtonFlags_AllowOverlap = 1 << 12, // require previous frame HoveredId to either match id or be null before being usable.
//ImGuiButtonFlags_DontClosePopups = 1 << 13, // disable automatically closing parent popup on press
@@ -923,8 +1053,10 @@ enum ImGuiButtonFlagsPrivate_
ImGuiButtonFlags_NoHoveredOnFocus = 1 << 19, // don't report as hovered when nav focus is on this item
ImGuiButtonFlags_NoSetKeyOwner = 1 << 20, // don't set key/input owner on the initial click (note: mouse buttons are keys! often, the key in question will be ImGuiKey_MouseLeft!)
ImGuiButtonFlags_NoTestKeyOwner = 1 << 21, // don't test key/input owner when polling the key (note: mouse buttons are keys! often, the key in question will be ImGuiKey_MouseLeft!)
+ ImGuiButtonFlags_NoFocus = 1 << 22, // [EXPERIMENTAL: Not very well specced]. Don't focus parent window when clicking.
ImGuiButtonFlags_PressedOnMask_ = ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick | ImGuiButtonFlags_PressedOnDragDropHold,
ImGuiButtonFlags_PressedOnDefault_ = ImGuiButtonFlags_PressedOnClickRelease,
+ //ImGuiButtonFlags_NoKeyModifiers = ImGuiButtonFlags_NoKeyModsAllowed, // Renamed in 1.91.4
};
// Extend ImGuiComboFlags_
@@ -945,7 +1077,6 @@ enum ImGuiSelectableFlagsPrivate_
{
// NB: need to be in sync with last value of ImGuiSelectableFlags_
ImGuiSelectableFlags_NoHoldingActiveID = 1 << 20,
- ImGuiSelectableFlags_SelectOnNav = 1 << 21, // (WIP) Auto-select when moved into. This is not exposed in public API as to handle multi-select and modifiers we will need user to explicitly control focus scope. May be replaced with a BeginSelection() API.
ImGuiSelectableFlags_SelectOnClick = 1 << 22, // Override button behavior to react on Click (default is Click+Release)
ImGuiSelectableFlags_SelectOnRelease = 1 << 23, // Override button behavior to react on Release (default is Click+Release)
ImGuiSelectableFlags_SpanAvailWidth = 1 << 24, // 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)
@@ -957,9 +1088,11 @@ enum ImGuiSelectableFlagsPrivate_
// Extend ImGuiTreeNodeFlags_
enum ImGuiTreeNodeFlagsPrivate_
{
+ ImGuiTreeNodeFlags_NoNavFocus = 1 << 27,// Don't claim nav focus when interacting with this item (#8551)
ImGuiTreeNodeFlags_ClipLabelForTrailingButton = 1 << 28,// FIXME-WIP: Hard-coded for CollapsingHeader()
ImGuiTreeNodeFlags_UpsideDownArrow = 1 << 29,// FIXME-WIP: Turn Down arrow into an Up arrow, for reversed trees (#6517)
ImGuiTreeNodeFlags_OpenOnMask_ = ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_OpenOnArrow,
+ ImGuiTreeNodeFlags_DrawLinesMask_ = ImGuiTreeNodeFlags_DrawLinesNone | ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes,
};
enum ImGuiSeparatorFlags_
@@ -1000,13 +1133,16 @@ enum ImGuiLayoutType_
ImGuiLayoutType_Vertical = 1
};
-enum ImGuiLogType
+// Flags for LogBegin() text capturing function
+enum ImGuiLogFlags_
{
- ImGuiLogType_None = 0,
- ImGuiLogType_TTY,
- ImGuiLogType_File,
- ImGuiLogType_Buffer,
- ImGuiLogType_Clipboard,
+ ImGuiLogFlags_None = 0,
+
+ ImGuiLogFlags_OutputTTY = 1 << 0,
+ ImGuiLogFlags_OutputFile = 1 << 1,
+ ImGuiLogFlags_OutputBuffer = 1 << 2,
+ ImGuiLogFlags_OutputClipboard = 1 << 3,
+ ImGuiLogFlags_OutputMask_ = ImGuiLogFlags_OutputTTY | ImGuiLogFlags_OutputFile | ImGuiLogFlags_OutputBuffer | ImGuiLogFlags_OutputClipboard,
};
// X/Y enums are fixed to 0/1 so they may be used to index ImVec2
@@ -1023,23 +1159,6 @@ enum ImGuiPlotType
ImGuiPlotType_Histogram,
};
-// Stacked color modifier, backup of modified data so we can restore it
-struct ImGuiColorMod
-{
- ImGuiCol Col;
- ImVec4 BackupValue;
-};
-
-// Stacked style modifier, backup of modified data so we can restore it. Data type inferred from the variable.
-struct ImGuiStyleMod
-{
- ImGuiStyleVar VarIdx;
- union { int BackupInt[2]; float BackupFloat[2]; };
- ImGuiStyleMod(ImGuiStyleVar idx, int v) { VarIdx = idx; BackupInt[0] = v; }
- ImGuiStyleMod(ImGuiStyleVar idx, float v) { VarIdx = idx; BackupFloat[0] = v; }
- ImGuiStyleMod(ImGuiStyleVar idx, ImVec2 v) { VarIdx = idx; BackupFloat[0] = v.x; BackupFloat[1] = v.y; }
-};
-
// Storage data for BeginComboPreview()/EndComboPreview()
struct IMGUI_API ImGuiComboPreviewData
{
@@ -1065,7 +1184,7 @@ struct IMGUI_API ImGuiGroupData
ImVec2 BackupCurrLineSize;
float BackupCurrLineTextBaseOffset;
ImGuiID BackupActiveIdIsAlive;
- bool BackupActiveIdPreviousFrameIsAlive;
+ bool BackupDeactivatedIdIsAlive;
bool BackupHoveredIdIsAlive;
bool BackupIsSameLine;
bool EmitItem;
@@ -1116,28 +1235,34 @@ struct IMGUI_API ImGuiInputTextState
{
ImGuiContext* Ctx; // parent UI context (needs to be set explicitly by parent).
ImStbTexteditState* Stb; // State for stb_textedit.h
+ ImGuiInputTextFlags Flags; // copy of InputText() flags. may be used to check if e.g. ImGuiInputTextFlags_Password is set.
ImGuiID ID; // widget id owning the text state
- int CurLenA; // UTF-8 length of the string in TextA (in bytes)
- ImVector<char> TextA; // main UTF8 buffer.
- ImVector<char> InitialTextA; // value to revert to when pressing Escape = backup of end-user buffer at the time of focus (in UTF-8, unaltered)
+ int TextLen; // UTF-8 length of the string in TextA (in bytes)
+ const char* TextSrc; // == TextA.Data unless read-only, in which case == buf passed to InputText(). Field only set and valid _inside_ the call InputText() call.
+ ImVector<char> TextA; // main UTF8 buffer. TextA.Size is a buffer size! Should always be >= buf_size passed by user (and of course >= CurLenA + 1).
+ ImVector<char> TextToRevertTo; // value to revert to when pressing Escape = backup of end-user buffer at the time of focus (in UTF-8, unaltered)
ImVector<char> CallbackTextBackup; // temporary storage for callback to support automatic reconcile of undo-stack
- int BufCapacityA; // end-user buffer capacity
+ int BufCapacity; // end-user buffer capacity (include zero terminator)
ImVec2 Scroll; // horizontal offset (managed manually) + vertical scrolling (pulled from child window's own Scroll.y)
+ int LineCount; // last line count (solely for debugging)
+ float WrapWidth; // word-wrapping width
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 CursorCenterY; // set when we want scrolling to be centered over the cursor position (while resizing a word-wrapping field)
bool SelectedAllMouseLock; // after a double-click to select all, we ignore further mouse drags to update selection
bool Edited; // edited this frame
- ImGuiInputTextFlags Flags; // copy of InputText() flags. may be used to check if e.g. ImGuiInputTextFlags_Password is set.
- bool ReloadUserBuf; // force a reload of user buf so it may be modified externally. may be automatic in future version.
- int ReloadSelectionStart; // POSITIONS ARE IN IMWCHAR units *NOT* UTF-8 this is why this is not exposed yet.
+ bool WantReloadUserBuf; // force a reload of user buf so it may be modified externally. may be automatic in future version.
+ ImS8 LastMoveDirectionLR; // ImGuiDir_Left or ImGuiDir_Right. track last movement direction so when cursor cross over a word-wrapping boundaries we can display it on either line depending on last move.s
+ int ReloadSelectionStart;
int ReloadSelectionEnd;
ImGuiInputTextState();
~ImGuiInputTextState();
- void ClearText() { CurLenA = 0; TextA[0] = 0; CursorClamp(); }
- void ClearFreeMemory() { TextA.clear(); InitialTextA.clear(); }
+ void ClearText() { TextLen = 0; TextA[0] = 0; CursorClamp(); }
+ void ClearFreeMemory() { TextA.clear(); TextToRevertTo.clear(); }
void OnKeyPressed(int key); // Cannot be inline because we call in code in stb_textedit.h implementation
void OnCharPressed(unsigned int c);
+ float GetPreferredOffsetX() const;
// Cursor & Selection
void CursorAnimReset();
@@ -1179,17 +1304,20 @@ enum ImGuiNextWindowDataFlags_
ImGuiNextWindowDataFlags_HasFocus = 1 << 5,
ImGuiNextWindowDataFlags_HasBgAlpha = 1 << 6,
ImGuiNextWindowDataFlags_HasScroll = 1 << 7,
- ImGuiNextWindowDataFlags_HasChildFlags = 1 << 8,
- ImGuiNextWindowDataFlags_HasRefreshPolicy = 1 << 9,
- ImGuiNextWindowDataFlags_HasViewport = 1 << 10,
- ImGuiNextWindowDataFlags_HasDock = 1 << 11,
- ImGuiNextWindowDataFlags_HasWindowClass = 1 << 12,
+ ImGuiNextWindowDataFlags_HasWindowFlags = 1 << 8,
+ ImGuiNextWindowDataFlags_HasChildFlags = 1 << 9,
+ ImGuiNextWindowDataFlags_HasRefreshPolicy = 1 << 10,
+ ImGuiNextWindowDataFlags_HasViewport = 1 << 11,
+ ImGuiNextWindowDataFlags_HasDock = 1 << 12,
+ ImGuiNextWindowDataFlags_HasWindowClass = 1 << 13,
};
// Storage for SetNexWindow** functions
struct ImGuiNextWindowData
{
- ImGuiNextWindowDataFlags Flags;
+ ImGuiNextWindowDataFlags HasFlags;
+
+ // Members below are NOT cleared. Always rely on HasFlags.
ImGuiCond PosCond;
ImGuiCond SizeCond;
ImGuiCond CollapsedCond;
@@ -1199,6 +1327,7 @@ struct ImGuiNextWindowData
ImVec2 SizeVal;
ImVec2 ContentSizeVal;
ImVec2 ScrollVal;
+ ImGuiWindowFlags WindowFlags; // Only honored by BeginTable()
ImGuiChildFlags ChildFlags;
bool PosUndock;
bool CollapsedVal;
@@ -1213,7 +1342,7 @@ struct ImGuiNextWindowData
ImGuiWindowRefreshFlags RefreshFlagsVal;
ImGuiNextWindowData() { memset(this, 0, sizeof(*this)); }
- inline void ClearFlags() { Flags = ImGuiNextWindowDataFlags_None; }
+ inline void ClearFlags() { HasFlags = ImGuiNextWindowDataFlags_None; }
};
enum ImGuiNextItemDataFlags_
@@ -1230,7 +1359,8 @@ struct ImGuiNextItemData
{
ImGuiNextItemDataFlags HasFlags; // Called HasFlags instead of Flags to avoid mistaking this
ImGuiItemFlags ItemFlags; // Currently only tested/used for ImGuiItemFlags_AllowOverlap and ImGuiItemFlags_HasSelectionUserData.
- // Non-flags members are NOT cleared by ItemAdd() meaning they are still valid during NavProcessItem()
+
+ // Members below are NOT cleared by ItemAdd() meaning they are still valid during e.g. NavProcessItem(). Always rely on HasFlags.
ImGuiID FocusScopeId; // Set by SetNextItemSelectionUserData()
ImGuiSelectionUserData SelectionUserData; // Set by SetNextItemSelectionUserData() (note that NULL/0 is a valid value, we use -1 == ImGuiSelectionUserData_Invalid to mark invalid values)
float Width; // Set by SetNextItemWidth()
@@ -1249,11 +1379,11 @@ struct ImGuiNextItemData
struct ImGuiLastItemData
{
ImGuiID ID;
- ImGuiItemFlags ItemFlags; // See ImGuiItemFlags_
+ ImGuiItemFlags ItemFlags; // See ImGuiItemFlags_ (called 'InFlags' before v1.91.4).
ImGuiItemStatusFlags StatusFlags; // See ImGuiItemStatusFlags_
ImRect Rect; // Full rectangle
ImRect NavRect; // Navigation scoring rectangle (not displayed)
- // Rarely used fields are not explicitly cleared, only valid when the corresponding ImGuiItemStatusFlags ar set.
+ // Rarely used fields are not explicitly cleared, only valid when the corresponding ImGuiItemStatusFlags are set.
ImRect DisplayRect; // Display rectangle. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) is set.
ImRect ClipRect; // Clip rectangle at the time of submitting item. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags_HasClipRect) is set..
ImGuiKeyChord Shortcut; // Shortcut at the time of submitting item. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags_HasShortcut) is set..
@@ -1262,15 +1392,18 @@ struct ImGuiLastItemData
};
// Store data emitted by TreeNode() for usage by TreePop()
-// - To implement ImGuiTreeNodeFlags_NavLeftJumpsBackHere: store the minimum amount of data
+// - To implement ImGuiTreeNodeFlags_NavLeftJumpsToParent: store the minimum amount of data
// which we can't infer in TreePop(), to perform the equivalent of NavApplyItemToResult().
// Only stored when the node is a potential candidate for landing on a Left arrow jump.
struct ImGuiTreeNodeStackData
{
ImGuiID ID;
ImGuiTreeNodeFlags TreeFlags;
- ImGuiItemFlags ItemFlags; // Used for nav landing
- ImRect NavRect; // Used for nav landing
+ ImGuiItemFlags ItemFlags; // Used for nav landing
+ ImRect NavRect; // Used for nav landing
+ float DrawLinesX1;
+ float DrawLinesToNodesY2;
+ ImGuiTableColumnIdx DrawLinesTableColumn;
};
// sizeof() = 20
@@ -1298,6 +1431,7 @@ struct ImGuiWindowStackData
ImGuiLastItemData ParentLastItemDataBackup;
ImGuiErrorRecoveryState StackSizesInBegin; // Store size of various stacks for asserting
bool DisabledOverrideReenable; // Non-child window override disabled flag
+ float DisabledOverrideReenableAlphaBackup;
};
struct ImGuiShrinkWidthItem
@@ -1316,6 +1450,15 @@ struct ImGuiPtrOrIndex
ImGuiPtrOrIndex(int index) { Ptr = NULL; Index = index; }
};
+// Data used by IsItemDeactivated()/IsItemDeactivatedAfterEdit() functions
+struct ImGuiDeactivatedItemData
+{
+ ImGuiID ID;
+ int ElapseFrame;
+ bool HasBeenEditedBefore;
+ bool IsAlive;
+};
+
//-----------------------------------------------------------------------------
// [SECTION] Popup support
//-----------------------------------------------------------------------------
@@ -1384,7 +1527,7 @@ enum ImGuiInputEventType
ImGuiInputEventType_COUNT
};
-enum ImGuiInputSource
+enum ImGuiInputSource : int
{
ImGuiInputSource_None = 0,
ImGuiInputSource_Mouse, // Note: may be Mouse or TouchScreen or Pen. See io.MouseSource to distinguish them.
@@ -1549,8 +1692,9 @@ enum ImGuiActivateFlags_
ImGuiActivateFlags_PreferInput = 1 << 0, // Favor activation that requires keyboard text input (e.g. for Slider/Drag). Default for Enter key.
ImGuiActivateFlags_PreferTweak = 1 << 1, // Favor activation for tweaking with arrows or gamepad (e.g. for Slider/Drag). Default for Space key and if keyboard is not used.
ImGuiActivateFlags_TryToPreserveState = 1 << 2, // Request widget to preserve state if it can (e.g. InputText will try to preserve cursor/selection)
- ImGuiActivateFlags_FromTabbing = 1 << 3, // Activation requested by a tabbing request
+ ImGuiActivateFlags_FromTabbing = 1 << 3, // Activation requested by a tabbing request (ImGuiNavMoveFlags_IsTabbing)
ImGuiActivateFlags_FromShortcut = 1 << 4, // Activation requested by an item shortcut via SetNextItemShortcut() function.
+ ImGuiActivateFlags_FromFocusApi = 1 << 5, // Activation requested by an api request (ImGuiNavMoveFlags_FocusApi)
};
// Early work-in-progress API for ScrollToItem()
@@ -1579,6 +1723,7 @@ enum ImGuiNavRenderCursorFlags_
ImGuiNavHighlightFlags_Compact = ImGuiNavRenderCursorFlags_Compact, // Renamed in 1.91.4
ImGuiNavHighlightFlags_AlwaysDraw = ImGuiNavRenderCursorFlags_AlwaysDraw, // Renamed in 1.91.4
ImGuiNavHighlightFlags_NoRounding = ImGuiNavRenderCursorFlags_NoRounding, // Renamed in 1.91.4
+ //ImGuiNavHighlightFlags_TypeThin = ImGuiNavRenderCursorFlags_Compact, // Renamed in 1.90.2
#endif
};
@@ -1825,6 +1970,7 @@ enum ImGuiDockNodeFlagsPrivate_
ImGuiDockNodeFlags_NoResizeX = 1 << 16, // //
ImGuiDockNodeFlags_NoResizeY = 1 << 17, // //
ImGuiDockNodeFlags_DockedWindowsInFocusRoute= 1 << 18, // // Any docked window will be automatically be focus-route chained (window->ParentWindowForFocusRoute set to this) so Shortcut() in this window can run when any docked window is focused.
+
// Disable docking/undocking actions in this dockspace or individual node (existing docked nodes will be preserved)
// Those are not exposed in public because the desirable sharing/inheriting/copy-flag-on-split behaviors are quite difficult to design and understand.
// The two public flags ImGuiDockNodeFlags_NoDockingOverCentralNode/ImGuiDockNodeFlags_NoDockingSplit don't have those issues.
@@ -1833,6 +1979,7 @@ enum ImGuiDockNodeFlagsPrivate_
ImGuiDockNodeFlags_NoDockingOverOther = 1 << 21, // // Disable this node from being docked over another window or non-empty node.
ImGuiDockNodeFlags_NoDockingOverEmpty = 1 << 22, // // Disable this node from being docked over an empty node (e.g. DockSpace with no other windows)
ImGuiDockNodeFlags_NoDocking = ImGuiDockNodeFlags_NoDockingOverMe | ImGuiDockNodeFlags_NoDockingOverOther | ImGuiDockNodeFlags_NoDockingOverEmpty | ImGuiDockNodeFlags_NoDockingSplit | ImGuiDockNodeFlags_NoDockingSplitOther,
+
// Masks
ImGuiDockNodeFlags_SharedFlagsInheritMask_ = ~0,
ImGuiDockNodeFlags_NoResizeFlagsMask_ = (int)ImGuiDockNodeFlags_NoResize | ImGuiDockNodeFlags_NoResizeX | ImGuiDockNodeFlags_NoResizeY,
@@ -2097,6 +2244,7 @@ typedef void (*ImGuiErrorCallback)(ImGuiContext* ctx, void* user_data, const cha
// [SECTION] Metrics, Debug Tools
//-----------------------------------------------------------------------------
+// See IMGUI_DEBUG_LOG() and IMGUI_DEBUG_LOG_XXX() macros.
enum ImGuiDebugLogFlags_
{
// Event types
@@ -2109,11 +2257,12 @@ enum ImGuiDebugLogFlags_
ImGuiDebugLogFlags_EventClipper = 1 << 5,
ImGuiDebugLogFlags_EventSelection = 1 << 6,
ImGuiDebugLogFlags_EventIO = 1 << 7,
- ImGuiDebugLogFlags_EventInputRouting = 1 << 8,
- ImGuiDebugLogFlags_EventDocking = 1 << 9,
- ImGuiDebugLogFlags_EventViewport = 1 << 10,
+ ImGuiDebugLogFlags_EventFont = 1 << 8,
+ ImGuiDebugLogFlags_EventInputRouting = 1 << 9,
+ ImGuiDebugLogFlags_EventDocking = 1 << 10,
+ ImGuiDebugLogFlags_EventViewport = 1 << 11,
- ImGuiDebugLogFlags_EventMask_ = ImGuiDebugLogFlags_EventError | ImGuiDebugLogFlags_EventActiveId | ImGuiDebugLogFlags_EventFocus | ImGuiDebugLogFlags_EventPopup | ImGuiDebugLogFlags_EventNav | ImGuiDebugLogFlags_EventClipper | ImGuiDebugLogFlags_EventSelection | ImGuiDebugLogFlags_EventIO | ImGuiDebugLogFlags_EventInputRouting | ImGuiDebugLogFlags_EventDocking | ImGuiDebugLogFlags_EventViewport,
+ ImGuiDebugLogFlags_EventMask_ = ImGuiDebugLogFlags_EventError | ImGuiDebugLogFlags_EventActiveId | ImGuiDebugLogFlags_EventFocus | ImGuiDebugLogFlags_EventPopup | ImGuiDebugLogFlags_EventNav | ImGuiDebugLogFlags_EventClipper | ImGuiDebugLogFlags_EventSelection | ImGuiDebugLogFlags_EventIO | ImGuiDebugLogFlags_EventFont | ImGuiDebugLogFlags_EventInputRouting | ImGuiDebugLogFlags_EventDocking | ImGuiDebugLogFlags_EventViewport,
ImGuiDebugLogFlags_OutputToTTY = 1 << 20, // Also send output to TTY
ImGuiDebugLogFlags_OutputToTestEngine = 1 << 21, // Also send output to Test Engine
};
@@ -2145,12 +2294,13 @@ struct ImGuiMetricsConfig
bool ShowDrawCmdMesh = true;
bool ShowDrawCmdBoundingBoxes = true;
bool ShowTextEncodingViewer = false;
- bool ShowAtlasTintedWithTextColor = false;
+ bool ShowTextureUsedRect = false;
bool ShowDockingNodes = false;
int ShowWindowsRectsType = -1;
int ShowTablesRectsType = -1;
int HighlightMonitorIdx = -1;
ImGuiID HighlightViewportID = 0;
+ bool ShowFontPreview = true;
};
struct ImGuiStackLevelInfo
@@ -2158,10 +2308,10 @@ struct ImGuiStackLevelInfo
ImGuiID ID;
ImS8 QueryFrameCount; // >= 1: Query in progress
bool QuerySuccess; // Obtained result from DebugHookIdInfo()
- ImGuiDataType DataType : 8;
- char Desc[57]; // Arbitrarily sized buffer to hold a result (FIXME: could replace Results[] with a chunk stream?) FIXME: Now that we added CTRL+C this should be fixed.
+ ImS8 DataType; // ImGuiDataType
+ int DescOffset; // -1 or offset into parent's ResultPathsBuf
- ImGuiStackLevelInfo() { memset(this, 0, sizeof(*this)); }
+ ImGuiStackLevelInfo() { memset(this, 0, sizeof(*this)); DescOffset = -1; }
};
// State for ID Stack tool queries
@@ -2169,12 +2319,16 @@ struct ImGuiIDStackTool
{
int LastActiveFrame;
int StackLevel; // -1: query stack and resize Results, >= 0: individual stack level
- ImGuiID QueryId; // ID to query details for
+ ImGuiID QueryMainId; // ID to query details for
ImVector<ImGuiStackLevelInfo> Results;
- bool CopyToClipboardOnCtrlC;
+ bool QueryHookActive; // Used to disambiguate the case where DebugHookIdInfoId == 0 which is valid.
+ bool OptHexEncodeNonAsciiChars;
+ bool OptCopyToClipboardOnCtrlC;
float CopyToClipboardLastTime;
+ ImGuiTextBuffer ResultPathsBuf;
+ ImGuiTextBuffer ResultTempBuf;
- ImGuiIDStackTool() { memset(this, 0, sizeof(*this)); CopyToClipboardLastTime = -FLT_MAX; }
+ ImGuiIDStackTool() { memset(this, 0, sizeof(*this)); LastActiveFrame = -1; OptHexEncodeNonAsciiChars = true; CopyToClipboardLastTime = -FLT_MAX; }
};
//-----------------------------------------------------------------------------
@@ -2202,16 +2356,18 @@ struct ImGuiContextHook
struct ImGuiContext
{
bool Initialized;
- 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.
- float FontScale; // == FontSize / Font->FontSize
+ ImVector<ImFontAtlas*> FontAtlases; // List of font atlases used by the context (generally only contains g.IO.Fonts aka the main font atlas)
+ ImFont* Font; // Currently bound font. (== FontStack.back().Font)
+ ImFontBaked* FontBaked; // Currently bound font at currently bound size. (== Font->GetFontBaked(FontSize))
+ float FontSize; // Currently bound font size == line height (== FontSizeBase + externals scales applied in the UpdateCurrentFontSize() function).
+ float FontSizeBase; // Font size before scaling == style.FontSizeBase == value passed to PushFont() when specified.
+ float FontBakedScale; // == FontBaked->Size / FontSize. Scale factor over baked size. Rarely used nowadays, very often == 1.0f.
+ float FontRasterizerDensity; // Current font density. Used by all calls to GetFontBaked().
float CurrentDpiScale; // Current window/viewport DpiScale == CurrentViewport->DpiScale
ImDrawListSharedData DrawListSharedData;
double Time;
@@ -2219,9 +2375,9 @@ struct ImGuiContext
int FrameCountEnded;
int FrameCountPlatformEnded;
int FrameCountRendered;
+ ImGuiID WithinEndChildID; // Set within EndChild()
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()
void* TestEngine; // Test engine user data
@@ -2240,7 +2396,7 @@ struct ImGuiContext
ImVector<ImGuiWindowStackData> CurrentWindowStack;
ImGuiStorage WindowsById; // Map window's ImGuiID to ImGuiWindow*
int WindowsActiveCount; // Number of unique windows submitted by frame
- ImVec2 WindowsHoverPadding; // Padding around resizable windows for which hovering on counts as hovering the window == ImMax(style.TouchExtraPadding, WINDOWS_HOVER_PADDING).
+ float WindowsBorderHoverPadding; // Padding around resizable windows for which hovering on counts as hovering the window == ImMax(style.TouchExtraPadding, style.WindowBorderHoverPadding). This isn't so multi-dpi friendly.
ImGuiID DebugBreakInWindow; // Set to break in Begin() call.
ImGuiWindow* CurrentWindow; // Window being drawn into
ImGuiWindow* HoveredWindow; // Window the mouse is hovering. Will typically catch mouse inputs.
@@ -2256,8 +2412,8 @@ struct ImGuiContext
ImVec2 WheelingAxisAvg;
// Item/widgets state and tracking information
- ImGuiID DebugDrawIdConflicts; // Set when we detect multiple items with the same identifier
- ImGuiID DebugHookIdInfo; // Will call core hooks: DebugHookIdInfo() from GetID functions, used by ID Stack Tool [next HoveredId/ActiveId to not pull in an extra cache-line]
+ ImGuiID DebugDrawIdConflictsId; // Set when we detect multiple items with the same identifier
+ ImGuiID DebugHookIdInfoId; // Will call core hooks: DebugHookIdInfo() from GetID functions, used by ID Stack Tool [next HoveredId/ActiveId to not pull in an extra cache-line]
ImGuiID HoveredId; // Hovered widget, filled during the frame
ImGuiID HoveredIdPreviousFrame;
int HoveredIdPreviousFrameItemCount; // Count numbers of items using the same ID as last frame's hovered id
@@ -2276,14 +2432,14 @@ struct ImGuiContext
bool ActiveIdHasBeenEditedBefore; // Was the value associated to the widget Edited over the course of the Active state.
bool ActiveIdHasBeenEditedThisFrame;
bool ActiveIdFromShortcut;
+ ImGuiID ActiveIdDisabledId; // When clicking a disabled item we set ActiveId=window->MoveId to avoid interference with widget code. Actual item ID is stored here.
int ActiveIdMouseButton : 8;
ImVec2 ActiveIdClickOffset; // Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior)
ImGuiWindow* ActiveIdWindow;
ImGuiInputSource ActiveIdSource; // Activating source: ImGuiInputSource_Mouse OR ImGuiInputSource_Keyboard OR ImGuiInputSource_Gamepad
ImGuiID ActiveIdPreviousFrame;
- bool ActiveIdPreviousFrameIsAlive;
- bool ActiveIdPreviousFrameHasBeenEditedBefore;
- ImGuiWindow* ActiveIdPreviousFrameWindow;
+ ImGuiDeactivatedItemData DeactivatedItemData;
+ ImGuiDataTypeStorage ActiveIdValueOnActivation; // Backup of initial value at the time of activation. ONLY SET BY SPECIFIC WIDGETS: DragXXX and SliderXXX.
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.
@@ -2315,7 +2471,7 @@ struct ImGuiContext
ImGuiCol DebugFlashStyleColorIdx; // (Keep close to ColorStack to share cache line)
ImVector<ImGuiColorMod> ColorStack; // Stack for PushStyleColor()/PopStyleColor() - inherited by Begin()
ImVector<ImGuiStyleMod> StyleVarStack; // Stack for PushStyleVar()/PopStyleVar() - inherited by Begin()
- ImVector<ImFont*> FontStack; // Stack for PushFont()/PopFont() - inherited by Begin()
+ ImVector<ImFontStackData> FontStack; // Stack for PushFont()/PopFont() - inherited by Begin()
ImVector<ImGuiFocusScopeData> FocusScopeStack; // Stack for PushFocusScope()/PopFocusScope() - inherited by BeginChild(), pushed into by Begin()
ImVector<ImGuiItemFlags> ItemFlagsStack; // Stack for PushItemFlag()/PopItemFlag() - inherited by Begin()
ImVector<ImGuiGroupData> GroupStack; // Stack for BeginGroup()/EndGroup() - not inherited by Begin()
@@ -2346,18 +2502,19 @@ struct ImGuiContext
ImGuiWindow* NavWindow; // Focused window for navigation. Could be called 'FocusedWindow'
ImGuiID NavFocusScopeId; // Focused focus scope (e.g. selection code often wants to "clear other items" when landing on an item of the same scope)
ImGuiNavLayer NavLayer; // Focused layer (main scrolling layer, or menu/title bar layer)
- ImGuiID NavActivateId; // ~~ (g.ActiveId == 0) && (IsKeyPressed(ImGuiKey_Space) || IsKeyDown(ImGuiKey_Enter) || IsKeyPressed(ImGuiKey_NavGamepadActivate)) ? NavId : 0, also set when calling ActivateItem()
+ ImGuiID NavActivateId; // ~~ (g.ActiveId == 0) && (IsKeyPressed(ImGuiKey_Space) || IsKeyDown(ImGuiKey_Enter) || IsKeyPressed(ImGuiKey_NavGamepadActivate)) ? NavId : 0, also set when calling ActivateItemByID()
ImGuiID NavActivateDownId; // ~~ IsKeyDown(ImGuiKey_Space) || IsKeyDown(ImGuiKey_Enter) || IsKeyDown(ImGuiKey_NavGamepadActivate) ? NavId : 0
ImGuiID NavActivatePressedId; // ~~ IsKeyPressed(ImGuiKey_Space) || IsKeyPressed(ImGuiKey_Enter) || IsKeyPressed(ImGuiKey_NavGamepadActivate) ? NavId : 0 (no repeat)
ImGuiActivateFlags NavActivateFlags;
ImVector<ImGuiFocusScopeData> NavFocusRoute; // Reversed copy focus scope stack for NavId (should contains NavFocusScopeId). This essentially follow the window->ParentWindowForFocusRoute chain.
ImGuiID NavHighlightActivatedId;
float NavHighlightActivatedTimer;
- ImGuiID NavNextActivateId; // Set by ActivateItem(), queued until next frame.
+ ImGuiID NavNextActivateId; // Set by ActivateItemByID(), queued until next frame.
ImGuiActivateFlags NavNextActivateFlags;
ImGuiInputSource NavInputSource; // Keyboard or Gamepad mode? THIS CAN ONLY BE ImGuiInputSource_Keyboard or ImGuiInputSource_Mouse
ImGuiSelectionUserData NavLastValidSelectionUserData; // Last valid data passed to SetNextItemSelectionUser(), or -1. For current window. Not reset when focusing an item that doesn't have selection data.
ImS8 NavCursorHideFrames;
+ //ImGuiID NavActivateInputId; // Removed in 1.89.4 (July 2023). This is now part of g.NavActivateId and sets g.NavActivateFlags |= ImGuiActivateFlags_PreferInput. See commit c9a53aa74, issue #5606.
// Navigation: Init & Move Requests
bool NavAnyRequest; // ~~ NavMoveRequest || NavInitRequest this is to perform early out in ItemAdd()
@@ -2392,6 +2549,7 @@ struct ImGuiContext
bool NavJustMovedToHasSelectionData; // Copy of move result's ItemFlags & ImGuiItemFlags_HasSelectionUserData). Maybe we should just store ImGuiNavItemData.
// Navigation: Windowing (CTRL+TAB for list, or Menu button + keys or directional pads to move/resize)
+ bool ConfigNavWindowingWithGamepad; // = true. Enable CTRL+TAB by holding ImGuiKey_GamepadFaceLeft (== ImGuiKey_NavGamepadMenu). When false, the button may still be used to toggle Menu layer.
ImGuiKeyChord ConfigNavWindowingKeyNext; // = ImGuiMod_Ctrl | ImGuiKey_Tab (or ImGuiMod_Super | ImGuiKey_Tab on OS X). For reconfiguration (see #4828)
ImGuiKeyChord ConfigNavWindowingKeyPrev; // = ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Tab (or ImGuiMod_Super | ImGuiMod_Shift | ImGuiKey_Tab on OS X)
ImGuiWindow* NavWindowingTarget; // Target window when doing CTRL+Tab (or Pad Menu + FocusPrev/Next), this window is temporarily displayed top-most!
@@ -2399,8 +2557,9 @@ struct ImGuiContext
ImGuiWindow* NavWindowingListWindow; // Internal window actually listing the CTRL+Tab contents
float NavWindowingTimer;
float NavWindowingHighlightAlpha;
- bool NavWindowingToggleLayer;
- ImGuiKey NavWindowingToggleKey;
+ ImGuiInputSource NavWindowingInputSource;
+ bool NavWindowingToggleLayer; // Set while Alt or GamepadMenu is held, may be cleared by other operations, and processed when releasing the key.
+ ImGuiKey NavWindowingToggleKey; // Keyboard/gamepad key used when toggling to menu layer.
ImVec2 NavWindowingAccumDeltaPos;
ImVec2 NavWindowingAccumDeltaSize;
@@ -2468,8 +2627,10 @@ struct ImGuiContext
// Widget state
ImGuiInputTextState InputTextState;
+ ImGuiTextIndex InputTextLineIndex; // Temporary storage
ImGuiInputTextDeactivatedState InputTextDeactivatedState;
- ImFont InputTextPasswordFont;
+ ImFontBaked InputTextPasswordFontBackupBaked;
+ ImFontFlags InputTextPasswordFontBackupFlags;
ImGuiID TempInputId; // Temporary text input when CTRL+clicking on a slider, etc.
ImGuiDataTypeStorage DataTypeZeroValue; // 0 for all data types
int BeginMenuDepth;
@@ -2501,12 +2662,12 @@ struct ImGuiContext
ImGuiTypingSelectState TypingSelectState; // State for GetTypingSelectRequest()
// Platform support
- ImGuiPlatformImeData PlatformImeData; // Data updated by current frame
+ ImGuiPlatformImeData PlatformImeData; // Data updated by current frame. Will be applied at end of the frame. For some backends, this is required to have WantVisible=true in order to receive text message.
ImGuiPlatformImeData PlatformImeDataPrev; // Previous frame data. When changed we call the platform_io.Platform_SetImeDataFn() handler.
- ImGuiID PlatformImeViewport;
// Extensions
// FIXME: We could provide an API to register one slot in an array held in ImGuiContext?
+ ImVector<ImTextureData*> UserTextures; // List of textures created/managed by user or third-party extension. Automatically appended into platform_io.Textures[].
ImGuiDockContext DockContext;
void (*DockNodeWindowMenuHandler)(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar);
@@ -2525,7 +2686,8 @@ struct ImGuiContext
// Capture/Logging
bool LogEnabled; // Currently capturing
- ImGuiLogType LogType; // Capture target
+ ImGuiLogFlags LogFlags; // Capture flags/type
+ ImGuiWindow* LogWindow;
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.
const char* LogNextPrefix;
@@ -2567,6 +2729,10 @@ struct ImGuiContext
ImGuiIDStackTool DebugIDStackTool;
ImGuiDebugAllocInfo DebugAllocInfo;
ImGuiDockNode* DebugHoveredDockNode; // Hovered dock node.
+#if defined(IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS) && !defined(IMGUI_DISABLE_DEBUG_TOOLS)
+ ImGuiStorage DebugDrawIdConflictsAliveCount;
+ ImGuiStorage DebugDrawIdConflictsHighlightSet;
+#endif
// Misc
float FramerateSecPerFrame[60]; // Calculate estimate of framerate for user over the last 60 frames..
@@ -2575,7 +2741,7 @@ struct ImGuiContext
float FramerateSecPerFrameAccum;
int WantCaptureMouseNextFrame; // Explicit capture override via SetNextFrameWantCaptureMouse()/SetNextFrameWantCaptureKeyboard(). Default to -1.
int WantCaptureKeyboardNextFrame; // "
- int WantTextInputNextFrame;
+ int WantTextInputNextFrame; // Copied in EndFrame() from g.PlatformImeData.WantTextInput. Needs to be set for some backends (SDL3) to emit character inputs.
ImVector<char> TempBuffer; // Temporary text buffer
char TempKeychordName[64];
@@ -2621,7 +2787,8 @@ struct IMGUI_API ImGuiWindowTempData
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 TreeHasStackDataDepthMask; // Store whether given depth has ImGuiTreeNodeStackData data. Could be turned into a ImU64 if necessary.
+ ImU32 TreeHasStackDataDepthMask; // Store whether given depth has ImGuiTreeNodeStackData data. Could be turned into a ImU64 if necessary.
+ ImU32 TreeRecordsClippedNodesY2Mask; // Store whether we should keep recording Y2. Cleared when passing clip max. Equivalent TreeHasStackDataDepthMask value should always be set.
ImVector<ImGuiWindow*> ChildWindows;
ImGuiStorage* StateStorage; // Current persistent per-window storage (store e.g. tree node open/close state)
ImGuiOldColumns* CurrentColumns; // Current columns set
@@ -2630,6 +2797,12 @@ struct IMGUI_API ImGuiWindowTempData
ImGuiLayoutType ParentLayoutType; // Layout type of parent window at the time of Begin()
ImU32 ModalDimBgColor;
+ // Status flags
+ ImGuiItemStatusFlags WindowItemStatusFlags;
+ ImGuiItemStatusFlags ChildItemStatusFlags;
+ ImGuiItemStatusFlags DockTabItemStatusFlags;
+ ImRect DockTabItemRect;
+
// 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.
float ItemWidth; // Current item width (>0.0: width in pixels, <0.0: align xx pixels to the right of window).
@@ -2676,6 +2849,8 @@ struct IMGUI_API ImGuiWindow
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 ScrollbarXStabilizeEnabled; // Was ScrollbarX previously auto-stabilized?
+ ImU8 ScrollbarXStabilizeToggledHistory; // Used to stabilize scrollbar visibility in case of feedback loops
bool ViewportOwned;
bool Active; // Set to true on Begin(), unless Collapsed
bool WasActive;
@@ -2732,7 +2907,8 @@ struct IMGUI_API ImGuiWindow
ImGuiStorage StateStorage;
ImVector<ImGuiOldColumns> ColumnsStorage;
float FontWindowScale; // User scale multiplier per-window, via SetWindowFontScale()
- float FontDpiScale;
+ float FontWindowScaleParents;
+ float FontRefSize; // This is a copy of window->CalcFontSize() at the time of Begin(), trying to phase out CalcFontSize() especially as it may be called on non-current window.
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)
@@ -2766,8 +2942,6 @@ struct IMGUI_API ImGuiWindow
ImGuiDockNode* DockNode; // Which node are we docked into. Important: Prefer testing DockIsActive in many cases as this will still be set when the dock node is hidden.
ImGuiDockNode* DockNodeAsHost; // Which node are we owning (for parent windows)
ImGuiID DockId; // Backup of last valid DockNode->ID, so single window remember their dock node id even when they are not bound any more
- ImGuiItemStatusFlags DockTabItemStatusFlags;
- ImRect DockTabItemRect;
public:
ImGuiWindow(ImGuiContext* context, const char* name);
@@ -2781,9 +2955,11 @@ public:
// We don't use g.FontSize because the window may be != g.CurrentWindow.
ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); }
- float CalcFontSize() const { ImGuiContext& g = *Ctx; float scale = g.FontBaseSize * FontWindowScale * FontDpiScale; if (ParentWindow) scale *= ParentWindow->FontWindowScale; return scale; }
ImRect TitleBarRect() const { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight)); }
ImRect MenuBarRect() const { float y1 = Pos.y + TitleBarHeight; return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight); }
+
+ // [Obsolete] ImGuiWindow::CalcFontSize() was removed in 1.92.x because error-prone/misleading. You can use window->FontRefSize for a copy of g.FontSize at the time of the last Begin() call for this window.
+ //float CalcFontSize() const { ImGuiContext& g = *Ctx; return g.FontSizeBase * FontWindowScale * FontDpiScale * FontWindowScaleParents;
};
//-----------------------------------------------------------------------------
@@ -2804,7 +2980,8 @@ enum ImGuiTabItemFlagsPrivate_
ImGuiTabItemFlags_SectionMask_ = ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing,
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
- ImGuiTabItemFlags_Unsorted = 1 << 22, // [Docking] Trailing tabs with the _Unsorted flag will be sorted based on the DockOrder of their Window.
+ ImGuiTabItemFlags_Invisible = 1 << 22, // To reserve space e.g. with ImGuiTabItemFlags_Leading
+ ImGuiTabItemFlags_Unsorted = 1 << 23, // [Docking] Trailing tabs with the _Unsorted flag will be sorted based on the DockOrder of their Window.
};
// Storage for one active tab item (sizeof() 48 bytes)
@@ -2817,7 +2994,7 @@ struct ImGuiTabItem
int LastFrameSelected; // This allows us to infer an ordered list of the last activated tabs with little maintenance
float Offset; // Position relative to beginning of tab
float Width; // Width currently displayed
- float ContentWidth; // Width of label, stored during BeginTabItem() call
+ float ContentWidth; // Width of label + padding, stored during BeginTabItem() call (misnamed as "Content" would normally imply width of label only)
float RequestedWidth; // Width optionally requested by caller, -1.0f is unused
ImS32 NameOffset; // When Window==NULL, offset to name within parent ImGuiTabBar::TabsNames
ImS16 BeginOrder; // BeginTabItem() order, used to re-order tabs after toggling ImGuiTabBarFlags_Reorderable
@@ -2840,6 +3017,7 @@ struct IMGUI_API ImGuiTabBar
int CurrFrameVisible;
int PrevFrameVisible;
ImRect BarRect;
+ float BarRectPrevWidth; // Backup of previous width. When width change we enforce keep horizontal scroll on focused tab.
float CurrTabsContentsHeight;
float PrevTabsContentsHeight; // Record the height of contents submitted below the tab bar
float WidthAllTabs; // Actual width of all tabs (locked during layout)
@@ -2858,6 +3036,7 @@ struct IMGUI_API ImGuiTabBar
bool WantLayout;
bool VisibleTabWasSubmitted;
bool TabsAddedNew; // Set to true when a new tab item or button has been added to the tab bar during last frame
+ bool ScrollButtonEnabled;
ImS16 TabsActiveCount; // Number of tabs submitted this frame.
ImS16 LastTabItemIdx; // Index of last BeginTabItem() tab for use by EndTabItem()
float ItemSpacingY;
@@ -2873,11 +3052,7 @@ struct IMGUI_API ImGuiTabBar
//-----------------------------------------------------------------------------
#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 512 // May be further lifted
-
-// Our current column maximum is 64 but we may raise that in the future.
-typedef ImS16 ImGuiTableColumnIdx;
-typedef ImU16 ImGuiTableDrawChannelIdx;
+#define IMGUI_TABLE_MAX_COLUMNS 512 // Arbitrary "safety" maximum, may be lifted in the future if needed. Must fit in ImGuiTableColumnIdx/ImGuiTableDrawChannelIdx.
// [Internal] sizeof() ~ 112
// We use the terminology "Enabled" to refer to a column that is not Hidden by user/api.
@@ -2979,7 +3154,7 @@ struct IMGUI_API ImGuiTable
{
ImGuiID ID;
ImGuiTableFlags Flags;
- void* RawData; // Single allocation to hold Columns[], DisplayOrderToIndex[] and RowCellData[]
+ void* RawData; // Single allocation to hold Columns[], DisplayOrderToIndex[], and RowCellData[]
ImGuiTableTempData* TempData; // Transient data while table is active. Point within g.CurrentTableStack[]
ImSpan<ImGuiTableColumn> Columns; // Point within RawData[]
ImSpan<ImGuiTableColumnIdx> DisplayOrderToIndex; // Point within RawData[]. Store display order of columns (when not reordered, the values are 0...Count-1)
@@ -2993,7 +3168,7 @@ struct IMGUI_API ImGuiTable
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 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 tables with the same ID are multiple tables, they are just synced.
ImS16 InstanceInteracted; // Mark which instance (generally 0) of the same ID is being interacted with
float RowPosY1;
float RowPosY2;
@@ -3025,7 +3200,7 @@ struct IMGUI_API ImGuiTable
float AngledHeadersHeight; // Set by TableAngledHeadersRow(), used in TableUpdateLayout()
float AngledHeadersSlope; // Set by TableAngledHeadersRow(), used in TableUpdateLayout()
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 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, evolve during the frame as we cross frozen rows boundaries
@@ -3069,13 +3244,14 @@ struct IMGUI_API ImGuiTable
ImGuiTableDrawChannelIdx DummyDrawChannel; // Redirect non-visible columns here.
ImGuiTableDrawChannelIdx Bg2DrawChannelCurrent; // For Selectable() and other widgets drawing across columns after the freezing line. Index within DrawSplitter.Channels[]
ImGuiTableDrawChannelIdx Bg2DrawChannelUnfrozen;
+ ImS8 NavLayer; // ImGuiNavLayer at the time of BeginTable().
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 DisableDefaultContextMenu; // Disable default context menu contents. You may submit your own using TableBeginContextMenuPopup()/EndPopup()
+ bool DisableDefaultContextMenu; // Disable default context menu. You may submit your own using TableBeginContextMenuPopup()/EndPopup()
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)
@@ -3121,7 +3297,7 @@ struct IMGUI_API ImGuiTableTempData
ImGuiTableTempData() { memset(this, 0, sizeof(*this)); LastTimeActive = -1.0f; }
};
-// sizeof() ~ 12
+// sizeof() ~ 16
struct ImGuiTableColumnSettings
{
float WidthOrWeight;
@@ -3130,7 +3306,7 @@ struct ImGuiTableColumnSettings
ImGuiTableColumnIdx DisplayOrder;
ImGuiTableColumnIdx SortOrder;
ImU8 SortDirection : 2;
- ImU8 IsEnabled : 1; // "Visible" in ini file
+ ImS8 IsEnabled : 2; // "Visible" in ini file
ImU8 IsStretch : 1;
ImGuiTableColumnSettings()
@@ -3140,7 +3316,7 @@ struct ImGuiTableColumnSettings
Index = -1;
DisplayOrder = SortOrder = -1;
SortDirection = ImGuiSortDirection_None;
- IsEnabled = 1;
+ IsEnabled = -1;
IsStretch = 0;
}
};
@@ -3171,6 +3347,8 @@ namespace ImGui
// If this ever crashes because g.CurrentWindow is NULL, it means that either:
// - ImGui::NewFrame() has never been called, which is illegal.
// - You are calling ImGui functions after ImGui::EndFrame()/ImGui::Render() and before the next ImGui::NewFrame(), which is also illegal.
+ IMGUI_API ImGuiIO& GetIO(ImGuiContext* ctx);
+ IMGUI_API ImGuiPlatformIO& GetPlatformIO(ImGuiContext* ctx);
inline ImGuiWindow* GetCurrentWindowRead() { ImGuiContext& g = *GImGui; return g.CurrentWindow; }
inline ImGuiWindow* GetCurrentWindow() { ImGuiContext& g = *GImGui; g.CurrentWindow->WriteAccessed = true; return g.CurrentWindow; }
IMGUI_API ImGuiWindow* FindWindowByID(ImGuiID id);
@@ -3207,8 +3385,18 @@ namespace ImGui
IMGUI_API void SetNextWindowRefreshPolicy(ImGuiWindowRefreshFlags flags);
// 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]; }
+ IMGUI_API void RegisterUserTexture(ImTextureData* tex); // Register external texture. EXPERIMENTAL: DO NOT USE YET.
+ IMGUI_API void UnregisterUserTexture(ImTextureData* tex);
+ IMGUI_API void RegisterFontAtlas(ImFontAtlas* atlas);
+ IMGUI_API void UnregisterFontAtlas(ImFontAtlas* atlas);
+ IMGUI_API void SetCurrentFont(ImFont* font, float font_size_before_scaling, float font_size_after_scaling);
+ IMGUI_API void UpdateCurrentFontSize(float restore_font_size_after_scaling);
+ IMGUI_API void SetFontRasterizerDensity(float rasterizer_density);
+ inline float GetFontRasterizerDensity() { return GImGui->FontRasterizerDensity; }
+ inline float GetRoundedFontSize(float size) { return IM_ROUND(size); }
+ IMGUI_API ImFont* GetDefaultFont();
+ IMGUI_API void PushPasswordFont();
+ IMGUI_API void PopPasswordFont();
inline ImDrawList* GetForegroundDrawList(ImGuiWindow* window) { return GetForegroundDrawList(window->Viewport); }
IMGUI_API void AddDrawListToDrawDataEx(ImDrawData* draw_data, ImVector<ImDrawList*>* out_list, ImDrawList* draw_list);
@@ -3218,10 +3406,11 @@ namespace ImGui
// NewFrame
IMGUI_API void UpdateInputEvents(bool trickle_fast_inputs);
- IMGUI_API void UpdateHoveredWindowAndCaptureFlags();
+ IMGUI_API void UpdateHoveredWindowAndCaptureFlags(const ImVec2& mouse_pos);
IMGUI_API void FindHoveredWindowEx(const ImVec2& pos, bool find_first_and_in_any_viewport, ImGuiWindow** out_hovered_window, ImGuiWindow** out_hovered_window_under_moving_window);
IMGUI_API void StartMouseMovingWindow(ImGuiWindow* window);
IMGUI_API void StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock);
+ IMGUI_API void StopMouseMovingWindow();
IMGUI_API void UpdateMouseMovingWindowNewFrame();
IMGUI_API void UpdateMouseMovingWindowEndFrame();
@@ -3294,19 +3483,20 @@ namespace ImGui
IMGUI_API bool ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flags);
IMGUI_API bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags = 0);
IMGUI_API bool IsClippedEx(const ImRect& bb, ImGuiID id);
- IMGUI_API void SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags status_flags, const ImRect& item_rect);
+ IMGUI_API void SetLastItemData(ImGuiID item_id, ImGuiItemFlags item_flags, ImGuiItemStatusFlags status_flags, const ImRect& item_rect);
IMGUI_API ImVec2 CalcItemSize(ImVec2 size, float default_w, float default_h);
IMGUI_API float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x);
IMGUI_API void PushMultiItemsWidths(int components, float width_full);
- IMGUI_API void ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess);
+ IMGUI_API void ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess, float width_min);
+ IMGUI_API void CalcClipRectVisibleItemsY(const ImRect& clip_rect, const ImVec2& pos, float items_height, int* out_visible_start, int* out_visible_end);
// Parameter stacks (shared)
- IMGUI_API const ImGuiDataVarInfo* GetStyleVarInfo(ImGuiStyleVar idx);
+ IMGUI_API const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx);
IMGUI_API void BeginDisabledOverrideReenable();
IMGUI_API void EndDisabledOverrideReenable();
// 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 LogBegin(ImGuiLogFlags flags, 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 LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end = NULL);
IMGUI_API void LogSetNextTextDecoration(const char* prefix, const char* suffix);
@@ -3316,6 +3506,7 @@ namespace ImGui
// Popups, Modals
IMGUI_API bool BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_window_flags);
+ IMGUI_API bool BeginPopupMenuEx(ImGuiID id, const char* label, ImGuiWindowFlags extra_window_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);
@@ -3349,7 +3540,7 @@ namespace ImGui
IMGUI_API void NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags);
IMGUI_API void NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags);
IMGUI_API void NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result);
- IMGUI_API void NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, ImGuiTreeNodeStackData* tree_node_data);
+ IMGUI_API void NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, const ImGuiTreeNodeStackData* tree_node_data);
IMGUI_API void NavMoveRequestCancel();
IMGUI_API void NavMoveRequestApplyResult();
IMGUI_API void NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags);
@@ -3365,7 +3556,7 @@ namespace ImGui
// This should be part of a larger set of API: FocusItem(offset = -1), FocusItemByID(id), ActivateItem(offset = -1), ActivateItemByID(id) etc. which are
// much harder to design and implement than expected. I have a couple of private branches on this matter but it's not simple. For now implementing the easy ones.
IMGUI_API void FocusItem(); // Focus last item (no selection/activation).
- IMGUI_API void ActivateItemByID(ImGuiID id); // Activate an item by ID (button, checkbox, tree node etc.). Activation is queued and processed on the next frame when the item is encountered again.
+ IMGUI_API void ActivateItemByID(ImGuiID id); // Activate an item by ID (button, checkbox, tree node etc.). Activation is queued and processed on the next frame when the item is encountered again. Was called 'ActivateItem()' before 1.89.7.
// Inputs
// FIXME: Eventually we should aim to move e.g. IsActiveIdUsingKey() into IsKeyXXX functions.
@@ -3567,6 +3758,8 @@ namespace ImGui
IMGUI_API float TableGetHeaderAngledMaxLabelWidth();
IMGUI_API void TablePushBackgroundChannel();
IMGUI_API void TablePopBackgroundChannel();
+ IMGUI_API void TablePushColumnChannel(int column_n);
+ IMGUI_API void TablePopColumnChannel();
IMGUI_API void TableAngledHeadersRowEx(ImGuiID row_id, float angle, float max_label_width, const ImGuiTableHeaderData* data, int data_count);
// Tables: Internals
@@ -3616,6 +3809,8 @@ namespace ImGui
// Tab Bars
inline ImGuiTabBar* GetCurrentTabBar() { ImGuiContext& g = *GImGui; return g.CurrentTabBar; }
+ IMGUI_API ImGuiTabBar* TabBarFindByID(ImGuiID id);
+ IMGUI_API void TabBarRemove(ImGuiTabBar* tab_bar);
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* TabBarFindTabByOrder(ImGuiTabBar* tab_bar, int order);
@@ -3632,6 +3827,7 @@ namespace ImGui
IMGUI_API void TabBarQueueReorderFromMousePos(ImGuiTabBar* tab_bar, ImGuiTabItem* tab, ImVec2 mouse_pos);
IMGUI_API bool TabBarProcessReorder(ImGuiTabBar* tab_bar);
IMGUI_API bool TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags, ImGuiWindow* docked_window);
+ IMGUI_API void TabItemSpacing(const char* str_id, ImGuiTabItemFlags flags, float width);
IMGUI_API ImVec2 TabItemCalcSize(const char* label, bool has_close_button_or_unsaved_marker);
IMGUI_API ImVec2 TabItemCalcSize(ImGuiWindow* window);
IMGUI_API void TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImU32 col);
@@ -3644,7 +3840,7 @@ namespace ImGui
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 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 RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, 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 borders = true, float rounding = 0.0f);
IMGUI_API void RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding = 0.0f);
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, ImDrawFlags flags = 0);
@@ -3665,11 +3861,15 @@ namespace ImGui
IMGUI_API void RenderRectFilledWithHole(ImDrawList* draw_list, const ImRect& outer, const ImRect& inner, ImU32 col, float rounding);
IMGUI_API ImDrawFlags CalcRoundingFlagsForRectInRect(const ImRect& r_in, const ImRect& r_outer, float threshold);
- // Widgets
+ // Widgets: Text
IMGUI_API void TextEx(const char* text, const char* text_end = NULL, ImGuiTextFlags flags = 0);
+ IMGUI_API void TextAligned(float align_x, float size_x, const char* fmt, ...); // FIXME-WIP: Works but API is likely to be reworked. This is designed for 1 item on the line. (#7024)
+ IMGUI_API void TextAlignedV(float align_x, float size_x, const char* fmt, va_list args);
+
+ // Widgets
IMGUI_API bool ButtonEx(const char* label, const ImVec2& size_arg = ImVec2(0, 0), ImGuiButtonFlags flags = 0);
IMGUI_API bool ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size_arg, ImGuiButtonFlags flags = 0);
- IMGUI_API bool ImageButtonEx(ImGuiID id, ImTextureID texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col, ImGuiButtonFlags flags = 0);
+ IMGUI_API bool ImageButtonEx(ImGuiID id, ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col, ImGuiButtonFlags flags = 0);
IMGUI_API void SeparatorEx(ImGuiSeparatorFlags flags, float thickness = 1.0f);
IMGUI_API void SeparatorTextEx(ImGuiID id, const char* label, const char* label_end, float extra_width);
IMGUI_API bool CheckboxFlags(const char* label, ImS64* flags, ImS64 flags_value);
@@ -3679,7 +3879,7 @@ namespace ImGui
IMGUI_API bool CloseButton(ImGuiID id, const ImVec2& pos);
IMGUI_API bool CollapseButton(ImGuiID id, const ImVec2& pos, ImGuiDockNode* dock_node);
IMGUI_API void Scrollbar(ImGuiAxis axis);
- IMGUI_API bool ScrollbarEx(const ImRect& bb, ImGuiID id, ImGuiAxis axis, ImS64* p_scroll_v, ImS64 avail_v, ImS64 contents_v, ImDrawFlags flags);
+ IMGUI_API bool ScrollbarEx(const ImRect& bb, ImGuiID id, ImGuiAxis axis, ImS64* p_scroll_v, ImS64 avail_v, ImS64 contents_v, ImDrawFlags draw_rounding_flags = 0);
IMGUI_API ImRect GetWindowScrollbarRect(ImGuiWindow* window, ImGuiAxis axis);
IMGUI_API ImGuiID GetWindowScrollbarID(ImGuiWindow* window, ImGuiAxis axis);
IMGUI_API ImGuiID GetWindowResizeCornerID(ImGuiWindow* window, int n); // 0..3: corners
@@ -3693,6 +3893,8 @@ namespace ImGui
// Widgets: Tree Nodes
IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL);
+ IMGUI_API void TreeNodeDrawLineToChildNode(const ImVec2& target_pos);
+ IMGUI_API void TreeNodeDrawLineToTreePop(const ImGuiTreeNodeStackData* data);
IMGUI_API void TreePushOverrideID(ImGuiID id);
IMGUI_API bool TreeNodeGetOpen(ImGuiID storage_id);
IMGUI_API void TreeNodeSetOpen(ImGuiID storage_id, bool open);
@@ -3725,6 +3927,7 @@ namespace ImGui
inline bool TempInputIsActive(ImGuiID id) { ImGuiContext& g = *GImGui; return (g.ActiveId == id && g.TempInputId == id); }
inline ImGuiInputTextState* GetInputTextState(ImGuiID id) { ImGuiContext& g = *GImGui; return (id != 0 && g.InputTextState.ID == id) ? &g.InputTextState : NULL; } // Get input text state if active
IMGUI_API void SetNextItemRefVal(ImGuiDataType data_type, void* p_data);
+ inline bool IsItemActiveAsInputText() { ImGuiContext& g = *GImGui; return g.ActiveId != 0 && g.ActiveId == g.LastItemData.ID && g.InputTextState.ID == g.LastItemData.ID; } // This may be useful to apply workaround that a based on distinguish whenever an item is active as a text input field.
// Color
IMGUI_API void ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags);
@@ -3773,7 +3976,9 @@ namespace ImGui
IMGUI_API void DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label);
IMGUI_API void DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb);
IMGUI_API void DebugNodeFont(ImFont* font);
+ IMGUI_API void DebugNodeFontGlyphesForSrcMask(ImFont* font, ImFontBaked* baked, int src_mask);
IMGUI_API void DebugNodeFontGlyph(ImFont* font, const ImFontGlyph* glyph);
+ IMGUI_API void DebugNodeTexture(ImTextureData* tex, int int_id, const ImFontAtlasRect* highlight_rect = NULL); // ID used to facilitate persisting the "current" texture.
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);
@@ -3808,28 +4013,193 @@ namespace ImGui
//-----------------------------------------------------------------------------
-// [SECTION] ImFontAtlas internal API
+// [SECTION] ImFontLoader
//-----------------------------------------------------------------------------
-// This structure is likely to evolve as we add support for incremental atlas updates
-struct ImFontBuilderIO
+// Hooks and storage for a given font backend.
+// This structure is likely to evolve as we add support for incremental atlas updates.
+// Conceptually this could be public, but API is still going to be evolve.
+struct ImFontLoader
{
- bool (*FontBuilder_Build)(ImFontAtlas* atlas);
+ const char* Name;
+ bool (*LoaderInit)(ImFontAtlas* atlas);
+ void (*LoaderShutdown)(ImFontAtlas* atlas);
+ bool (*FontSrcInit)(ImFontAtlas* atlas, ImFontConfig* src);
+ void (*FontSrcDestroy)(ImFontAtlas* atlas, ImFontConfig* src);
+ bool (*FontSrcContainsGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint);
+ bool (*FontBakedInit)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src);
+ void (*FontBakedDestroy)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src);
+ bool (*FontBakedLoadGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, ImWchar codepoint, ImFontGlyph* out_glyph, float* out_advance_x);
+
+ // Size of backend data, Per Baked * Per Source. Buffers are managed by core to avoid excessive allocations.
+ // FIXME: At this point the two other types of buffers may be managed by core to be consistent?
+ size_t FontBakedSrcLoaderDataSize;
+
+ ImFontLoader() { memset(this, 0, sizeof(*this)); }
};
-// Helper for font builder
#ifdef IMGUI_ENABLE_STB_TRUETYPE
-IMGUI_API const ImFontBuilderIO* ImFontAtlasGetBuilderForStbTruetype();
+IMGUI_API const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype();
+#endif
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+typedef ImFontLoader ImFontBuilderIO; // [renamed/changed in 1.92] The types are not actually compatible but we provide this as a compile-time error report helper.
+#endif
+
+//-----------------------------------------------------------------------------
+// [SECTION] ImFontAtlas internal API
+//-----------------------------------------------------------------------------
+
+#define IMGUI_FONT_SIZE_MAX (512.0f)
+#define IMGUI_FONT_SIZE_THRESHOLD_FOR_LOADADVANCEXONLYMODE (128.0f)
+
+// Helpers: ImTextureRef ==/!= operators provided as convenience
+// (note that _TexID and _TexData are never set simultaneously)
+inline bool operator==(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID == rhs._TexID && lhs._TexData == rhs._TexData; }
+inline bool operator!=(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID != rhs._TexID || lhs._TexData != rhs._TexData; }
+
+// Refer to ImFontAtlasPackGetRect() to better understand how this works.
+#define ImFontAtlasRectId_IndexMask_ (0x0007FFFF) // 20-bits signed: index to access builder->RectsIndex[].
+#define ImFontAtlasRectId_GenerationMask_ (0x3FF00000) // 10-bits: entry generation, so each ID is unique and get can safely detected old identifiers.
+#define ImFontAtlasRectId_GenerationShift_ (20)
+inline int ImFontAtlasRectId_GetIndex(ImFontAtlasRectId id) { return (id & ImFontAtlasRectId_IndexMask_); }
+inline unsigned int ImFontAtlasRectId_GetGeneration(ImFontAtlasRectId id) { return (unsigned int)(id & ImFontAtlasRectId_GenerationMask_) >> ImFontAtlasRectId_GenerationShift_; }
+inline ImFontAtlasRectId ImFontAtlasRectId_Make(int index_idx, int gen_idx) { IM_ASSERT(index_idx >= 0 && index_idx <= ImFontAtlasRectId_IndexMask_ && gen_idx <= (ImFontAtlasRectId_GenerationMask_ >> ImFontAtlasRectId_GenerationShift_)); return (ImFontAtlasRectId)(index_idx | (gen_idx << ImFontAtlasRectId_GenerationShift_)); }
+
+// Packed rectangle lookup entry (we need an indirection to allow removing/reordering rectangles)
+// User are returned ImFontAtlasRectId values which are meant to be persistent.
+// We handle this with an indirection. While Rects[] may be in theory shuffled, compacted etc., RectsIndex[] cannot it is keyed by ImFontAtlasRectId.
+// RectsIndex[] is used both as an index into Rects[] and an index into itself. This is basically a free-list. See ImFontAtlasBuildAllocRectIndexEntry() code.
+// Having this also makes it easier to e.g. sort rectangles during repack.
+struct ImFontAtlasRectEntry
+{
+ int TargetIndex : 20; // When Used: ImFontAtlasRectId -> into Rects[]. When unused: index to next unused RectsIndex[] slot to consume free-list.
+ unsigned int Generation : 10; // Increased each time the entry is reused for a new rectangle.
+ unsigned int IsUsed : 1;
+};
+
+// Data available to potential texture post-processing functions
+struct ImFontAtlasPostProcessData
+{
+ ImFontAtlas* FontAtlas;
+ ImFont* Font;
+ ImFontConfig* FontSrc;
+ ImFontBaked* FontBaked;
+ ImFontGlyph* Glyph;
+
+ // Pixel data
+ void* Pixels;
+ ImTextureFormat Format;
+ int Pitch;
+ int Width;
+ int Height;
+};
+
+// We avoid dragging imstb_rectpack.h into public header (partly because binding generators are having issues with it)
+#ifdef IMGUI_STB_NAMESPACE
+namespace IMGUI_STB_NAMESPACE { struct stbrp_node; }
+typedef IMGUI_STB_NAMESPACE::stbrp_node stbrp_node_im;
+#else
+struct stbrp_node;
+typedef stbrp_node stbrp_node_im;
#endif
-IMGUI_API void ImFontAtlasUpdateConfigDataPointers(ImFontAtlas* atlas);
-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 x, int y, int w, int h, const char* in_str, char in_marker_char, unsigned char in_marker_pixel_value);
-IMGUI_API void ImFontAtlasBuildRender32bppRectFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char, unsigned int 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);
+struct stbrp_context_opaque { char data[80]; };
+
+// Internal storage for incrementally packing and building a ImFontAtlas
+struct ImFontAtlasBuilder
+{
+ stbrp_context_opaque PackContext; // Actually 'stbrp_context' but we don't want to define this in the header file.
+ ImVector<stbrp_node_im> PackNodes;
+ ImVector<ImTextureRect> Rects;
+ ImVector<ImFontAtlasRectEntry> RectsIndex; // ImFontAtlasRectId -> index into Rects[]
+ ImVector<unsigned char> TempBuffer; // Misc scratch buffer
+ int RectsIndexFreeListStart;// First unused entry
+ int RectsPackedCount; // Number of packed rectangles.
+ int RectsPackedSurface; // Number of packed pixels. Used when compacting to heuristically find the ideal texture size.
+ int RectsDiscardedCount;
+ int RectsDiscardedSurface;
+ int FrameCount; // Current frame count
+ ImVec2i MaxRectSize; // Largest rectangle to pack (de-facto used as a "minimum texture size")
+ ImVec2i MaxRectBounds; // Bottom-right most used pixels
+ bool LockDisableResize; // Disable resizing texture
+ bool PreloadedAllGlyphsRanges; // Set when missing ImGuiBackendFlags_RendererHasTextures features forces atlas to preload everything.
+
+ // Cache of all ImFontBaked
+ ImStableVector<ImFontBaked,32> BakedPool;
+ ImGuiStorage BakedMap; // BakedId --> ImFontBaked*
+ int BakedDiscardedCount;
+
+ // Custom rectangle identifiers
+ ImFontAtlasRectId PackIdMouseCursors; // White pixel + mouse cursors. Also happen to be fallback in case of packing failure.
+ ImFontAtlasRectId PackIdLinesTexData;
+
+ ImFontAtlasBuilder() { memset(this, 0, sizeof(*this)); FrameCount = -1; RectsIndexFreeListStart = -1; PackIdMouseCursors = PackIdLinesTexData = -1; }
+};
+
+IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas* atlas);
+IMGUI_API void ImFontAtlasBuildDestroy(ImFontAtlas* atlas);
+IMGUI_API void ImFontAtlasBuildMain(ImFontAtlas* atlas);
+IMGUI_API void ImFontAtlasBuildSetupFontLoader(ImFontAtlas* atlas, const ImFontLoader* font_loader);
+IMGUI_API void ImFontAtlasBuildUpdatePointers(ImFontAtlas* atlas);
+IMGUI_API void ImFontAtlasBuildRenderBitmapFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char);
+IMGUI_API void ImFontAtlasBuildClear(ImFontAtlas* atlas); // Clear output and custom rects
+
+IMGUI_API ImTextureData* ImFontAtlasTextureAdd(ImFontAtlas* atlas, int w, int h);
+IMGUI_API void ImFontAtlasTextureMakeSpace(ImFontAtlas* atlas);
+IMGUI_API void ImFontAtlasTextureRepack(ImFontAtlas* atlas, int w, int h);
+IMGUI_API void ImFontAtlasTextureGrow(ImFontAtlas* atlas, int old_w = -1, int old_h = -1);
+IMGUI_API void ImFontAtlasTextureCompact(ImFontAtlas* atlas);
+IMGUI_API ImVec2i ImFontAtlasTextureGetSizeEstimate(ImFontAtlas* atlas);
+
+IMGUI_API void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src);
+IMGUI_API void ImFontAtlasBuildLegacyPreloadAllGlyphRanges(ImFontAtlas* atlas); // Legacy
+IMGUI_API void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, ImFontBaked* baked, int* out_oversample_h, int* out_oversample_v);
+IMGUI_API void ImFontAtlasBuildDiscardBakes(ImFontAtlas* atlas, int unused_frames);
+
+IMGUI_API bool ImFontAtlasFontSourceInit(ImFontAtlas* atlas, ImFontConfig* src);
+IMGUI_API void ImFontAtlasFontSourceAddToFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src);
+IMGUI_API void ImFontAtlasFontDestroySourceData(ImFontAtlas* atlas, ImFontConfig* src);
+IMGUI_API bool ImFontAtlasFontInitOutput(ImFontAtlas* atlas, ImFont* font); // Using FontDestroyOutput/FontInitOutput sequence useful notably if font loader params have changed
+IMGUI_API void ImFontAtlasFontDestroyOutput(ImFontAtlas* atlas, ImFont* font);
+IMGUI_API void ImFontAtlasFontDiscardBakes(ImFontAtlas* atlas, ImFont* font, int unused_frames);
+
+IMGUI_API ImGuiID ImFontAtlasBakedGetId(ImGuiID font_id, float baked_size, float rasterizer_density);
+IMGUI_API ImFontBaked* ImFontAtlasBakedGetOrAdd(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density);
+IMGUI_API ImFontBaked* ImFontAtlasBakedGetClosestMatch(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density);
+IMGUI_API ImFontBaked* ImFontAtlasBakedAdd(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density, ImGuiID baked_id);
+IMGUI_API void ImFontAtlasBakedDiscard(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked);
+IMGUI_API ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, const ImFontGlyph* in_glyph);
+IMGUI_API void ImFontAtlasBakedAddFontGlyphAdvancedX(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImWchar codepoint, float advance_x);
+IMGUI_API void ImFontAtlasBakedDiscardFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked, ImFontGlyph* glyph);
+IMGUI_API void ImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImFontGlyph* glyph, ImTextureRect* r, const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch);
+
+IMGUI_API void ImFontAtlasPackInit(ImFontAtlas* atlas);
+IMGUI_API ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFontAtlasRectEntry* overwrite_entry = NULL);
+IMGUI_API ImTextureRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id);
+IMGUI_API ImTextureRect* ImFontAtlasPackGetRectSafe(ImFontAtlas* atlas, ImFontAtlasRectId id);
+IMGUI_API void ImFontAtlasPackDiscardRect(ImFontAtlas* atlas, ImFontAtlasRectId id);
+
+IMGUI_API void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas, int frame_count, bool renderer_has_textures);
+IMGUI_API void ImFontAtlasAddDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data);
+IMGUI_API void ImFontAtlasRemoveDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data);
+IMGUI_API void ImFontAtlasUpdateDrawListsTextures(ImFontAtlas* atlas, ImTextureRef old_tex, ImTextureRef new_tex);
+IMGUI_API void ImFontAtlasUpdateDrawListsSharedData(ImFontAtlas* atlas);
+
+IMGUI_API void ImFontAtlasTextureBlockConvert(const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch, unsigned char* dst_pixels, ImTextureFormat dst_fmt, int dst_pitch, int w, int h);
+IMGUI_API void ImFontAtlasTextureBlockPostProcess(ImFontAtlasPostProcessData* data);
+IMGUI_API void ImFontAtlasTextureBlockPostProcessMultiply(ImFontAtlasPostProcessData* data, float multiply_factor);
+IMGUI_API void ImFontAtlasTextureBlockFill(ImTextureData* dst_tex, int dst_x, int dst_y, int w, int h, ImU32 col);
+IMGUI_API void ImFontAtlasTextureBlockCopy(ImTextureData* src_tex, int src_x, int src_y, ImTextureData* dst_tex, int dst_x, int dst_y, int w, int h);
+IMGUI_API void ImFontAtlasTextureBlockQueueUpload(ImFontAtlas* atlas, ImTextureData* tex, int x, int y, int w, int h);
+
+IMGUI_API int ImTextureDataGetFormatBytesPerPixel(ImTextureFormat format);
+IMGUI_API const char* ImTextureDataGetStatusName(ImTextureStatus status);
+IMGUI_API const char* ImTextureDataGetFormatName(ImTextureFormat format);
+
+#ifndef IMGUI_DISABLE_DEBUG_TOOLS
+IMGUI_API void ImFontAtlasDebugLogTextureRequests(ImFontAtlas* atlas);
+#endif
+
+IMGUI_API bool ImFontAtlasGetMouseCursorTexData(ImFontAtlas* atlas, ImGuiMouseCursor cursor_type, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]);
//-----------------------------------------------------------------------------
// [SECTION] Test Engine specific hooks (imgui_test_engine)
diff --git a/source/code/Libs/imgui/imgui_tables.cpp b/source/code/Libs/imgui/imgui_tables.cpp index 598496b..f5c4c25 100644 --- a/source/code/Libs/imgui/imgui_tables.cpp +++ b/source/code/Libs/imgui/imgui_tables.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.4
+// dear imgui, v1.92.3
// (tables and columns code)
/*
@@ -221,6 +221,7 @@ Index of this file:
#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" // warning: format specifies type 'int' but the argument has type 'unsigned int'
#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
@@ -229,9 +230,15 @@ Index of this file:
#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
#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access
+#pragma clang diagnostic ignored "-Wnontrivial-memaccess" // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
+#pragma clang diagnostic ignored "-Wswitch-default" // warning: 'switch' missing 'default' label
#elif defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
+#pragma GCC diagnostic ignored "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe
#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
+#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
+#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'int'/'void*', but argument X has type 'unsigned int'/'ImGuiWindow*'
+#pragma GCC diagnostic ignored "-Wstrict-overflow"
#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
@@ -335,6 +342,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG
{
ItemSize(outer_rect);
ItemAdd(outer_rect, id);
+ g.NextWindowData.ClearFlags();
return false;
}
@@ -369,6 +377,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG
table->ColumnsCount = columns_count;
table->IsLayoutLocked = false;
table->InnerWidth = inner_width;
+ table->NavLayer = (ImS8)outer_window->DC.NavLayerCurrent;
temp_data->UserOuterSize = outer_size;
// Instance data (for instance 0, TableID == TableInstanceID)
@@ -409,11 +418,15 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG
// Reset scroll if we are reactivating it
if ((previous_flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) == 0)
- SetNextWindowScroll(ImVec2(0.0f, 0.0f));
+ if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasScroll) == 0)
+ SetNextWindowScroll(ImVec2(0.0f, 0.0f));
// Create scrolling region (without border and zero window padding)
- ImGuiWindowFlags child_window_flags = (flags & ImGuiTableFlags_ScrollX) ? ImGuiWindowFlags_HorizontalScrollbar : ImGuiWindowFlags_None;
- BeginChildEx(name, instance_id, outer_rect.GetSize(), ImGuiChildFlags_None, child_window_flags);
+ ImGuiChildFlags child_child_flags = (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasChildFlags) ? g.NextWindowData.ChildFlags : ImGuiChildFlags_None;
+ ImGuiWindowFlags child_window_flags = (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasWindowFlags) ? g.NextWindowData.WindowFlags : ImGuiWindowFlags_None;
+ if (flags & ImGuiTableFlags_ScrollX)
+ child_window_flags |= ImGuiWindowFlags_HorizontalScrollbar;
+ BeginChildEx(name, instance_id, outer_rect.GetSize(), child_child_flags, child_window_flags);
table->InnerWindow = g.CurrentWindow;
table->WorkRect = table->InnerWindow->WorkRect;
table->OuterRect = table->InnerWindow->Rect();
@@ -424,7 +437,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG
if (table->InnerWindow->SkipItems && outer_window_is_measuring_size)
table->InnerWindow->SkipItems = false;
- // When using multiple instances, ensure they have the same amount of horizontal decorations (aka vertical scrollbar) so stretched columns can be aligned)
+ // When using multiple instances, ensure they have the same amount of horizontal decorations (aka vertical scrollbar) so stretched columns can be aligned
if (instance_no == 0)
{
table->HasScrollbarYPrev = table->HasScrollbarYCurr;
@@ -438,6 +451,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG
// 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;
table->HasScrollbarYPrev = table->HasScrollbarYCurr = false;
+ table->InnerWindow->DC.TreeDepth++; // This is designed to always linking ImGuiTreeNodeFlags_DrawLines linking accross a table
}
// Push a standardized ID for both child-using and not-child-using tables
@@ -528,7 +542,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG
// Make table current
g.CurrentTable = table;
- outer_window->DC.NavIsScrollPushableX = false; // Shortcut for NavUpdateCurrentWindowIsScrollPushableX();
+ inner_window->DC.NavIsScrollPushableX = false; // Shortcut for NavUpdateCurrentWindowIsScrollPushableX();
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;
@@ -566,6 +580,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG
// Initialize
table->SettingsOffset = -1;
table->IsSortSpecsDirty = true;
+ table->IsSettingsDirty = true; // Records itself into .ini file even when in default state (#7934)
table->InstanceInteracted = -1;
table->ContextPopupColumn = -1;
table->ReorderColumn = table->ResizedColumn = table->LastResizedColumn = -1;
@@ -965,7 +980,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table)
// [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_removed = (table->HasScrollbarYPrev && !table->InnerWindow->ScrollbarY) ? g.Style.ScrollbarSize : 0.0f; // To synchronize decoration width of synched tables with mismatching scrollbar state (#5920)
+ const float width_removed = (table->HasScrollbarYPrev && !table->InnerWindow->ScrollbarY) ? g.Style.ScrollbarSize : 0.0f; // To synchronize decoration width of synced tables with mismatching scrollbar state (#5920)
const float width_avail = ImMax(1.0f, (((table->Flags & ImGuiTableFlags_ScrollX) && table->InnerWidth == 0.0f) ? table->InnerClipRect.GetWidth() : work_rect.GetWidth()) - width_removed);
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;
@@ -1044,7 +1059,8 @@ void ImGui::TableUpdateLayout(ImGuiTable* table)
const int column_n = table->DisplayOrderToIndex[order_n];
ImGuiTableColumn* column = &table->Columns[column_n];
- column->NavLayerCurrent = (ImS8)(table->FreezeRowsCount > 0 ? ImGuiNavLayer_Menu : ImGuiNavLayer_Main); // Use Count NOT request so Header line changes layer when frozen
+ // Initial nav layer: using FreezeRowsCount, NOT FreezeRowsRequest, so Header line changes layer when frozen
+ column->NavLayerCurrent = (ImS8)(table->FreezeRowsCount > 0 ? ImGuiNavLayer_Menu : (ImGuiNavLayer)table->NavLayer);
if (offset_x_frozen && table->FreezeColumnsCount == visible_n)
{
@@ -1235,7 +1251,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table)
// [Part 11] Default context menu
// - To append to this menu: you can call TableBeginContextMenuPopup()/.../EndPopup().
- // - To modify or replace this: set table->IsContextPopupNoDefaultContents = true, then call TableBeginContextMenuPopup()/.../EndPopup().
+ // - To modify or replace this: set table->DisableDefaultContextMenu = true, then call TableBeginContextMenuPopup()/.../EndPopup().
// - You may call TableDrawDefaultContextMenu() with selected flags to display specific sections of the default menu,
// e.g. TableDrawDefaultContextMenu(table, table->Flags & ~ImGuiTableFlags_Hideable) will display everything EXCEPT columns visibility options.
if (table->DisableDefaultContextMenu == false && TableBeginContextMenuPopup(table))
@@ -1331,7 +1347,11 @@ void ImGui::EndTable()
{
ImGuiContext& g = *GImGui;
ImGuiTable* table = g.CurrentTable;
- IM_ASSERT(table != NULL && "Only call EndTable() if BeginTable() returns true!");
+ if (table == NULL)
+ {
+ IM_ASSERT_USER_ERROR(table != NULL, "EndTable() call should only be done while in BeginTable() scope!");
+ return;
+ }
// 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)
@@ -1373,7 +1393,7 @@ void ImGui::EndTable()
// 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.
+ // but since the later is likely to be impossible to do we'd rather update both axes together.
if (table->Flags & ImGuiTableFlags_ScrollX)
{
const float outer_padding_for_border = (table->Flags & ImGuiTableFlags_BordersOuterV) ? TABLE_BORDER_SIZE : 0.0f;
@@ -1483,7 +1503,7 @@ void ImGui::EndTable()
if (inner_window != outer_window)
{
short backup_nav_layers_active_mask = inner_window->DC.NavLayersActiveMask;
- inner_window->DC.NavLayersActiveMask |= 1 << ImGuiNavLayer_Main; // So empty table don't appear to navigate differently.
+ inner_window->DC.NavLayersActiveMask |= 1 << table->NavLayer; // So empty table don't appear to navigate differently.
g.CurrentTable = NULL; // To avoid error recovery recursing
EndChild();
g.CurrentTable = table;
@@ -1491,6 +1511,7 @@ void ImGui::EndTable()
}
else
{
+ table->InnerWindow->DC.TreeDepth--;
ItemSize(table->OuterRect.GetSize());
ItemAdd(table->OuterRect, 0);
}
@@ -1548,14 +1569,43 @@ void ImGui::EndTable()
NavUpdateCurrentWindowIsScrollPushableX();
}
+// Called in TableSetupColumn() when initializing and in TableLoadSettings() for defaults before applying stored settings.
+// 'init_mask' specify which fields to initialize.
+static void TableInitColumnDefaults(ImGuiTable* table, ImGuiTableColumn* column, ImGuiTableColumnFlags init_mask)
+{
+ ImGuiTableColumnFlags flags = column->Flags;
+ if (init_mask & ImGuiTableFlags_Resizable)
+ {
+ float init_width_or_weight = column->InitStretchWeightOrWidth;
+ column->WidthRequest = ((flags & ImGuiTableColumnFlags_WidthFixed) && init_width_or_weight > 0.0f) ? init_width_or_weight : -1.0f;
+ column->StretchWeight = (init_width_or_weight > 0.0f && (flags & ImGuiTableColumnFlags_WidthStretch)) ? init_width_or_weight : -1.0f;
+ if (init_width_or_weight > 0.0f) // Disable auto-fit if an explicit width/weight has been specified
+ column->AutoFitQueue = 0x00;
+ }
+ if (init_mask & ImGuiTableFlags_Reorderable)
+ column->DisplayOrder = (ImGuiTableColumnIdx)table->Columns.index_from_ptr(column);
+ if (init_mask & ImGuiTableFlags_Hideable)
+ column->IsUserEnabled = column->IsUserEnabledNextFrame = (flags & ImGuiTableColumnFlags_DefaultHide) ? 0 : 1;
+ if (init_mask & ImGuiTableFlags_Sortable)
+ {
+ // Multiple columns using _DefaultSort will be reassigned unique SortOrder values when building the sort specs.
+ column->SortOrder = (flags & ImGuiTableColumnFlags_DefaultSort) ? 0 : -1;
+ column->SortDirection = (flags & ImGuiTableColumnFlags_DefaultSort) ? ((flags & ImGuiTableColumnFlags_PreferSortDescending) ? (ImS8)ImGuiSortDirection_Descending : (ImU8)(ImGuiSortDirection_Ascending)) : (ImS8)ImGuiSortDirection_None;
+ }
+}
+
// See "COLUMNS 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!");
+ if (table == NULL)
+ {
+ IM_ASSERT_USER_ERROR(table != NULL, "Call should only be done while in BeginTable() scope!");
+ return;
+ }
+ IM_ASSERT(table->IsLayoutLocked == false && "Need to call TableSetupColumn() before first row!");
IM_ASSERT((flags & ImGuiTableColumnFlags_StatusMask_) == 0 && "Illegal to pass StatusMask values to TableSetupColumn()");
if (table->DeclColumnsCount >= table->ColumnsCount)
{
@@ -1572,7 +1622,7 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, flo
IM_ASSERT(init_width_or_weight <= 0.0f && "Can only specify width/weight if sizing policy is set explicitly in either Table or Column.");
// When passing a width automatically enforce WidthFixed policy
- // (whereas TableSetupColumnFlags would default to WidthAuto if table is not Resizable)
+ // (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;
@@ -1590,27 +1640,10 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, flo
column->InitStretchWeightOrWidth = init_width_or_weight;
if (table->IsInitializing)
{
- // Init width or weight
+ ImGuiTableFlags init_flags = ~table->SettingsLoadedFlags;
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->IsUserEnabled = column->IsUserEnabledNextFrame = 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);
- }
+ init_flags |= ImGuiTableFlags_Resizable;
+ TableInitColumnDefaults(table, column, init_flags);
}
// Store name (append with zero-terminator in contiguous buffer)
@@ -1619,7 +1652,7 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, flo
if (label != NULL && label[0] != 0)
{
column->NameOffset = (ImS16)table->ColumnsNames.size();
- table->ColumnsNames.append(label, label + strlen(label) + 1);
+ table->ColumnsNames.append(label, label + ImStrlen(label) + 1);
}
}
@@ -1628,7 +1661,11 @@ void ImGui::TableSetupScrollFreeze(int columns, int rows)
{
ImGuiContext& g = *GImGui;
ImGuiTable* table = g.CurrentTable;
- IM_ASSERT(table != NULL && "Need to call TableSetupColumn() after BeginTable()!");
+ if (table == NULL)
+ {
+ IM_ASSERT_USER_ERROR(table != NULL, "Call should only be done while in BeginTable() scope!");
+ return;
+ }
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
@@ -1705,9 +1742,11 @@ void ImGui::TableSetColumnEnabled(int column_n, bool enabled)
{
ImGuiContext& g = *GImGui;
ImGuiTable* table = g.CurrentTable;
- IM_ASSERT(table != NULL);
- if (!table)
+ if (table == NULL)
+ {
+ IM_ASSERT_USER_ERROR(table != NULL, "Call should only be done while in BeginTable() scope!");
return;
+ }
IM_ASSERT(table->Flags & ImGuiTableFlags_Hideable); // See comments above
if (column_n < 0)
column_n = table->CurrentColumn;
@@ -1786,6 +1825,11 @@ void ImGui::TableSetBgColor(ImGuiTableBgTarget target, ImU32 color, int column_n
ImGuiContext& g = *GImGui;
ImGuiTable* table = g.CurrentTable;
IM_ASSERT(target != ImGuiTableBgTarget_None);
+ if (table == NULL)
+ {
+ IM_ASSERT_USER_ERROR(table != NULL, "Call should only be done while in BeginTable() scope!");
+ return;
+ }
if (color == IM_COL32_DISABLE)
color = 0;
@@ -1914,7 +1958,10 @@ void ImGui::TableEndRow(ImGuiTable* table)
IM_ASSERT(table->IsInsideRow);
if (table->CurrentColumn != -1)
+ {
TableEndCell(table);
+ table->CurrentColumn = -1;
+ }
// Logging
if (g.LogEnabled)
@@ -2007,12 +2054,13 @@ void ImGui::TableEndRow(ImGuiTable* table)
}
// 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.
+ // - 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)
{
+ IM_ASSERT(table->FreezeRowsRequest > 0);
for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
- table->Columns[column_n].NavLayerCurrent = ImGuiNavLayer_Main;
+ table->Columns[column_n].NavLayerCurrent = table->NavLayer;
const float y0 = ImMax(table->RowPosY2 + 1, table->InnerClipRect.Min.y);
table_instance->LastFrozenHeight = y0 - table->OuterRect.Min.y;
@@ -2079,7 +2127,11 @@ bool ImGui::TableSetColumnIndex(int column_n)
{
if (table->CurrentColumn != -1)
TableEndCell(table);
- IM_ASSERT(column_n >= 0 && table->ColumnsCount);
+ if ((column_n >= 0 && column_n < table->ColumnsCount) == false)
+ {
+ IM_ASSERT_USER_ERROR(column_n >= 0 && column_n < table->ColumnsCount, "TableSetColumnIndex() invalid column index!");
+ return false;
+ }
TableBeginCell(table, column_n);
}
@@ -2150,6 +2202,7 @@ void ImGui::TableBeginCell(ImGuiTable* table, int column_n)
g.LastItemData.StatusFlags = 0;
}
+ // Also see TablePushColumnChannel()
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.
@@ -2423,10 +2476,38 @@ 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, table->Columns[table->CurrentColumn].DrawChannelCurrent);
+}
+
+// Also see TableBeginCell()
+void ImGui::TablePushColumnChannel(int column_n)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiTable* table = g.CurrentTable;
+
+ // Optimization: avoid SetCurrentChannel() + PushClipRect()
+ if (table->Flags & ImGuiTableFlags_NoClip)
+ return;
+ ImGuiWindow* window = g.CurrentWindow;
+ const ImGuiTableColumn* column = &table->Columns[column_n];
+ SetWindowClipRectBeforeSetChannel(window, column->ClipRect);
+ table->DrawSplitter->SetCurrentChannel(window->DrawList, column->DrawChannelCurrent);
+}
+
+void ImGui::TablePopColumnChannel()
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiTable* table = g.CurrentTable;
+
+ // Optimization: avoid PopClipRect() + SetCurrentChannel()
+ if ((table->Flags & ImGuiTableFlags_NoClip) || (table->CurrentColumn == -1)) // Calling TreePop() after TableNextRow() is supported.
+ return;
+ ImGuiWindow* window = g.CurrentWindow;
+ const ImGuiTableColumn* column = &table->Columns[table->CurrentColumn];
+ SetWindowClipRectBeforeSetChannel(window, column->ClipRect);
table->DrawSplitter->SetCurrentChannel(window->DrawList, column->DrawChannelCurrent);
}
@@ -2801,9 +2882,7 @@ ImGuiTableSortSpecs* ImGui::TableGetSortSpecs()
{
ImGuiContext& g = *GImGui;
ImGuiTable* table = g.CurrentTable;
- IM_ASSERT(table != NULL);
-
- if (!(table->Flags & ImGuiTableFlags_Sortable))
+ if (table == NULL || !(table->Flags & ImGuiTableFlags_Sortable))
return NULL;
// Require layout (in case TableHeadersRow() hasn't been called) as it may alter IsSortSpecsDirty in some paths.
@@ -3028,7 +3107,11 @@ void ImGui::TableHeadersRow()
{
ImGuiContext& g = *GImGui;
ImGuiTable* table = g.CurrentTable;
- IM_ASSERT(table != NULL && "Need to call TableHeadersRow() after BeginTable()!");
+ if (table == NULL)
+ {
+ IM_ASSERT_USER_ERROR(table != NULL, "Call should only be done while in BeginTable() scope!");
+ return;
+ }
// Call layout if not already done. This is automatically done by TableNextRow: we do it here _only_ to make
// it easier to debug-step in TableUpdateLayout(). Your own version of this function doesn't need this.
@@ -3073,7 +3156,12 @@ void ImGui::TableHeader(const char* label)
return;
ImGuiTable* table = g.CurrentTable;
- IM_ASSERT(table != NULL && "Need to call TableHeader() after BeginTable()!");
+ if (table == NULL)
+ {
+ IM_ASSERT_USER_ERROR(table != NULL, "Call should only be done while in BeginTable() scope!");
+ return;
+ }
+
IM_ASSERT(table->CurrentColumn != -1);
const int column_n = table->CurrentColumn;
ImGuiTableColumn* column = &table->Columns[column_n];
@@ -3194,7 +3282,7 @@ void ImGui::TableHeader(const char* label)
// 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);
+ RenderTextEllipsis(window->DrawList, label_pos, ImVec2(ellipsis_max, bb.Max.y), ellipsis_max, label, label_end, &label_size);
const bool text_clipped = label_size.x > (ellipsis_max - label_pos.x);
if (text_clipped && hovered && g.ActiveId == 0)
@@ -3248,7 +3336,11 @@ void ImGui::TableAngledHeadersRowEx(ImGuiID row_id, float angle, float max_label
ImGuiTable* table = g.CurrentTable;
ImGuiWindow* window = g.CurrentWindow;
ImDrawList* draw_list = window->DrawList;
- IM_ASSERT(table != NULL && "Need to call TableHeadersRow() after BeginTable()!");
+ if (table == NULL)
+ {
+ IM_ASSERT_USER_ERROR(table != NULL, "Call should only be done while in BeginTable() scope!");
+ return;
+ }
IM_ASSERT(table->CurrentRow == -1 && "Must be first row");
if (max_label_width == 0.0f)
@@ -3287,13 +3379,13 @@ void ImGui::TableAngledHeadersRowEx(ImGuiID row_id, float angle, float max_label
ButtonBehavior(row_r, row_id, NULL, NULL);
KeepAliveID(row_id);
- const float ascent_scaled = g.Font->Ascent * g.FontScale; // FIXME: Standardize those scaling factors better
+ const float ascent_scaled = g.FontBaked->Ascent * g.FontBakedScale; // FIXME: Standardize those scaling factors better
const float line_off_for_ascent_x = (ImMax((g.FontSize - ascent_scaled) * 0.5f, 0.0f) / -sin_a) * (flip_label ? -1.0f : 1.0f);
const ImVec2 padding = g.Style.CellPadding; // We will always use swapped component
const ImVec2 align = g.Style.TableAngledHeadersTextAlign;
// Draw background and labels in first pass, then all borders.
- float max_x = 0.0f;
+ float max_x = -FLT_MAX;
for (int pass = 0; pass < 2; pass++)
for (int order_n = 0; order_n < data_count; order_n++)
{
@@ -3342,7 +3434,7 @@ void ImGui::TableAngledHeadersRowEx(ImGuiID row_id, float angle, float max_label
ImRect clip_r(window->ClipRect.Min, window->ClipRect.Min + ImVec2(clip_width, clip_height));
int vtx_idx_begin = draw_list->_VtxCurrentIdx;
PushStyleColor(ImGuiCol_Text, request->TextColor);
- RenderTextEllipsis(draw_list, clip_r.Min, clip_r.Max, clip_r.Max.x, clip_r.Max.x, label_name, label_name_eol, &label_size);
+ RenderTextEllipsis(draw_list, clip_r.Min, clip_r.Max, clip_r.Max.x, label_name, label_name_eol, &label_size);
PopStyleColor();
int vtx_idx_end = draw_list->_VtxCurrentIdx;
@@ -3679,6 +3771,14 @@ void ImGui::TableLoadSettings(ImGuiTable* table)
table->SettingsLoadedFlags = settings->SaveFlags;
table->RefScale = settings->RefScale;
+ // Initialize default columns settings
+ for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
+ {
+ ImGuiTableColumn* column = &table->Columns[column_n];
+ TableInitColumnDefaults(table, column, ~0);
+ column->AutoFitQueue = 0x00;
+ }
+
// Serialize ImGuiTableSettings/ImGuiTableColumnSettings into ImGuiTable/ImGuiTableColumn
ImGuiTableColumnSettings* column_settings = settings->GetColumnSettings();
ImU64 display_order_mask = 0;
@@ -3695,14 +3795,12 @@ void ImGui::TableLoadSettings(ImGuiTable* table)
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->IsUserEnabled = column->IsUserEnabledNextFrame = column_settings->IsEnabled;
+ if ((settings->SaveFlags & ImGuiTableFlags_Hideable) && column_settings->IsEnabled != -1)
+ column->IsUserEnabled = column->IsUserEnabledNextFrame = column_settings->IsEnabled == 1;
column->SortOrder = column_settings->SortOrder;
column->SortDirection = column_settings->SortDirection;
}
@@ -3798,8 +3896,7 @@ static void TableSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandle
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;
+ // We need to save the [Table] entry even if all the bools are false, since this records a table with "default settings".
buf->reserve(buf->size() + 30 + settings->ColumnsCount * 50); // ballpark reserve
buf->appendf("[%s][0x%08X,%d]\n", handler->TypeName, settings->ID, settings->ColumnsCount);
@@ -3846,7 +3943,7 @@ void ImGui::TableSettingsAddSettingsHandler()
// - TableGcCompactSettings() [Internal]
//-------------------------------------------------------------------------
-// Remove Table (currently only used by TestEngine)
+// Remove Table data (currently only used by TestEngine)
void ImGui::TableRemove(ImGuiTable* table)
{
//IMGUI_DEBUG_PRINT("TableRemove() id=0x%08X\n", table->ID);
diff --git a/source/code/Libs/imgui/imgui_widgets.cpp b/source/code/Libs/imgui/imgui_widgets.cpp index 5a29021..629dd0e 100644 --- a/source/code/Libs/imgui/imgui_widgets.cpp +++ b/source/code/Libs/imgui/imgui_widgets.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.4
+// dear imgui, v1.92.3
// (widgets code)
/*
@@ -70,6 +70,7 @@ Index of this file:
#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" // warning: format specifies type 'int' but the argument has type 'unsigned int'
#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 "-Wunused-macros" // warning: macro is not used // we define snprintf/vsnprintf on Windows so they are available, but not always used.
@@ -79,11 +80,18 @@ Index of this file:
#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
#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access
+#pragma clang diagnostic ignored "-Wnontrivial-memaccess" // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
+#pragma clang diagnostic ignored "-Wswitch-default" // warning: 'switch' missing 'default' label
#elif defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
+#pragma GCC diagnostic ignored "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe
+#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'int'/'void*', but argument X has type 'unsigned int'/'ImGuiWindow*'
#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 "-Wdeprecated-enum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated
+#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
+#pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when simplifying division / ..when changing X +- C1 cmp C2 to X cmp C2 -+ C1
+#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 "-Wcast-qual" // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers
#endif
//-------------------------------------------------------------------------
@@ -127,8 +135,7 @@ static const ImU64 IM_U64_MAX = (2ULL * 9223372036854775807LL + 1);
// For InputTextEx()
static bool InputTextFilterCharacter(ImGuiContext* ctx, unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data, bool input_source_is_clipboard = false);
-static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end);
-static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, const char* text_end, const char** remaining = NULL, ImVec2* out_offset = NULL, bool stop_on_new_line = false);
+static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, const char* text_end_display, const char* text_end, const char** out_remaining = NULL, ImVec2* out_offset = NULL, ImDrawTextFlags flags = 0);
//-------------------------------------------------------------------------
// [SECTION] Widgets: Text, etc.
@@ -163,7 +170,7 @@ void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags)
// Calculate length
const char* text_begin = text;
if (text_end == NULL)
- text_end = text + strlen(text); // FIXME-OPT
+ text_end = text + ImStrlen(text); // FIXME-OPT
const ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);
const float wrap_pos_x = window->DC.TextWrapPos;
@@ -203,7 +210,7 @@ void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags)
int lines_skipped = 0;
while (line < text_end && lines_skipped < lines_skippable)
{
- const char* line_end = (const char*)memchr(line, '\n', text_end - line);
+ const char* line_end = (const char*)ImMemchr(line, '\n', text_end - line);
if (!line_end)
line_end = text_end;
if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0)
@@ -224,7 +231,7 @@ void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags)
if (IsClippedEx(line_rect, 0))
break;
- const char* line_end = (const char*)memchr(line, '\n', text_end - line);
+ const char* line_end = (const char*)ImMemchr(line, '\n', text_end - line);
if (!line_end)
line_end = text_end;
text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x);
@@ -239,7 +246,7 @@ void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags)
int lines_skipped = 0;
while (line < text_end)
{
- const char* line_end = (const char*)memchr(line, '\n', text_end - line);
+ const char* line_end = (const char*)ImMemchr(line, '\n', text_end - line);
if (!line_end)
line_end = text_end;
if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0)
@@ -331,6 +338,46 @@ void ImGui::TextWrappedV(const char* fmt, va_list args)
PopTextWrapPos();
}
+void ImGui::TextAligned(float align_x, float size_x, const char* fmt, ...)
+{
+ va_list args;
+ va_start(args, fmt);
+ TextAlignedV(align_x, size_x, fmt, args);
+ va_end(args);
+}
+
+// align_x: 0.0f = left, 0.5f = center, 1.0f = right.
+// size_x : 0.0f = shortcut for GetContentRegionAvail().x
+// FIXME-WIP: Works but API is likely to be reworked. This is designed for 1 item on the line. (#7024)
+void ImGui::TextAlignedV(float align_x, float size_x, const char* fmt, va_list args)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ if (window->SkipItems)
+ return;
+
+ const char* text, *text_end;
+ ImFormatStringToTempBufferV(&text, &text_end, fmt, args);
+ const ImVec2 text_size = CalcTextSize(text, text_end);
+ size_x = CalcItemSize(ImVec2(size_x, 0.0f), 0.0f, text_size.y).x;
+
+ ImVec2 pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);
+ ImVec2 pos_max(pos.x + size_x, window->ClipRect.Max.y);
+ ImVec2 size(ImMin(size_x, text_size.x), text_size.y);
+ window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, pos.x + text_size.x);
+ window->DC.IdealMaxPos.x = ImMax(window->DC.IdealMaxPos.x, pos.x + text_size.x);
+ if (align_x > 0.0f && text_size.x < size_x)
+ pos.x += ImTrunc((size_x - text_size.x) * align_x);
+ RenderTextEllipsis(window->DrawList, pos, pos_max, pos_max.x, text, text_end, &text_size);
+
+ const ImVec2 backup_max_pos = window->DC.CursorMaxPos;
+ ItemSize(size);
+ ItemAdd(ImRect(pos, pos + size), 0);
+ window->DC.CursorMaxPos.x = backup_max_pos.x; // Cancel out extending content size because right-aligned text would otherwise mess it up.
+
+ if (size_x < text_size.x && IsItemHovered(ImGuiHoveredFlags_NoNavOverride | ImGuiHoveredFlags_AllowWhenDisabled | ImGuiHoveredFlags_ForTooltip))
+ SetTooltip("%.*s", (int)(text_end - text), text);
+}
+
void ImGui::LabelText(const char* label, const char* fmt, ...)
{
va_list args;
@@ -471,7 +518,7 @@ void ImGui::BulletTextV(const char* fmt, va_list args)
// - PressedOnDragDropHold can generally be associated with any flag.
// - PressedOnDoubleClick can be associated by PressedOnClickRelease/PressedOnRelease, in which case the second release event won't be reported.
//------------------------------------------------------------------------------------------------------------------------------------------------
-// The behavior of the return-value changes when ImGuiButtonFlags_Repeat is set:
+// The behavior of the return-value changes when ImGuiItemFlags_ButtonRepeat is set:
// Repeat+ Repeat+ Repeat+ Repeat+
// PressedOnClickRelease PressedOnClick PressedOnRelease PressedOnDoubleClick
//-------------------------------------------------------------------------------------------------------------------------------------------------
@@ -486,7 +533,7 @@ void ImGui::BulletTextV(const char* fmt, va_list args)
// And better standardize how widgets use 'GetColor32((held && hovered) ? ... : hovered ? ...)' vs 'GetColor32(held ? ... : hovered ? ...);'
// For mouse feedback we typically prefer the 'held && hovered' test, but for nav feedback not always. Outputting hovered=true on Activation may be misleading.
// - Since v1.91.2 (Sept 2024) we included io.ConfigDebugHighlightIdConflicts feature.
-// One idiom which was previously valid which will now emit a warning is when using multiple overlayed ButtonBehavior()
+// One idiom which was previously valid which will now emit a warning is when using multiple overlaid ButtonBehavior()
// with same ID and different MouseButton (see #8030). You can fix it by:
// (1) switching to use a single ButtonBehavior() with multiple _MouseButton flags.
// or (2) surrounding those calls with PushItemFlag(ImGuiItemFlags_AllowDuplicateId, true); ... PopItemFlag()
@@ -495,19 +542,21 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
+ // Default behavior inherited from item flags
+ // Note that _both_ ButtonFlags and ItemFlags are valid sources, so copy one into the item_flags and only check that.
+ ImGuiItemFlags item_flags = (g.LastItemData.ID == id ? g.LastItemData.ItemFlags : g.CurrentItemFlags);
+ if (flags & ImGuiButtonFlags_AllowOverlap)
+ item_flags |= ImGuiItemFlags_AllowOverlap;
+ if (item_flags & ImGuiItemFlags_NoFocus)
+ flags |= ImGuiButtonFlags_NoFocus | ImGuiButtonFlags_NoNavFocus;
+
// Default only reacts to left mouse button
if ((flags & ImGuiButtonFlags_MouseButtonMask_) == 0)
flags |= ImGuiButtonFlags_MouseButtonLeft;
// Default behavior requires click + release inside bounding box
if ((flags & ImGuiButtonFlags_PressedOnMask_) == 0)
- flags |= ImGuiButtonFlags_PressedOnDefault_;
-
- // Default behavior inherited from item flags
- // Note that _both_ ButtonFlags and ItemFlags are valid sources, so copy one into the item_flags and only check that.
- ImGuiItemFlags item_flags = (g.LastItemData.ID == id ? g.LastItemData.ItemFlags : g.CurrentItemFlags);
- if (flags & ImGuiButtonFlags_AllowOverlap)
- item_flags |= ImGuiItemFlags_AllowOverlap;
+ flags |= (item_flags & ImGuiItemFlags_ButtonRepeat) ? ImGuiButtonFlags_PressedOnClick : ImGuiButtonFlags_PressedOnDefault_;
ImGuiWindow* backup_hovered_window = g.HoveredWindow;
const bool flatten_hovered_children = (flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredWindow && g.HoveredWindow->RootWindowDockTree == window->RootWindowDockTree;
@@ -523,7 +572,8 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
bool pressed = false;
bool hovered = ItemHoverable(bb, id, item_flags);
- // Special mode for Drag and Drop where holding button pressed for a long time while dragging another item triggers the button
+ // Special mode for Drag and Drop used by openables (tree nodes, tabs etc.)
+ // where holding the button pressed for a long time while drag a payload item triggers the button.
if (g.DragDropActive && (flags & ImGuiButtonFlags_PressedOnDragDropHold) && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoHoldToOpenOthers))
if (IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
{
@@ -575,7 +625,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
SetFocusID(id, window);
FocusWindow(window);
}
- else
+ else if (!(flags & ImGuiButtonFlags_NoFocus))
{
FocusWindow(window, ImGuiFocusRequestFlags_RestoreFocusedChild); // Still need to focus and bring to front, but try to avoid losing NavId when navigating a child
}
@@ -593,7 +643,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
SetFocusID(id, window);
FocusWindow(window);
}
- else
+ else if (!(flags & ImGuiButtonFlags_NoFocus))
{
FocusWindow(window, ImGuiFocusRequestFlags_RestoreFocusedChild); // Still need to focus and bring to front, but try to avoid losing NavId when navigating a child
}
@@ -859,11 +909,12 @@ bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos)
if (hovered)
window->DrawList->AddRectFilled(bb.Min, bb.Max, bg_col);
RenderNavCursor(bb, id, ImGuiNavRenderCursorFlags_Compact);
- ImU32 cross_col = GetColorU32(ImGuiCol_Text);
- ImVec2 cross_center = bb.GetCenter() - ImVec2(0.5f, 0.5f);
- float cross_extent = g.FontSize * 0.5f * 0.7071f - 1.0f;
- window->DrawList->AddLine(cross_center + ImVec2(+cross_extent, +cross_extent), cross_center + ImVec2(-cross_extent, -cross_extent), cross_col, 1.0f);
- window->DrawList->AddLine(cross_center + ImVec2(+cross_extent, -cross_extent), cross_center + ImVec2(-cross_extent, +cross_extent), cross_col, 1.0f);
+ const ImU32 cross_col = GetColorU32(ImGuiCol_Text);
+ const ImVec2 cross_center = bb.GetCenter() - ImVec2(0.5f, 0.5f);
+ const float cross_extent = g.FontSize * 0.5f * 0.7071f - 1.0f;
+ const float cross_thickness = 1.0f; // FIXME-DPI
+ window->DrawList->AddLine(cross_center + ImVec2(+cross_extent, +cross_extent), cross_center + ImVec2(-cross_extent, -cross_extent), cross_col, cross_thickness);
+ window->DrawList->AddLine(cross_center + ImVec2(+cross_extent, -cross_extent), cross_center + ImVec2(-cross_extent, +cross_extent), cross_col, cross_thickness);
return pressed;
}
@@ -909,15 +960,17 @@ ImGuiID ImGui::GetWindowScrollbarID(ImGuiWindow* window, ImGuiAxis axis)
// Return scrollbar rectangle, must only be called for corresponding axis if window->ScrollbarX/Y is set.
ImRect ImGui::GetWindowScrollbarRect(ImGuiWindow* window, ImGuiAxis axis)
{
+ ImGuiContext& g = *GImGui;
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);
+ IM_ASSERT(scrollbar_size >= 0.0f);
+ const float border_size = IM_ROUND(window->WindowBorderSize * 0.5f);
+ const float border_top = (window->Flags & ImGuiWindowFlags_MenuBar) ? IM_ROUND(g.Style.FrameBorderSize * 0.5f) : 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 - border_size, outer_rect.Max.y - border_size);
+ return ImRect(inner_rect.Min.x + border_size, ImMax(outer_rect.Min.y + border_size, outer_rect.Max.y - border_size - scrollbar_size), inner_rect.Max.x - border_size, outer_rect.Max.y - border_size);
else
- return ImRect(ImMax(outer_rect.Min.x, outer_rect.Max.x - border_size - scrollbar_size), inner_rect.Min.y, outer_rect.Max.x - border_size, inner_rect.Max.y - border_size);
+ return ImRect(ImMax(outer_rect.Min.x, outer_rect.Max.x - border_size - scrollbar_size), inner_rect.Min.y + border_top, outer_rect.Max.x - border_size, inner_rect.Max.y - border_size);
}
void ImGui::Scrollbar(ImGuiAxis axis)
@@ -955,7 +1008,7 @@ void ImGui::Scrollbar(ImGuiAxis axis)
// - We store values as normalized ratio and in a form that allows the window content to change while we are holding on a scrollbar
// - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal.
// Still, the code should probably be made simpler..
-bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, ImS64* p_scroll_v, ImS64 size_visible_v, ImS64 size_contents_v, ImDrawFlags flags)
+bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, ImS64* p_scroll_v, ImS64 size_visible_v, ImS64 size_contents_v, ImDrawFlags draw_rounding_flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
@@ -969,8 +1022,8 @@ bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, ImS6
// 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));
+ if ((axis == ImGuiAxis_Y) && bb_frame_height < bb_frame_width)
+ alpha = ImSaturate(bb_frame_height / ImMax(bb_frame_width * 2.0f, 1.0f));
if (alpha <= 0.0f)
return false;
@@ -978,7 +1031,8 @@ bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, ImS6
const bool allow_interaction = (alpha >= 1.0f);
ImRect bb = bb_frame;
- bb.Expand(ImVec2(-ImClamp(IM_TRUNC((bb_frame_width - 2.0f) * 0.5f), 0.0f, 3.0f), -ImClamp(IM_TRUNC((bb_frame_height - 2.0f) * 0.5f), 0.0f, 3.0f)));
+ float padding = IM_TRUNC(ImMin(style.ScrollbarPadding, ImMin(bb_frame_width, bb_frame_height) * 0.5f));
+ bb.Expand(-padding);
// V denote the main, longer axis of the scrollbar (= height for a vertical scrollbar)
const float scrollbar_size_v = (axis == ImGuiAxis_X) ? bb.GetWidth() : bb.GetHeight();
@@ -987,7 +1041,8 @@ bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, ImS6
// But we maintain a minimum size in pixel to allow for the user to still aim inside.
IM_ASSERT(ImMax(size_contents_v, size_visible_v) > 0.0f); // Adding this assert to check if the ImMax(XXX,1.0f) is still needed. PLEASE CONTACT ME if this triggers.
const ImS64 win_size_v = ImMax(ImMax(size_contents_v, size_visible_v), (ImS64)1);
- const float grab_h_pixels = ImClamp(scrollbar_size_v * ((float)size_visible_v / (float)win_size_v), style.GrabMinSize, scrollbar_size_v);
+ const float grab_h_minsize = ImMin(bb.GetSize()[axis], style.GrabMinSize);
+ const float grab_h_pixels = ImClamp(scrollbar_size_v * ((float)size_visible_v / (float)win_size_v), grab_h_minsize, scrollbar_size_v);
const float grab_h_norm = grab_h_pixels / scrollbar_size_v;
// Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar().
@@ -1046,7 +1101,7 @@ bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, ImS6
// Render
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, flags);
+ window->DrawList->AddRectFilled(bb_frame.Min, bb_frame.Max, bg_col, window->WindowRounding, draw_rounding_flags);
ImRect grab_rect;
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);
@@ -1057,30 +1112,48 @@ bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, ImS6
return held;
}
-// - Read about ImTextureID here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples
+// - Read about ImTextureID/ImTextureRef here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples
// - 'uv0' and 'uv1' are texture coordinates. Read about them from the same link above.
-void ImGui::Image(ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col)
+void ImGui::ImageWithBg(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col)
{
+ ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
- const float border_size = (border_col.w > 0.0f) ? 1.0f : 0.0f;
- const ImVec2 padding(border_size, border_size);
+ const ImVec2 padding(g.Style.ImageBorderSize, g.Style.ImageBorderSize);
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + image_size + padding * 2.0f);
ItemSize(bb);
if (!ItemAdd(bb, 0))
return;
// Render
- if (border_size > 0.0f)
- window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(border_col), 0.0f, ImDrawFlags_None, border_size);
- window->DrawList->AddImage(user_texture_id, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col));
+ if (g.Style.ImageBorderSize > 0.0f)
+ window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border), 0.0f, ImDrawFlags_None, g.Style.ImageBorderSize);
+ if (bg_col.w > 0.0f)
+ window->DrawList->AddRectFilled(bb.Min + padding, bb.Max - padding, GetColorU32(bg_col));
+ window->DrawList->AddImage(tex_ref, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(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& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col, ImGuiButtonFlags flags)
+void ImGui::Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1)
+{
+ ImageWithBg(tex_ref, image_size, uv0, uv1);
+}
+
+// 1.91.9 (February 2025) removed 'tint_col' and 'border_col' parameters, made border size not depend on color value. (#8131, #8238)
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+void ImGui::Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col)
+{
+ ImGuiContext& g = *GImGui;
+ PushStyleVar(ImGuiStyleVar_ImageBorderSize, (border_col.w > 0.0f) ? ImMax(1.0f, g.Style.ImageBorderSize) : 0.0f); // Preserve legacy behavior where border is always visible when border_col's Alpha is >0.0f
+ PushStyleColor(ImGuiCol_Border, border_col);
+ ImageWithBg(tex_ref, image_size, uv0, uv1, ImVec4(0, 0, 0, 0), tint_col);
+ PopStyleColor();
+ PopStyleVar();
+}
+#endif
+
+bool ImGui::ImageButtonEx(ImGuiID id, ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col, ImGuiButtonFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
@@ -1102,25 +1175,26 @@ bool ImGui::ImageButtonEx(ImGuiID id, ImTextureID texture_id, const ImVec2& imag
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(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));
+ window->DrawList->AddImage(tex_ref, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col));
return pressed;
}
-// Note that ImageButton() adds style.FramePadding*2.0f to provided size. This is in order to facilitate fitting an image in a button.
-bool ImGui::ImageButton(const char* str_id, ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col)
+// - ImageButton() adds style.FramePadding*2.0f to provided size. This is in order to facilitate fitting an image in a button.
+// - ImageButton() draws a background based on regular Button() color + optionally an inner background if specified. (#8165) // FIXME: Maybe that's not the best design?
+bool ImGui::ImageButton(const char* str_id, ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return false;
- return ImageButtonEx(window->GetID(str_id), user_texture_id, image_size, uv0, uv1, bg_col, tint_col);
+ return ImageButtonEx(window->GetID(str_id), tex_ref, image_size, uv0, uv1, bg_col, tint_col);
}
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
// Legacy API obsoleted in 1.89. Two differences with new ImageButton()
-// - old ImageButton() used ImTextureId as item id (created issue with multiple buttons with same image, transient texture id values, opaque computation of ID)
+// - old ImageButton() used ImTextureID as item id (created issue with multiple buttons with same image, transient texture id values, opaque computation of ID)
// - new ImageButton() requires an explicit 'const char* str_id'
// - old ImageButton() had frame_padding' override argument.
// - new ImageButton() always use style.FramePadding.
@@ -1422,7 +1496,7 @@ bool ImGui::TextLink(const char* label)
const ImGuiID id = window->GetID(label);
const char* label_end = FindRenderedTextEnd(label);
- ImVec2 pos = window->DC.CursorPos;
+ ImVec2 pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);
ImVec2 size = CalcTextSize(label, label_end, true);
ImRect bb(pos, pos + size);
ItemSize(size, 0.0f);
@@ -1453,8 +1527,8 @@ bool ImGui::TextLink(const char* label)
ColorConvertHSVtoRGB(h, s, v, line_colf.x, line_colf.y, line_colf.z);
}
- float line_y = bb.Max.y + ImFloor(g.Font->Descent * g.FontScale * 0.20f);
- window->DrawList->AddLine(ImVec2(bb.Min.x, line_y), ImVec2(bb.Max.x, line_y), GetColorU32(line_colf)); // FIXME-TEXT: Underline mode.
+ float line_y = bb.Max.y + ImFloor(g.FontBaked->Descent * g.FontBakedScale * 0.20f);
+ window->DrawList->AddLine(ImVec2(bb.Min.x, line_y), ImVec2(bb.Max.x, line_y), GetColorU32(line_colf)); // FIXME-TEXT: Underline mode // FIXME-DPI
PushStyleColor(ImGuiCol_Text, GetColorU32(text_colf));
RenderText(bb.Min, label, label_end);
@@ -1464,14 +1538,14 @@ bool ImGui::TextLink(const char* label)
return pressed;
}
-void ImGui::TextLinkOpenURL(const char* label, const char* url)
+bool ImGui::TextLinkOpenURL(const char* label, const char* url)
{
ImGuiContext& g = *GImGui;
if (url == NULL)
url = label;
- if (TextLink(label))
- if (g.PlatformIO.Platform_OpenInShellFn != NULL)
- g.PlatformIO.Platform_OpenInShellFn(&g, url);
+ bool pressed = TextLink(label);
+ if (pressed && g.PlatformIO.Platform_OpenInShellFn != NULL)
+ g.PlatformIO.Platform_OpenInShellFn(&g, url);
SetItemTooltip(LocalizeGetMsg(ImGuiLocKey_OpenLink_s), url); // It is more reassuring for user to _always_ display URL when we same as label
if (BeginPopupContextItem())
{
@@ -1479,6 +1553,7 @@ void ImGui::TextLinkOpenURL(const char* label, const char* url)
SetClipboardText(url);
EndPopup();
}
+ return pressed;
}
//-------------------------------------------------------------------------
@@ -1665,7 +1740,7 @@ void ImGui::SeparatorTextEx(ImGuiID id, const char* label, const char* label_end
window->DrawList->AddLine(ImVec2(sep2_x1, seps_y), ImVec2(sep2_x2, seps_y), separator_col, separator_thickness);
if (g.LogEnabled)
LogSetNextTextDecoration("---", NULL);
- RenderTextEllipsis(window->DrawList, label_pos, ImVec2(bb.Max.x, bb.Max.y + style.ItemSpacing.y), bb.Max.x, bb.Max.x, label, label_end, &label_size);
+ RenderTextEllipsis(window->DrawList, label_pos, ImVec2(bb.Max.x, bb.Max.y + style.ItemSpacing.y), bb.Max.x, label, label_end, &label_size);
}
else
{
@@ -1761,27 +1836,31 @@ 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)
+void ImGui::ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess, float width_min)
{
if (count == 1)
{
if (items[0].Width >= 0.0f)
- items[0].Width = ImMax(items[0].Width - width_excess, 1.0f);
+ items[0].Width = ImMax(items[0].Width - width_excess, width_min);
return;
}
- ImQsort(items, (size_t)count, sizeof(ImGuiShrinkWidthItem), ShrinkWidthItemComparer);
+ ImQsort(items, (size_t)count, sizeof(ImGuiShrinkWidthItem), ShrinkWidthItemComparer); // Sort largest first, smallest last.
int count_same_width = 1;
- while (width_excess > 0.0f && count_same_width < count)
+ while (width_excess > 0.001f && count_same_width < count)
{
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[count_same_width].Width >= 0.0f) ? (items[0].Width - items[count_same_width].Width) : (items[0].Width - 1.0f);
+ max_width_to_remove_per_item = ImMin(items[0].Width - width_min, max_width_to_remove_per_item);
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);
+ float base_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;
- width_excess -= width_to_remove_per_item * count_same_width;
+ {
+ float width_to_remove_for_this_item = ImMin(base_width_to_remove_per_item, items[item_n].Width - width_min);
+ items[item_n].Width -= width_to_remove_for_this_item;
+ width_excess -= width_to_remove_for_this_item;
+ }
}
// Round width and redistribute remainder
@@ -1827,7 +1906,7 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
- ImGuiNextWindowDataFlags backup_next_window_data_flags = g.NextWindowData.Flags;
+ ImGuiNextWindowDataFlags backup_next_window_data_flags = g.NextWindowData.HasFlags;
g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
if (window->SkipItems)
return false;
@@ -1896,7 +1975,7 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF
if (!popup_open)
return false;
- g.NextWindowData.Flags = backup_next_window_data_flags;
+ g.NextWindowData.HasFlags = backup_next_window_data_flags;
return BeginComboPopup(popup_id, bb, flags);
}
@@ -1911,7 +1990,7 @@ bool ImGui::BeginComboPopup(ImGuiID popup_id, const ImRect& bb, ImGuiComboFlags
// Set popup size
float w = bb.GetWidth();
- if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
+ if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSizeConstraint)
{
g.NextWindowData.SizeConstraintRect.Min.x = ImMax(g.NextWindowData.SizeConstraintRect.Min.x, w);
}
@@ -1925,9 +2004,9 @@ bool ImGui::BeginComboPopup(ImGuiID popup_id, const ImRect& bb, ImGuiComboFlags
else if (flags & ImGuiComboFlags_HeightSmall) popup_max_height_in_items = 4;
else if (flags & ImGuiComboFlags_HeightLarge) popup_max_height_in_items = 20;
ImVec2 constraint_min(0.0f, 0.0f), constraint_max(FLT_MAX, FLT_MAX);
- if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) == 0 || g.NextWindowData.SizeVal.x <= 0.0f) // Don't apply constraints if user specified a size
+ if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) == 0 || g.NextWindowData.SizeVal.x <= 0.0f) // Don't apply constraints if user specified a size
constraint_min.x = w;
- if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) == 0 || g.NextWindowData.SizeVal.y <= 0.0f)
+ if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) == 0 || g.NextWindowData.SizeVal.y <= 0.0f)
constraint_max.y = CalcMaxPopupHeightFromItemCount(popup_max_height_in_items);
SetNextWindowSizeConstraints(constraint_min, constraint_max);
}
@@ -1958,7 +2037,8 @@ bool ImGui::BeginComboPopup(ImGuiID popup_id, const ImRect& bb, ImGuiComboFlags
if (!ret)
{
EndPopup();
- IM_ASSERT(0); // This should never happen as we tested for IsPopupOpen() above
+ if (!g.IO.ConfigDebugBeginReturnValueOnce && !g.IO.ConfigDebugBeginReturnValueLoop) // Begin may only return false with those debug tools activated.
+ IM_ASSERT(0); // This should never happen as we tested for IsPopupOpen() above
return false;
}
g.BeginComboDepth++;
@@ -2042,7 +2122,7 @@ static const char* Items_SingleStringGetter(void* data, int idx)
{
if (idx == items_count)
break;
- p += strlen(p) + 1;
+ p += ImStrlen(p) + 1;
items_count++;
}
return *p ? p : NULL;
@@ -2059,7 +2139,7 @@ bool ImGui::Combo(const char* label, int* current_item, const char* (*getter)(vo
preview_value = getter(user_data, *current_item);
// 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))
+ if (popup_max_height_in_items != -1 && !(g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSizeConstraint))
SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items)));
if (!BeginCombo(label, preview_value, ImGuiComboFlags_None))
@@ -2110,7 +2190,7 @@ bool ImGui::Combo(const char* label, int* current_item, const char* items_separa
const char* p = items_separated_by_zeros; // FIXME-OPT: Avoid computing this, or at least only when combo is open
while (*p)
{
- p += strlen(p) + 1;
+ p += ImStrlen(p) + 1;
items_count++;
}
bool value_changed = Combo(label, current_item, Items_SingleStringGetter, (void*)items_separated_by_zeros, items_count, height_in_items);
@@ -2172,6 +2252,7 @@ static const ImGuiDataTypeInfo GDataTypeInfo[] =
{ sizeof(float), "float", "%.3f","%f" }, // ImGuiDataType_Float (float are promoted to double in va_arg)
{ sizeof(double), "double","%f", "%lf" }, // ImGuiDataType_Double
{ sizeof(bool), "bool", "%d", "%d" }, // ImGuiDataType_Bool
+ { 0, "char*","%s", "%s" }, // ImGuiDataType_String
};
IM_STATIC_ASSERT(IM_ARRAYSIZE(GDataTypeInfo) == ImGuiDataType_COUNT);
@@ -2440,9 +2521,9 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const
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)
+ if (g.IO.KeyAlt && !(flags & ImGuiSliderFlags_NoSpeedTweaks))
adjust_delta *= 1.0f / 100.0f;
- if (g.IO.KeyShift)
+ if (g.IO.KeyShift && !(flags & ImGuiSliderFlags_NoSpeedTweaks))
adjust_delta *= 10.0f;
}
else if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
@@ -2450,7 +2531,7 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const
const int decimal_precision = is_floating_point ? ImParseFormatPrecision(format, 3) : 0;
const bool tweak_slow = IsKeyDown((g.NavInputSource == ImGuiInputSource_Gamepad) ? ImGuiKey_NavGamepadTweakSlow : ImGuiKey_NavKeyboardTweakSlow);
const bool tweak_fast = IsKeyDown((g.NavInputSource == ImGuiInputSource_Gamepad) ? ImGuiKey_NavGamepadTweakFast : ImGuiKey_NavKeyboardTweakFast);
- const float tweak_factor = tweak_slow ? 1.0f / 10.0f : tweak_fast ? 10.0f : 1.0f;
+ const float tweak_factor = (flags & ImGuiSliderFlags_NoSpeedTweaks) ? 1.0f : tweak_slow ? 1.0f / 10.0f : tweak_fast ? 10.0f : 1.0f;
adjust_delta = GetNavTweakPressedAmount(axis) * tweak_factor;
v_speed = ImMax(v_speed, GetMinimumStepAtDecimalPrecision(decimal_precision));
}
@@ -2619,7 +2700,7 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data,
bool temp_input_is_active = temp_input_allowed && TempInputIsActive(id);
if (!temp_input_is_active)
{
- // Tabbing or CTRL-clicking on Drag turns it into an InputText
+ // Tabbing or CTRL+click on Drag turns it into an InputText
const bool clicked = hovered && IsMouseClicked(0, ImGuiInputFlags_None, id);
const bool double_clicked = (hovered && g.IO.MouseClickedCount[0] == 2 && TestKeyOwner(ImGuiKey_MouseLeft, id));
const bool make_active = (clicked || double_clicked || g.NavActivateId == id);
@@ -2638,6 +2719,10 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data,
temp_input_is_active = true;
}
+ // Store initial value (not used by main lib but available as a convenience but some mods e.g. to revert)
+ if (make_active)
+ memcpy(&g.ActiveIdValueOnActivation, p_data, DataTypeGetInfo(data_type)->Size);
+
if (make_active && !temp_input_is_active)
{
SetActiveID(id, window);
@@ -3219,7 +3304,7 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat
bool temp_input_is_active = temp_input_allowed && TempInputIsActive(id);
if (!temp_input_is_active)
{
- // Tabbing or CTRL-clicking on Slider turns it into an input box
+ // Tabbing or CTRL+click on Slider turns it into an input box
const bool clicked = hovered && IsMouseClicked(0, ImGuiInputFlags_None, id);
const bool make_active = (clicked || g.NavActivateId == id);
if (make_active && clicked)
@@ -3228,6 +3313,10 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat
if ((clicked && g.IO.KeyCtrl) || (g.NavActivateId == id && (g.NavActivateFlags & ImGuiActivateFlags_PreferInput)))
temp_input_is_active = true;
+ // Store initial value (not used by main lib but available as a convenience but some mods e.g. to revert)
+ if (make_active)
+ memcpy(&g.ActiveIdValueOnActivation, p_data, DataTypeGetInfo(data_type)->Size);
+
if (make_active && !temp_input_is_active)
{
SetActiveID(id, window);
@@ -3335,7 +3424,8 @@ bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, fl
format = "%.0f deg";
float v_deg = (*v_rad) * 360.0f / (2 * IM_PI);
bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, format, flags);
- *v_rad = v_deg * (2 * IM_PI) / 360.0f;
+ if (value_changed)
+ *v_rad = v_deg * (2 * IM_PI) / 360.0f;
return value_changed;
}
@@ -3827,9 +3917,6 @@ bool ImGui::InputDouble(const char* label, double* v, double step, double step_f
// - InputText()
// - InputTextWithHint()
// - InputTextMultiline()
-// - InputTextGetCharInfo() [Internal]
-// - InputTextReindexLines() [Internal]
-// - InputTextReindexLinesRange() [Internal]
// - InputTextEx() [Internal]
// - DebugNodeInputTextState() [Internal]
//-------------------------------------------------------------------------
@@ -3856,75 +3943,11 @@ bool ImGui::InputTextWithHint(const char* label, const char* hint, char* buf, si
return InputTextEx(label, hint, buf, (int)buf_size, ImVec2(0, 0), flags, callback, user_data);
}
-// This is only used in the path where the multiline widget is inactivate.
-static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end)
-{
- int line_count = 0;
- const char* s = text_begin;
- while (true)
- {
- const char* s_eol = strchr(s, '\n');
- line_count++;
- if (s_eol == NULL)
- {
- s = s + strlen(s);
- break;
- }
- s = s_eol + 1;
- }
- *out_text_end = s;
- return line_count;
-}
-
-// FIXME: Ideally we'd share code with ImFont::CalcTextSizeA()
-static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, const char* text_end, const char** remaining, ImVec2* out_offset, bool stop_on_new_line)
+static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, const char* text_end_display, const char* text_end, const char** out_remaining, ImVec2* out_offset, ImDrawTextFlags flags)
{
ImGuiContext& g = *ctx;
- ImFont* font = g.Font;
- const float line_height = g.FontSize;
- const float scale = line_height / font->FontSize;
-
- ImVec2 text_size = ImVec2(0, 0);
- float line_width = 0.0f;
-
- const char* s = text_begin;
- while (s < text_end)
- {
- unsigned int c = (unsigned int)*s;
- if (c < 0x80)
- s += 1;
- else
- s += ImTextCharFromUtf8(&c, s, text_end);
-
- if (c == '\n')
- {
- text_size.x = ImMax(text_size.x, line_width);
- text_size.y += line_height;
- line_width = 0.0f;
- if (stop_on_new_line)
- break;
- continue;
- }
- if (c == '\r')
- continue;
-
- const float char_width = ((int)c < font->IndexAdvanceX.Size ? font->IndexAdvanceX.Data[c] : font->FallbackAdvanceX) * scale;
- line_width += char_width;
- }
-
- if (text_size.x < line_width)
- text_size.x = line_width;
-
- if (out_offset)
- *out_offset = ImVec2(line_width, text_size.y + line_height); // offset allow for the possibility of sitting after a trailing \n
-
- if (line_width > 0 || text_size.y == 0.0f) // whereas size.y will ignore the trailing \n
- text_size.y += line_height;
-
- if (remaining)
- *remaining = s;
-
- return text_size;
+ ImGuiInputTextState* obj = &g.InputTextState;
+ return ImFontCalcTextSizeEx(g.Font, g.FontSize, FLT_MAX, obj->WrapWidth, text_begin, text_end_display, text_end, out_remaining, out_offset, flags);
}
// Wrapper for stb_textedit.h to edit text (our wrapper is for: statically sized buffer, single-line, wchar characters. InputText converts between UTF-8 and wchar)
@@ -3934,15 +3957,15 @@ static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, c
// - ...but we don't use that feature.
namespace ImStb
{
-static int STB_TEXTEDIT_STRINGLEN(const ImGuiInputTextState* obj) { return obj->CurLenA; }
-static char STB_TEXTEDIT_GETCHAR(const ImGuiInputTextState* obj, int idx) { IM_ASSERT(idx <= obj->CurLenA); return obj->TextA[idx]; }
-static float STB_TEXTEDIT_GETWIDTH(ImGuiInputTextState* obj, int line_start_idx, int char_idx) { unsigned int c; ImTextCharFromUtf8(&c, obj->TextA.Data + line_start_idx + char_idx, obj->TextA.Data + obj->TextA.Size); if ((ImWchar)c == '\n') return IMSTB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *obj->Ctx; return g.Font->GetCharAdvance((ImWchar)c) * g.FontScale; }
+static int STB_TEXTEDIT_STRINGLEN(const ImGuiInputTextState* obj) { return obj->TextLen; }
+static char STB_TEXTEDIT_GETCHAR(const ImGuiInputTextState* obj, int idx) { IM_ASSERT(idx >= 0 && idx <= obj->TextLen); return obj->TextSrc[idx]; }
+static float STB_TEXTEDIT_GETWIDTH(ImGuiInputTextState* obj, int line_start_idx, int char_idx) { unsigned int c; ImTextCharFromUtf8(&c, obj->TextSrc + line_start_idx + char_idx, obj->TextSrc + obj->TextLen); if ((ImWchar)c == '\n') return IMSTB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *obj->Ctx; return g.FontBaked->GetCharAdvance((ImWchar)c) * g.FontBakedScale; }
static char STB_TEXTEDIT_NEWLINE = '\n';
static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, ImGuiInputTextState* obj, int line_start_idx)
{
- const char* text = obj->TextA.Data;
+ const char* text = obj->TextSrc;
const char* text_remaining = NULL;
- const ImVec2 size = InputTextCalcTextSize(obj->Ctx, text + line_start_idx, text + obj->CurLenA, &text_remaining, NULL, true);
+ const ImVec2 size = InputTextCalcTextSize(obj->Ctx, text + line_start_idx, text + obj->TextLen, text + obj->TextLen, &text_remaining, NULL, ImDrawTextFlags_StopOnNewLine | ImDrawTextFlags_WrapKeepBlanks);
r->x0 = 0.0f;
r->x1 = size.x;
r->baseline_y_delta = size.y;
@@ -3956,18 +3979,18 @@ static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, ImGuiInputTextState* ob
static int IMSTB_TEXTEDIT_GETNEXTCHARINDEX_IMPL(ImGuiInputTextState* obj, int idx)
{
- if (idx >= obj->CurLenA)
- return obj->CurLenA + 1;
+ if (idx >= obj->TextLen)
+ return obj->TextLen + 1;
unsigned int c;
- return idx + ImTextCharFromUtf8(&c, obj->TextA.Data + idx, obj->TextA.Data + obj->TextA.Size);
+ return idx + ImTextCharFromUtf8(&c, obj->TextSrc + idx, obj->TextSrc + obj->TextLen);
}
static int IMSTB_TEXTEDIT_GETPREVCHARINDEX_IMPL(ImGuiInputTextState* obj, int idx)
{
if (idx <= 0)
return -1;
- const char* p = ImTextFindPreviousUtf8Codepoint(obj->TextA.Data, obj->TextA.Data + idx);
- return (int)(p - obj->TextA.Data);
+ const char* p = ImTextFindPreviousUtf8Codepoint(obj->TextSrc, obj->TextSrc + idx);
+ return (int)(p - obj->TextSrc);
}
static bool ImCharIsSeparatorW(unsigned int c)
@@ -3990,10 +4013,10 @@ static int is_word_boundary_from_right(ImGuiInputTextState* obj, int idx)
if ((obj->Flags & ImGuiInputTextFlags_Password) || idx <= 0)
return 0;
- const char* curr_p = obj->TextA.Data + idx;
- const char* prev_p = ImTextFindPreviousUtf8Codepoint(obj->TextA.Data, curr_p);
- unsigned int curr_c; ImTextCharFromUtf8(&curr_c, curr_p, obj->TextA.Data + obj->TextA.Size);
- unsigned int prev_c; ImTextCharFromUtf8(&prev_c, prev_p, obj->TextA.Data + obj->TextA.Size);
+ const char* curr_p = obj->TextSrc + idx;
+ const char* prev_p = ImTextFindPreviousUtf8Codepoint(obj->TextSrc, curr_p);
+ unsigned int curr_c; ImTextCharFromUtf8(&curr_c, curr_p, obj->TextSrc + obj->TextLen);
+ unsigned int prev_c; ImTextCharFromUtf8(&prev_c, prev_p, obj->TextSrc + obj->TextLen);
bool prev_white = ImCharIsBlankW(prev_c);
bool prev_separ = ImCharIsSeparatorW(prev_c);
@@ -4006,10 +4029,10 @@ static int is_word_boundary_from_left(ImGuiInputTextState* obj, int idx)
if ((obj->Flags & ImGuiInputTextFlags_Password) || idx <= 0)
return 0;
- const char* curr_p = obj->TextA.Data + idx;
- const char* prev_p = ImTextFindPreviousUtf8Codepoint(obj->TextA.Data, curr_p);
- unsigned int prev_c; ImTextCharFromUtf8(&prev_c, curr_p, obj->TextA.Data + obj->TextA.Size);
- unsigned int curr_c; ImTextCharFromUtf8(&curr_c, prev_p, obj->TextA.Data + obj->TextA.Size);
+ const char* curr_p = obj->TextSrc + idx;
+ const char* prev_p = ImTextFindPreviousUtf8Codepoint(obj->TextSrc, curr_p);
+ unsigned int prev_c; ImTextCharFromUtf8(&prev_c, curr_p, obj->TextSrc + obj->TextLen);
+ unsigned int curr_c; ImTextCharFromUtf8(&curr_c, prev_p, obj->TextSrc + obj->TextLen);
bool prev_white = ImCharIsBlankW(prev_c);
bool prev_separ = ImCharIsSeparatorW(prev_c);
@@ -4026,7 +4049,7 @@ static int STB_TEXTEDIT_MOVEWORDLEFT_IMPL(ImGuiInputTextState* obj, int idx)
}
static int STB_TEXTEDIT_MOVEWORDRIGHT_MAC(ImGuiInputTextState* obj, int idx)
{
- int len = obj->CurLenA;
+ int len = obj->TextLen;
idx = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx);
while (idx < len && !is_word_boundary_from_left(obj, idx))
idx = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx);
@@ -4035,7 +4058,7 @@ static int STB_TEXTEDIT_MOVEWORDRIGHT_MAC(ImGuiInputTextState* obj, int idx)
static int STB_TEXTEDIT_MOVEWORDRIGHT_WIN(ImGuiInputTextState* obj, int idx)
{
idx = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx);
- int len = obj->CurLenA;
+ int len = obj->TextLen;
while (idx < len && !is_word_boundary_from_right(obj, idx))
idx = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx);
return idx > len ? len : idx;
@@ -4044,35 +4067,103 @@ static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(ImGuiInputTextState* obj, int idx)
#define STB_TEXTEDIT_MOVEWORDLEFT STB_TEXTEDIT_MOVEWORDLEFT_IMPL // They need to be #define for stb_textedit.h
#define STB_TEXTEDIT_MOVEWORDRIGHT STB_TEXTEDIT_MOVEWORDRIGHT_IMPL
+// Reimplementation of stb_textedit_move_line_start()/stb_textedit_move_line_end() which supports word-wrapping.
+static int STB_TEXTEDIT_MOVELINESTART_IMPL(ImGuiInputTextState* obj, ImStb::STB_TexteditState* state, int cursor)
+{
+ if (state->single_line)
+ return 0;
+
+ if (obj->WrapWidth > 0.0f)
+ {
+ ImGuiContext& g = *obj->Ctx;
+ const char* p_cursor = obj->TextSrc + cursor;
+ const char* p_bol = ImStrbol(p_cursor, obj->TextSrc);
+ const char* p = p_bol;
+ const char* text_end = obj->TextSrc + obj->TextLen; // End of line would be enough
+ while (p >= p_bol)
+ {
+ const char* p_eol = ImFontCalcWordWrapPositionEx(g.Font, g.FontSize, p, text_end, obj->WrapWidth, ImDrawTextFlags_WrapKeepBlanks);
+ if (p == p_cursor) // If we are already on a visible beginning-of-line, return real beginning-of-line (would be same as regular handler below)
+ return (int)(p_bol - obj->TextSrc);
+ if (p_eol == p_cursor && obj->TextA[cursor] != '\n' && obj->LastMoveDirectionLR == ImGuiDir_Left)
+ return (int)(p_bol - obj->TextSrc);
+ if (p_eol >= p_cursor)
+ return (int)(p - obj->TextSrc);
+ p = (*p_eol == '\n') ? p_eol + 1 : p_eol;
+ }
+ }
+
+ // Regular handler, same as stb_textedit_move_line_start()
+ while (cursor > 0)
+ {
+ int prev_cursor = IMSTB_TEXTEDIT_GETPREVCHARINDEX(obj, cursor);
+ if (STB_TEXTEDIT_GETCHAR(obj, prev_cursor) == STB_TEXTEDIT_NEWLINE)
+ break;
+ cursor = prev_cursor;
+ }
+ return cursor;
+}
+
+static int STB_TEXTEDIT_MOVELINEEND_IMPL(ImGuiInputTextState* obj, ImStb::STB_TexteditState* state, int cursor)
+{
+ int n = STB_TEXTEDIT_STRINGLEN(obj);
+ if (state->single_line)
+ return n;
+
+ if (obj->WrapWidth > 0.0f)
+ {
+ ImGuiContext& g = *obj->Ctx;
+ const char* p_cursor = obj->TextSrc + cursor;
+ const char* p = ImStrbol(p_cursor, obj->TextSrc);
+ const char* text_end = obj->TextSrc + obj->TextLen; // End of line would be enough
+ while (p < text_end)
+ {
+ const char* p_eol = ImFontCalcWordWrapPositionEx(g.Font, g.FontSize, p, text_end, obj->WrapWidth, ImDrawTextFlags_WrapKeepBlanks);
+ cursor = (int)(p_eol - obj->TextSrc);
+ if (p_eol == p_cursor && obj->LastMoveDirectionLR != ImGuiDir_Left) // If we are already on a visible end-of-line, switch to regular handle
+ break;
+ if (p_eol > p_cursor)
+ return cursor;
+ p = (*p_eol == '\n') ? p_eol + 1 : p_eol;
+ }
+ }
+ // Regular handler, same as stb_textedit_move_line_end()
+ while (cursor < n && STB_TEXTEDIT_GETCHAR(obj, cursor) != STB_TEXTEDIT_NEWLINE)
+ cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, cursor);
+ return cursor;
+}
+
+#define STB_TEXTEDIT_MOVELINESTART STB_TEXTEDIT_MOVELINESTART_IMPL
+#define STB_TEXTEDIT_MOVELINEEND STB_TEXTEDIT_MOVELINEEND_IMPL
+
static void STB_TEXTEDIT_DELETECHARS(ImGuiInputTextState* obj, int pos, int n)
{
+ // Offset remaining text (+ copy zero terminator)
+ IM_ASSERT(obj->TextSrc == obj->TextA.Data);
char* dst = obj->TextA.Data + pos;
-
+ char* src = obj->TextA.Data + pos + n;
+ memmove(dst, src, obj->TextLen - n - pos + 1);
obj->Edited = true;
- obj->CurLenA -= n;
-
- // Offset remaining text (FIXME-OPT: Use memmove)
- const char* src = obj->TextA.Data + pos + n;
- while (char c = *src++)
- *dst++ = c;
- *dst = '\0';
+ obj->TextLen -= n;
}
static bool STB_TEXTEDIT_INSERTCHARS(ImGuiInputTextState* obj, int pos, const char* new_text, int new_text_len)
{
const bool is_resizable = (obj->Flags & ImGuiInputTextFlags_CallbackResize) != 0;
- const int text_len = obj->CurLenA;
+ const int text_len = obj->TextLen;
IM_ASSERT(pos <= text_len);
- if (!is_resizable && (new_text_len + obj->CurLenA + 1 > obj->BufCapacityA))
+ if (!is_resizable && (new_text_len + obj->TextLen + 1 > obj->BufCapacity))
return false;
// Grow internal buffer if needed
+ IM_ASSERT(obj->TextSrc == obj->TextA.Data);
if (new_text_len + text_len + 1 > obj->TextA.Size)
{
if (!is_resizable)
return false;
obj->TextA.resize(text_len + ImClamp(new_text_len, 32, ImMax(256, new_text_len)) + 1);
+ obj->TextSrc = obj->TextA.Data;
}
char* text = obj->TextA.Data;
@@ -4081,8 +4172,8 @@ static bool STB_TEXTEDIT_INSERTCHARS(ImGuiInputTextState* obj, int pos, const ch
memcpy(text + pos, new_text, (size_t)new_text_len);
obj->Edited = true;
- obj->CurLenA += new_text_len;
- obj->TextA[obj->CurLenA] = '\0';
+ obj->TextLen += new_text_len;
+ obj->TextA[obj->TextLen] = '\0';
return true;
}
@@ -4114,8 +4205,8 @@ static bool STB_TEXTEDIT_INSERTCHARS(ImGuiInputTextState* obj, int pos, const ch
// the stb_textedit_paste() function creates two separate records, so we perform it manually. (FIXME: Report to nothings/stb?)
static void stb_textedit_replace(ImGuiInputTextState* str, STB_TexteditState* state, const IMSTB_TEXTEDIT_CHARTYPE* text, int text_len)
{
- stb_text_makeundo_replace(str, state, 0, str->CurLenA, text_len);
- ImStb::STB_TEXTEDIT_DELETECHARS(str, 0, str->CurLenA);
+ stb_text_makeundo_replace(str, state, 0, str->TextLen, text_len);
+ ImStb::STB_TEXTEDIT_DELETECHARS(str, 0, str->TextLen);
state->cursor = state->select_start = state->select_end = 0;
if (text_len <= 0)
return;
@@ -4148,6 +4239,11 @@ void ImGuiInputTextState::OnKeyPressed(int key)
stb_textedit_key(this, Stb, key);
CursorFollow = true;
CursorAnimReset();
+ const int key_u = (key & ~STB_TEXTEDIT_K_SHIFT);
+ if (key_u == STB_TEXTEDIT_K_LEFT || key_u == STB_TEXTEDIT_K_LINESTART || key_u == STB_TEXTEDIT_K_TEXTSTART || key_u == STB_TEXTEDIT_K_BACKSPACE || key_u == STB_TEXTEDIT_K_WORDLEFT)
+ LastMoveDirectionLR = ImGuiDir_Left;
+ else if (key_u == STB_TEXTEDIT_K_RIGHT || key_u == STB_TEXTEDIT_K_LINEEND || key_u == STB_TEXTEDIT_K_TEXTEND || key_u == STB_TEXTEDIT_K_DELETE || key_u == STB_TEXTEDIT_K_WORDRIGHT)
+ LastMoveDirectionLR = ImGuiDir_Right;
}
void ImGuiInputTextState::OnCharPressed(unsigned int c)
@@ -4156,40 +4252,40 @@ void ImGuiInputTextState::OnCharPressed(unsigned int c)
// The changes we had to make to stb_textedit_key made it very much UTF-8 specific which is not too great.
char utf8[5];
ImTextCharToUtf8(utf8, c);
- stb_textedit_text(this, Stb, utf8, (int)strlen(utf8));
+ stb_textedit_text(this, Stb, utf8, (int)ImStrlen(utf8));
CursorFollow = true;
CursorAnimReset();
}
// Those functions are not inlined in imgui_internal.h, allowing us to hide ImStbTexteditState from that header.
void ImGuiInputTextState::CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking
-void ImGuiInputTextState::CursorClamp() { Stb->cursor = ImMin(Stb->cursor, CurLenA); Stb->select_start = ImMin(Stb->select_start, CurLenA); Stb->select_end = ImMin(Stb->select_end, CurLenA); }
+void ImGuiInputTextState::CursorClamp() { Stb->cursor = ImMin(Stb->cursor, TextLen); Stb->select_start = ImMin(Stb->select_start, TextLen); Stb->select_end = ImMin(Stb->select_end, TextLen); }
bool ImGuiInputTextState::HasSelection() const { return Stb->select_start != Stb->select_end; }
void ImGuiInputTextState::ClearSelection() { Stb->select_start = Stb->select_end = Stb->cursor; }
int ImGuiInputTextState::GetCursorPos() const { return Stb->cursor; }
int ImGuiInputTextState::GetSelectionStart() const { return Stb->select_start; }
int ImGuiInputTextState::GetSelectionEnd() const { return Stb->select_end; }
-void ImGuiInputTextState::SelectAll() { Stb->select_start = 0; Stb->cursor = Stb->select_end = CurLenA; Stb->has_preferred_x = 0; }
-void ImGuiInputTextState::ReloadUserBufAndSelectAll() { ReloadUserBuf = true; ReloadSelectionStart = 0; ReloadSelectionEnd = INT_MAX; }
-void ImGuiInputTextState::ReloadUserBufAndKeepSelection() { ReloadUserBuf = true; ReloadSelectionStart = Stb->select_start; ReloadSelectionEnd = Stb->select_end; }
-void ImGuiInputTextState::ReloadUserBufAndMoveToEnd() { ReloadUserBuf = true; ReloadSelectionStart = ReloadSelectionEnd = INT_MAX; }
+float ImGuiInputTextState::GetPreferredOffsetX() const { return Stb->has_preferred_x ? Stb->preferred_x : -1; }
+void ImGuiInputTextState::SelectAll() { Stb->select_start = 0; Stb->cursor = Stb->select_end = TextLen; Stb->has_preferred_x = 0; }
+void ImGuiInputTextState::ReloadUserBufAndSelectAll() { WantReloadUserBuf = true; ReloadSelectionStart = 0; ReloadSelectionEnd = INT_MAX; }
+void ImGuiInputTextState::ReloadUserBufAndKeepSelection() { WantReloadUserBuf = true; ReloadSelectionStart = Stb->select_start; ReloadSelectionEnd = Stb->select_end; }
+void ImGuiInputTextState::ReloadUserBufAndMoveToEnd() { WantReloadUserBuf = true; ReloadSelectionStart = ReloadSelectionEnd = INT_MAX; }
ImGuiInputTextCallbackData::ImGuiInputTextCallbackData()
{
memset(this, 0, sizeof(*this));
}
-// Public API to manipulate UTF-8 text
-// We expose UTF-8 to the user (unlike the STB_TEXTEDIT_* functions which are manipulating wchar)
+// Public API to manipulate UTF-8 text from within a callback.
// FIXME: The existence of this rarely exercised code path is a bit of a nuisance.
+// Historically they existed because STB_TEXTEDIT_INSERTCHARS() etc. worked on our ImWchar
+// buffer, but nowadays they both work on UTF-8 data. Should aim to merge both.
void ImGuiInputTextCallbackData::DeleteChars(int pos, int bytes_count)
{
IM_ASSERT(pos + bytes_count <= BufTextLen);
char* dst = Buf + pos;
const char* src = Buf + pos + bytes_count;
- while (char c = *src++)
- *dst++ = c;
- *dst = '\0';
+ memmove(dst, src, BufTextLen - bytes_count - pos + 1);
if (CursorPos >= pos + bytes_count)
CursorPos -= bytes_count;
@@ -4206,22 +4302,24 @@ void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, cons
if (new_text == new_text_end)
return;
+ ImGuiContext& g = *Ctx;
+ ImGuiInputTextState* obj = &g.InputTextState;
+ IM_ASSERT(obj->ID != 0 && g.ActiveId == obj->ID);
+
+ // Grow internal buffer if needed
const bool is_resizable = (Flags & ImGuiInputTextFlags_CallbackResize) != 0;
- const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)strlen(new_text);
- if (new_text_len + BufTextLen >= BufSize)
+ const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)ImStrlen(new_text);
+ if (new_text_len + BufTextLen + 1 > obj->TextA.Size && (Flags & ImGuiInputTextFlags_ReadOnly) == 0)
{
if (!is_resizable)
return;
- // Contrary to STB_TEXTEDIT_INSERTCHARS() this is working in the UTF8 buffer, hence the mildly similar code (until we remove the U16 buffer altogether!)
- ImGuiContext& g = *Ctx;
- ImGuiInputTextState* edit_state = &g.InputTextState;
- IM_ASSERT(edit_state->ID != 0 && g.ActiveId == edit_state->ID);
- IM_ASSERT(Buf == edit_state->TextA.Data);
+ IM_ASSERT(Buf == obj->TextA.Data);
int new_buf_size = BufTextLen + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1;
- edit_state->TextA.reserve(new_buf_size + 1);
- Buf = edit_state->TextA.Data;
- BufSize = edit_state->BufCapacityA = new_buf_size;
+ obj->TextA.resize(new_buf_size + 1);
+ obj->TextSrc = obj->TextA.Data;
+ Buf = obj->TextA.Data;
+ BufSize = obj->BufCapacity = new_buf_size;
}
if (BufTextLen != pos)
@@ -4236,6 +4334,34 @@ void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, cons
BufTextLen += new_text_len;
}
+void ImGui::PushPasswordFont()
+{
+ ImGuiContext& g = *GImGui;
+ ImFontBaked* backup = &g.InputTextPasswordFontBackupBaked;
+ IM_ASSERT(backup->IndexAdvanceX.Size == 0 && backup->IndexLookup.Size == 0);
+ ImFontGlyph* glyph = g.FontBaked->FindGlyph('*');
+ g.InputTextPasswordFontBackupFlags = g.Font->Flags;
+ backup->FallbackGlyphIndex = g.FontBaked->FallbackGlyphIndex;
+ backup->FallbackAdvanceX = g.FontBaked->FallbackAdvanceX;
+ backup->IndexLookup.swap(g.FontBaked->IndexLookup);
+ backup->IndexAdvanceX.swap(g.FontBaked->IndexAdvanceX);
+ g.Font->Flags |= ImFontFlags_NoLoadGlyphs;
+ g.FontBaked->FallbackGlyphIndex = g.FontBaked->Glyphs.index_from_ptr(glyph);
+ g.FontBaked->FallbackAdvanceX = glyph->AdvanceX;
+}
+
+void ImGui::PopPasswordFont()
+{
+ ImGuiContext& g = *GImGui;
+ ImFontBaked* backup = &g.InputTextPasswordFontBackupBaked;
+ g.Font->Flags = g.InputTextPasswordFontBackupFlags;
+ g.FontBaked->FallbackGlyphIndex = backup->FallbackGlyphIndex;
+ g.FontBaked->FallbackAdvanceX = backup->FallbackAdvanceX;
+ g.FontBaked->IndexLookup.swap(backup->IndexLookup);
+ g.FontBaked->IndexAdvanceX.swap(backup->IndexAdvanceX);
+ IM_ASSERT(backup->IndexAdvanceX.Size == 0 && backup->IndexLookup.Size == 0);
+}
+
// Return false to discard a character.
static bool InputTextFilterCharacter(ImGuiContext* ctx, unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data, bool input_source_is_clipboard)
{
@@ -4246,7 +4372,13 @@ static bool InputTextFilterCharacter(ImGuiContext* ctx, unsigned int* p_char, Im
if (c < 0x20)
{
bool pass = false;
- pass |= (c == '\n') && (flags & ImGuiInputTextFlags_Multiline) != 0; // Note that an Enter KEY will emit \r and be ignored (we poll for KEY in InputText() code)
+ pass |= (c == '\n') && (flags & ImGuiInputTextFlags_Multiline) != 0; // Note that an Enter KEY will emit \r and be ignored (we poll for KEY in InputText() code)
+ if (c == '\n' && input_source_is_clipboard && (flags & ImGuiInputTextFlags_Multiline) == 0) // In single line mode, replace \n with a space
+ {
+ c = *p_char = ' ';
+ pass = true;
+ }
+ pass |= (c == '\n') && (flags & ImGuiInputTextFlags_Multiline) != 0;
pass |= (c == '\t') && (flags & ImGuiInputTextFlags_AllowTabInput) != 0;
if (!pass)
return false;
@@ -4283,7 +4415,7 @@ static bool InputTextFilterCharacter(ImGuiContext* ctx, unsigned int* p_char, Im
if (c == '.' || c == ',')
c = c_decimal_point;
- // Full-width -> half-width conversion for numeric fields (https://en.wikipedia.org/wiki/Halfwidth_and_Fullwidth_Forms_(Unicode_block)
+ // Full-width -> half-width conversion for numeric fields: https://en.wikipedia.org/wiki/Halfwidth_and_Fullwidth_Forms_(Unicode_block)
// While this is mostly convenient, this has the side-effect for uninformed users accidentally inputting full-width characters that they may
// scratch their head as to why it works in numerical fields vs in generic text fields it would require support in the font.
if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsScientific | ImGuiInputTextFlags_CharsHexadecimal))
@@ -4337,26 +4469,23 @@ static bool InputTextFilterCharacter(ImGuiContext* ctx, unsigned int* p_char, Im
return true;
}
-// Find the shortest single replacement we can make to get the new text from the old text.
-// Important: needs to be run before TextW is rewritten with the new characters because calling STB_TEXTEDIT_GETCHAR() at the end.
+// Find the shortest single replacement we can make to get from old_buf to new_buf
+// Note that this doesn't directly alter state->TextA, state->TextLen. They are expected to be made valid separately.
// FIXME: Ideally we should transition toward (1) making InsertChars()/DeleteChars() update undo-stack (2) discourage (and keep reconcile) or obsolete (and remove reconcile) accessing buffer directly.
-static void InputTextReconcileUndoStateAfterUserCallback(ImGuiInputTextState* state, const char* new_buf_a, int new_length_a)
+static void InputTextReconcileUndoState(ImGuiInputTextState* state, const char* old_buf, int old_length, const char* new_buf, int new_length)
{
- const char* old_buf = state->CallbackTextBackup.Data;
- const int old_length = state->CallbackTextBackup.Size - 1;
-
- const int shorter_length = ImMin(old_length, new_length_a);
+ const int shorter_length = ImMin(old_length, new_length);
int first_diff;
for (first_diff = 0; first_diff < shorter_length; first_diff++)
- if (old_buf[first_diff] != new_buf_a[first_diff])
+ if (old_buf[first_diff] != new_buf[first_diff])
break;
- if (first_diff == old_length && first_diff == new_length_a)
+ if (first_diff == old_length && first_diff == new_length)
return;
int old_last_diff = old_length - 1;
- int new_last_diff = new_length_a - 1;
+ int new_last_diff = new_length - 1;
for (; old_last_diff >= first_diff && new_last_diff >= first_diff; old_last_diff--, new_last_diff--)
- if (old_buf[old_last_diff] != new_buf_a[new_last_diff])
+ if (old_buf[old_last_diff] != new_buf[new_last_diff])
break;
const int insert_len = new_last_diff - first_diff + 1;
@@ -4385,9 +4514,101 @@ void ImGui::InputTextDeactivateHook(ImGuiID id)
else
{
IM_ASSERT(state->TextA.Data != 0);
- g.InputTextDeactivatedState.TextA.resize(state->CurLenA + 1);
- memcpy(g.InputTextDeactivatedState.TextA.Data, state->TextA.Data, state->CurLenA + 1);
+ IM_ASSERT(state->TextA[state->TextLen] == 0);
+ g.InputTextDeactivatedState.TextA.resize(state->TextLen + 1);
+ memcpy(g.InputTextDeactivatedState.TextA.Data, state->TextA.Data, state->TextLen + 1);
+ }
+}
+
+static int* ImLowerBound(int* in_begin, int* in_end, int v)
+{
+ int* in_p = in_begin;
+ for (size_t count = (size_t)(in_end - in_p); count > 0; )
+ {
+ size_t count2 = count >> 1;
+ int* mid = in_p + count2;
+ if (*mid < v)
+ {
+ in_p = ++mid;
+ count -= count2 + 1;
+ }
+ else
+ {
+ count = count2;
+ }
}
+ return in_p;
+}
+
+// FIXME-WORDWRAP: Bundle some of this into ImGuiTextIndex and/or extract as a different tool?
+// 'max_output_buffer_size' happens to be a meaningful optimization to avoid writing the full line_index when not necessarily needed (e.g. very large buffer, scrolled up, inactive)
+static int InputTextLineIndexBuild(ImGuiInputTextFlags flags, ImGuiTextIndex* line_index, const char* buf, const char* buf_end, float wrap_width, int max_output_buffer_size, const char** out_buf_end)
+{
+ ImGuiContext& g = *GImGui;
+ int size = 0;
+ const char* s;
+ if (flags & ImGuiInputTextFlags_WordWrap)
+ {
+ for (s = buf; s < buf_end; s = (*s == '\n') ? s + 1 : s)
+ {
+ if (size++ <= max_output_buffer_size)
+ line_index->Offsets.push_back((int)(s - buf));
+ s = ImFontCalcWordWrapPositionEx(g.Font, g.FontSize, s, buf_end, wrap_width, ImDrawTextFlags_WrapKeepBlanks);
+ }
+ }
+ else if (buf_end != NULL)
+ {
+ for (s = buf; s < buf_end; s = s ? s + 1 : buf_end)
+ {
+ if (size++ <= max_output_buffer_size)
+ line_index->Offsets.push_back((int)(s - buf));
+ s = (const char*)ImMemchr(s, '\n', buf_end - s);
+ }
+ }
+ else
+ {
+ const char* s_eol;
+ for (s = buf; ; s = s_eol + 1)
+ {
+ if (size++ <= max_output_buffer_size)
+ line_index->Offsets.push_back((int)(s - buf));
+ if ((s_eol = strchr(s, '\n')) != NULL)
+ continue;
+ s += strlen(s);
+ break;
+ }
+ }
+ if (out_buf_end != NULL)
+ *out_buf_end = buf_end = s;
+ if (size == 0)
+ {
+ line_index->Offsets.push_back(0);
+ size++;
+ }
+ if (buf_end > buf && buf_end[-1] == '\n' && size <= max_output_buffer_size)
+ {
+ line_index->Offsets.push_back((int)(buf_end - buf));
+ size++;
+ }
+ return size;
+}
+
+static ImVec2 InputTextLineIndexGetPosOffset(ImGuiContext& g, ImGuiInputTextState* state, ImGuiTextIndex* line_index, const char* buf, const char* buf_end, int cursor_n)
+{
+ const char* cursor_ptr = buf + cursor_n;
+ int* it_begin = line_index->Offsets.begin();
+ int* it_end = line_index->Offsets.end();
+ const int* it = ImLowerBound(it_begin, it_end, cursor_n);
+ if (it > it_begin)
+ if (it == it_end || *it != cursor_n || (state != NULL && state->WrapWidth > 0.0f && state->LastMoveDirectionLR == ImGuiDir_Right && cursor_ptr[-1] != '\n' && cursor_ptr[-1] != 0))
+ it--;
+
+ const int line_no = (it == it_begin) ? 0 : line_index->Offsets.index_from_ptr(it);
+ const char* line_start = line_index->get_line_begin(buf, line_no);
+ ImVec2 offset;
+ offset.x = InputTextCalcTextSize(&g, line_start, cursor_ptr, buf_end, NULL, NULL, ImDrawTextFlags_WrapKeepBlanks).x;
+ offset.y = (line_no + 1) * g.FontSize;
+ return offset;
}
// Edit a string of text
@@ -4407,6 +4628,9 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
IM_ASSERT(buf != NULL && buf_size >= 0);
IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline))); // Can't use both together (they both use up/down keys)
IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key)
+ IM_ASSERT(!((flags & ImGuiInputTextFlags_ElideLeft) && (flags & ImGuiInputTextFlags_Multiline))); // Multiline does not not work with left-trimming
+ IM_ASSERT((flags & ImGuiInputTextFlags_WordWrap) == 0 || (flags & ImGuiInputTextFlags_Password) == 0); // WordWrap does not work with Password mode.
+ IM_ASSERT((flags & ImGuiInputTextFlags_WordWrap) == 0 || (flags & ImGuiInputTextFlags_Multiline) != 0); // WordWrap does not work in single-line mode.
ImGuiContext& g = *GImGui;
ImGuiIO& io = g.IO;
@@ -4440,8 +4664,8 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
item_data_backup = g.LastItemData;
window->DC.CursorPos = backup_pos;
- // Prevent NavActivation from Tabbing when our widget accepts Tab inputs: this allows cycling through widgets without stopping.
- if (g.NavActivateId == id && (g.NavActivateFlags & ImGuiActivateFlags_FromTabbing) && (flags & ImGuiInputTextFlags_AllowTabInput))
+ // Prevent NavActivation from explicit Tabbing when our widget accepts Tab inputs: this allows cycling through widgets without stopping.
+ if (g.NavActivateId == id && (g.NavActivateFlags & ImGuiActivateFlags_FromTabbing) && !(g.NavActivateFlags & ImGuiActivateFlags_FromFocusApi) && (flags & ImGuiInputTextFlags_AllowTabInput))
g.NavActivateId = 0;
// Prevent NavActivate reactivating in BeginChild() when we are already active.
@@ -4497,6 +4721,13 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
if (is_resizable)
IM_ASSERT(callback != NULL); // Must provide a callback if you set the ImGuiInputTextFlags_CallbackResize flag!
+ // Word-wrapping: enforcing a fixed width not altered by vertical scrollbar makes things easier, notably to track cursor reliably and avoid one-frame glitches.
+ // Instead of using ImGuiWindowFlags_AlwaysVerticalScrollbar we account for that space if the scrollbar is not visible.
+ const bool is_wordwrap = (flags & ImGuiInputTextFlags_WordWrap) != 0;
+ float wrap_width = 0.0f;
+ if (is_wordwrap)
+ wrap_width = ImMax(1.0f, GetContentRegionAvail().x + (draw_window->ScrollbarY ? 0.0f : -g.Style.ScrollbarSize));
+
const bool input_requested_by_nav = (g.ActiveId != id) && ((g.NavActivateId == id) && ((g.NavActivateFlags & ImGuiActivateFlags_PreferInput) || (g.NavInputSource == ImGuiInputSource_Keyboard)));
const bool user_clicked = hovered && io.MouseClicked[0];
@@ -4507,60 +4738,67 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
float scroll_y = is_multiline ? draw_window->Scroll.y : FLT_MAX;
- const bool init_reload_from_user_buf = (state != NULL && state->ReloadUserBuf);
+ const bool init_reload_from_user_buf = (state != NULL && state->WantReloadUserBuf);
const bool init_changed_specs = (state != NULL && state->Stb->single_line != !is_multiline); // state != NULL means its our state.
const bool init_make_active = (user_clicked || user_scroll_finish || input_requested_by_nav);
const bool init_state = (init_make_active || user_scroll_active);
- if ((init_state && g.ActiveId != id) || init_changed_specs || init_reload_from_user_buf)
+ if (init_reload_from_user_buf)
+ {
+ int new_len = (int)ImStrlen(buf);
+ IM_ASSERT(new_len + 1 <= buf_size && "Is your input buffer properly zero-terminated?");
+ state->WantReloadUserBuf = false;
+ InputTextReconcileUndoState(state, state->TextA.Data, state->TextLen, buf, new_len);
+ state->TextA.resize(buf_size + 1); // we use +1 to make sure that .Data is always pointing to at least an empty string.
+ state->TextLen = new_len;
+ memcpy(state->TextA.Data, buf, state->TextLen + 1);
+ state->Stb->select_start = state->ReloadSelectionStart;
+ state->Stb->cursor = state->Stb->select_end = state->ReloadSelectionEnd;
+ state->CursorClamp();
+ }
+ else if ((init_state && g.ActiveId != id) || init_changed_specs)
{
// Access state even if we don't own it yet.
state = &g.InputTextState;
state->CursorAnimReset();
- state->ReloadUserBuf = false;
// Backup state of deactivating item so they'll have a chance to do a write to output buffer on the same frame they report IsItemDeactivatedAfterEdit (#4714)
InputTextDeactivateHook(state->ID);
+ // Take a copy of the initial buffer value.
// From the moment we focused we are normally ignoring the content of 'buf' (unless we are in read-only mode)
- const int buf_len = (int)strlen(buf);
- if (!init_reload_from_user_buf)
- {
- // Take a copy of the initial buffer value.
- state->InitialTextA.resize(buf_len + 1); // UTF-8. we use +1 to make sure that .Data is always pointing to at least an empty string.
- memcpy(state->InitialTextA.Data, buf, buf_len + 1);
- }
+ const int buf_len = (int)ImStrlen(buf);
+ IM_ASSERT(((buf_len + 1 <= buf_size) || (buf_len == 0 && buf_size == 0)) && "Is your input buffer properly zero-terminated?");
+ state->TextToRevertTo.resize(buf_len + 1); // UTF-8. we use +1 to make sure that .Data is always pointing to at least an empty string.
+ memcpy(state->TextToRevertTo.Data, buf, buf_len + 1);
// Preserve cursor position and undo/redo stack if we come back to same widget
// FIXME: Since we reworked this on 2022/06, may want to differentiate recycle_cursor vs recycle_undostate?
- bool recycle_state = (state->ID == id && !init_changed_specs && !init_reload_from_user_buf);
- if (recycle_state && (state->CurLenA != buf_len || (strncmp(state->TextA.Data, buf, buf_len) != 0)))
+ bool recycle_state = (state->ID == id && !init_changed_specs);
+ if (recycle_state && (state->TextLen != buf_len || (state->TextA.Data == NULL || strncmp(state->TextA.Data, buf, buf_len) != 0)))
recycle_state = false;
// Start edition
state->ID = id;
- state->TextA.resize(buf_size + 1); // we use +1 to make sure that .Data is always pointing to at least an empty string.
- state->CurLenA = (int)strlen(buf);
- memcpy(state->TextA.Data, buf, state->CurLenA + 1);
+ state->TextLen = buf_len;
+ if (!is_readonly)
+ {
+ state->TextA.resize(buf_size + 1); // we use +1 to make sure that .Data is always pointing to at least an empty string.
+ memcpy(state->TextA.Data, buf, state->TextLen + 1);
+ }
+ // Find initial scroll position for right alignment
+ state->Scroll = ImVec2(0.0f, 0.0f);
+ if (flags & ImGuiInputTextFlags_ElideLeft)
+ state->Scroll.x += ImMax(0.0f, CalcTextSize(buf).x - frame_size.x + style.FramePadding.x * 2.0f);
+
+ // Recycle existing cursor/selection/undo stack but clamp position
+ // Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler.
if (recycle_state)
- {
- // Recycle existing cursor/selection/undo stack but clamp position
- // Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler.
state->CursorClamp();
- }
else
- {
- state->Scroll = ImVec2(0.0f, 0.0f);
stb_textedit_initialize_state(state->Stb, !is_multiline);
- }
- if (init_reload_from_user_buf)
- {
- state->Stb->select_start = state->ReloadSelectionStart;
- state->Stb->cursor = state->Stb->select_end = state->ReloadSelectionEnd;
- state->CursorClamp();
- }
- else if (!is_multiline)
+ if (!is_multiline)
{
if (flags & ImGuiInputTextFlags_AutoSelectAll)
select_all = true;
@@ -4585,7 +4823,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
if (g.ActiveId == id)
{
// Declare some inputs, the other are registered and polled via Shortcut() routing system.
- // FIXME: The reason we don't use Shortcut() is we would need a routing flag to specify multiple mods, or to all mods combinaison into individual shortcuts.
+ // FIXME: The reason we don't use Shortcut() is we would need a routing flag to specify multiple mods, or to all mods combination into individual shortcuts.
const ImGuiKey always_owned_keys[] = { ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_Enter, ImGuiKey_KeypadEnter, ImGuiKey_Delete, ImGuiKey_Backspace, ImGuiKey_Home, ImGuiKey_End };
for (ImGuiKey key : always_owned_keys)
SetKeyOwner(key, id);
@@ -4610,7 +4848,15 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
// Expose scroll in a manner that is agnostic to us using a child window
if (is_multiline && state != NULL)
state->Scroll.y = draw_window->Scroll.y;
+
+ // Read-only mode always ever read from source buffer. Refresh TextLen when active.
+ if (is_readonly && state != NULL)
+ state->TextLen = (int)ImStrlen(buf);
+ //if (is_readonly && state != NULL)
+ // state->TextA.clear(); // Uncomment to facilitate debugging, but we otherwise prefer to keep/amortize th allocation.
}
+ if (state != NULL)
+ state->TextSrc = is_readonly ? buf : state->TextA.Data;
// We have an edge case if ActiveId was set through another widget (e.g. widget being swapped), clear id immediately (don't wait until the end of the function)
if (g.ActiveId == id && state == NULL)
@@ -4628,22 +4874,19 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
// Select the buffer to render.
const bool buf_display_from_state = (render_cursor || render_selection || g.ActiveId == id) && !is_readonly && state;
- const bool is_displaying_hint = (hint != NULL && (buf_display_from_state ? state->TextA.Data : buf)[0] == 0);
+ bool is_displaying_hint = (hint != NULL && (buf_display_from_state ? state->TextA.Data : buf)[0] == 0);
// Password pushes a temporary font with only a fallback glyph
if (is_password && !is_displaying_hint)
+ PushPasswordFont();
+
+ // Word-wrapping: attempt to keep cursor in view while resizing frame/parent
+ // FIXME-WORDWRAP: It would be better to preserve same relative offset.
+ if (is_wordwrap && state != NULL && state->ID == id && state->WrapWidth != wrap_width)
{
- const ImFontGlyph* glyph = g.Font->FindGlyph('*');
- ImFont* password_font = &g.InputTextPasswordFont;
- password_font->FontSize = g.Font->FontSize;
- password_font->Scale = g.Font->Scale;
- password_font->Ascent = g.Font->Ascent;
- password_font->Descent = g.Font->Descent;
- password_font->ContainerAtlas = g.Font->ContainerAtlas;
- password_font->FallbackGlyph = glyph;
- password_font->FallbackAdvanceX = glyph->AdvanceX;
- IM_ASSERT(password_font->Glyphs.empty() && password_font->IndexAdvanceX.empty() && password_font->IndexLookup.empty());
- PushFont(password_font);
+ state->CursorCenterY = true;
+ state->WrapWidth = wrap_width;
+ render_cursor = true;
}
// Process mouse inputs and character inputs
@@ -4651,8 +4894,9 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
{
IM_ASSERT(state != NULL);
state->Edited = false;
- state->BufCapacityA = buf_size;
+ state->BufCapacity = buf_size;
state->Flags = flags;
+ state->WrapWidth = wrap_width;
// Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget.
// Down the line we should have a cleaner library-wide concept of Selected vs Active.
@@ -4690,9 +4934,11 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
{
// Triple-click: Select line
const bool is_eol = ImStb::STB_TEXTEDIT_GETCHAR(state, state->Stb->cursor) == '\n';
+ state->WrapWidth = 0.0f; // Temporarily disable wrapping so we use real line start.
state->OnKeyPressed(STB_TEXTEDIT_K_LINESTART);
state->OnKeyPressed(STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_SHIFT);
state->OnKeyPressed(STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_SHIFT);
+ state->WrapWidth = wrap_width;
if (!is_eol && is_multiline)
{
ImSwap(state->Stb->select_start, state->Stb->select_end);
@@ -4774,14 +5020,14 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
const bool is_wordmove_key_down = is_osx ? io.KeyAlt : io.KeyCtrl; // OS X style: Text editing cursor movement using Alt instead of Ctrl
const bool is_startend_key_down = is_osx && io.KeyCtrl && !io.KeySuper && !io.KeyAlt; // OS X style: Line/Text Start and End using Cmd+Arrows instead of Home/End
- // Using Shortcut() with ImGuiInputFlags_RouteFocused (default policy) to allow routing operations for other code (e.g. calling window trying to use CTRL+A and CTRL+B: formet would be handled by InputText)
+ // Using Shortcut() with ImGuiInputFlags_RouteFocused (default policy) to allow routing operations for other code (e.g. calling window trying to use CTRL+A and CTRL+B: former would be handled by InputText)
// Otherwise we could simply assume that we own the keys as we are active.
const ImGuiInputFlags f_repeat = ImGuiInputFlags_Repeat;
const bool is_cut = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_X, f_repeat, id) || Shortcut(ImGuiMod_Shift | ImGuiKey_Delete, f_repeat, id)) && !is_readonly && !is_password && (!is_multiline || state->HasSelection());
const bool is_copy = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_C, 0, id) || Shortcut(ImGuiMod_Ctrl | ImGuiKey_Insert, 0, id)) && !is_password && (!is_multiline || state->HasSelection());
const bool is_paste = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_V, f_repeat, id) || Shortcut(ImGuiMod_Shift | ImGuiKey_Insert, f_repeat, id)) && !is_readonly;
const bool is_undo = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_Z, f_repeat, id)) && !is_readonly && is_undoable;
- const bool is_redo = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_Y, f_repeat, id) || (is_osx && Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Z, f_repeat, id))) && !is_readonly && is_undoable;
+ const bool is_redo = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_Y, f_repeat, id) || Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Z, f_repeat, id)) && !is_readonly && is_undoable;
const bool is_select_all = Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, 0, id);
// We allow validate/cancel with Nav source (gamepad) to makes it easier to undo an accidental NavInput press with no keyboard wired, but otherwise it isn't very useful.
@@ -4825,7 +5071,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
{
// Determine if we turn Enter into a \n character
bool ctrl_enter_for_new_line = (flags & ImGuiInputTextFlags_CtrlEnterForNewLine) != 0;
- if (!is_multiline || is_gamepad_validate || (ctrl_enter_for_new_line && !io.KeyCtrl) || (!ctrl_enter_for_new_line && io.KeyCtrl))
+ if (!is_multiline || is_gamepad_validate || (ctrl_enter_for_new_line != io.KeyCtrl))
{
validated = true;
if (io.ConfigInputTextEnterKeepActive && !is_multiline)
@@ -4844,7 +5090,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
{
if (flags & ImGuiInputTextFlags_EscapeClearsAll)
{
- if (buf[0] != 0)
+ if (state->TextA.Data[0] != 0)
{
revert_edit = true;
}
@@ -4875,13 +5121,13 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
// Cut, Copy
if (g.PlatformIO.Platform_SetClipboardTextFn != NULL)
{
+ // SetClipboardText() only takes null terminated strings + state->TextSrc may point to read-only user buffer, so we need to make a copy.
const int ib = state->HasSelection() ? ImMin(state->Stb->select_start, state->Stb->select_end) : 0;
- const int ie = state->HasSelection() ? ImMax(state->Stb->select_start, state->Stb->select_end) : state->CurLenA;
-
- char backup = state->TextA.Data[ie];
- state->TextA.Data[ie] = 0; // A bit of a hack since SetClipboardText only takes null terminated strings
- SetClipboardText(state->TextA.Data + ib);
- state->TextA.Data[ie] = backup;
+ const int ie = state->HasSelection() ? ImMax(state->Stb->select_start, state->Stb->select_end) : state->TextLen;
+ g.TempBuffer.reserve(ie - ib + 1);
+ memcpy(g.TempBuffer.Data, state->TextSrc + ib, ie - ib);
+ g.TempBuffer.Data[ie - ib] = 0;
+ SetClipboardText(g.TempBuffer.Data);
}
if (is_cut)
{
@@ -4896,26 +5142,28 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
if (const char* clipboard = GetClipboardText())
{
// Filter pasted buffer
- const int clipboard_len = (int)strlen(clipboard);
- char* clipboard_filtered = (char*)IM_ALLOC(clipboard_len + 1);
- int clipboard_filtered_len = 0;
+ const int clipboard_len = (int)ImStrlen(clipboard);
+ ImVector<char> clipboard_filtered;
+ clipboard_filtered.reserve(clipboard_len + 1);
for (const char* s = clipboard; *s != 0; )
{
unsigned int c;
- int len = ImTextCharFromUtf8(&c, s, NULL);
- s += len;
+ int in_len = ImTextCharFromUtf8(&c, s, NULL);
+ s += in_len;
if (!InputTextFilterCharacter(&g, &c, flags, callback, callback_user_data, true))
continue;
- memcpy(clipboard_filtered + clipboard_filtered_len, s - len, len);
- clipboard_filtered_len += len;
+ char c_utf8[5];
+ ImTextCharToUtf8(c_utf8, c);
+ int out_len = (int)ImStrlen(c_utf8);
+ clipboard_filtered.resize(clipboard_filtered.Size + out_len);
+ memcpy(clipboard_filtered.Data + clipboard_filtered.Size - out_len, c_utf8, out_len);
}
- clipboard_filtered[clipboard_filtered_len] = 0;
- if (clipboard_filtered_len > 0) // If everything was filtered, ignore the pasting operation
+ if (clipboard_filtered.Size > 0) // If everything was filtered, ignore the pasting operation
{
- stb_textedit_paste(state, state->Stb, clipboard_filtered, clipboard_filtered_len);
+ clipboard_filtered.push_back(0);
+ stb_textedit_paste(state, state->Stb, clipboard_filtered.Data, clipboard_filtered.Size - 1);
state->CursorFollow = true;
}
- MemFree(clipboard_filtered);
}
}
@@ -4934,38 +5182,36 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
if (flags & ImGuiInputTextFlags_EscapeClearsAll)
{
// Clear input
- IM_ASSERT(buf[0] != 0);
+ IM_ASSERT(state->TextA.Data[0] != 0);
apply_new_text = "";
apply_new_text_length = 0;
value_changed = true;
- IMSTB_TEXTEDIT_CHARTYPE empty_string;
+ char empty_string = 0;
stb_textedit_replace(state, state->Stb, &empty_string, 0);
}
- else if (strcmp(buf, state->InitialTextA.Data) != 0)
+ else if (strcmp(state->TextA.Data, state->TextToRevertTo.Data) != 0)
{
- apply_new_text = state->InitialTextA.Data;
- apply_new_text_length = state->InitialTextA.Size - 1;
+ apply_new_text = state->TextToRevertTo.Data;
+ apply_new_text_length = state->TextToRevertTo.Size - 1;
// Restore initial value. Only return true if restoring to the initial value changes the current buffer contents.
// Push records into the undo stack so we can CTRL+Z the revert operation itself
value_changed = true;
- stb_textedit_replace(state, state->Stb, state->InitialTextA.Data, state->InitialTextA.Size - 1);
+ stb_textedit_replace(state, state->Stb, state->TextToRevertTo.Data, state->TextToRevertTo.Size - 1);
}
}
- // When using 'ImGuiInputTextFlags_EnterReturnsTrue' as a special case we reapply the live buffer back to the input buffer
- // before clearing ActiveId, even though strictly speaking it wasn't modified on this frame.
- // If we didn't do that, code like InputInt() with ImGuiInputTextFlags_EnterReturnsTrue would fail.
- // This also allows the user to use InputText() with ImGuiInputTextFlags_EnterReturnsTrue without maintaining any user-side storage
+ // FIXME-OPT: We always reapply the live buffer back to the input buffer before clearing ActiveId,
+ // even though strictly speaking it wasn't modified on this frame. Should mark dirty state from the stb_textedit callbacks.
+ // If we do that, need to ensure that as special case, 'validated == true' also writes back.
+ // This also allows the user to use InputText() without maintaining any user-side storage.
// (please note that if you use this property along ImGuiInputTextFlags_CallbackResize you can end up with your temporary string object
// unnecessarily allocating once a frame, either store your string data, either if you don't then don't use ImGuiInputTextFlags_CallbackResize).
- const bool apply_edit_back_to_user_buffer = !revert_edit || (validated && (flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0);
+ const bool apply_edit_back_to_user_buffer = true;// !revert_edit || (validated && (flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0);
if (apply_edit_back_to_user_buffer)
{
- // Apply new value immediately - copy modified buffer back
+ // Apply current edited text immediately.
// Note that as soon as the input box is active, the in-widget value gets priority over any underlying modification of the input buffer
- // FIXME: We actually always render 'buf' when calling DrawList->AddText, making the comment above incorrect.
- // FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks.
// User callback
if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackEdit | ImGuiInputTextFlags_CallbackAlways)) != 0)
@@ -5008,14 +5254,15 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
callback_data.UserData = callback_user_data;
// FIXME-OPT: Undo stack reconcile needs a backup of the data until we rework API, see #7925
- state->CallbackTextBackup.resize(state->CurLenA + 1);
- memcpy(state->CallbackTextBackup.Data, state->TextA.Data, state->CurLenA + 1);
-
char* callback_buf = is_readonly ? buf : state->TextA.Data;
+ IM_ASSERT(callback_buf == state->TextSrc);
+ state->CallbackTextBackup.resize(state->TextLen + 1);
+ memcpy(state->CallbackTextBackup.Data, callback_buf, state->TextLen + 1);
+
callback_data.EventKey = event_key;
callback_data.Buf = callback_buf;
- callback_data.BufTextLen = state->CurLenA;
- callback_data.BufSize = state->BufCapacityA;
+ callback_data.BufTextLen = state->TextLen;
+ callback_data.BufSize = state->BufCapacity;
callback_data.BufDirty = false;
const int utf8_cursor_pos = callback_data.CursorPos = state->Stb->cursor;
@@ -5028,7 +5275,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
// Read back what user may have modified
callback_buf = is_readonly ? buf : state->TextA.Data; // Pointer may have been invalidated by a resize callback
IM_ASSERT(callback_data.Buf == callback_buf); // Invalid to modify those fields
- IM_ASSERT(callback_data.BufSize == state->BufCapacityA);
+ IM_ASSERT(callback_data.BufSize == state->BufCapacity);
IM_ASSERT(callback_data.Flags == flags);
const bool buf_dirty = callback_data.BufDirty;
if (callback_data.CursorPos != utf8_cursor_pos || buf_dirty) { state->Stb->cursor = callback_data.CursorPos; state->CursorFollow = true; }
@@ -5037,20 +5284,19 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
if (buf_dirty)
{
// Callback may update buffer and thus set buf_dirty even in read-only mode.
- IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text!
- InputTextReconcileUndoStateAfterUserCallback(state, callback_data.Buf, callback_data.BufTextLen); // FIXME: Move the rest of this block inside function and rename to InputTextReconcileStateAfterUserCallback() ?
- state->CurLenA = callback_data.BufTextLen; // Assume correct length and valid UTF-8 from user, saves us an extra strlen()
- state->TextA.Size = state->CurLenA + 1;
+ IM_ASSERT(callback_data.BufTextLen == (int)ImStrlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text!
+ InputTextReconcileUndoState(state, state->CallbackTextBackup.Data, state->CallbackTextBackup.Size - 1, callback_data.Buf, callback_data.BufTextLen);
+ state->TextLen = callback_data.BufTextLen; // Assume correct length and valid UTF-8 from user, saves us an extra strlen()
state->CursorAnimReset();
}
}
}
// Will copy result string if modified
- if (!is_readonly && strcmp(state->TextA.Data, buf) != 0)
+ if (!is_readonly && strcmp(state->TextSrc, buf) != 0)
{
- apply_new_text = state->TextA.Data;
- apply_new_text_length = state->CurLenA;
+ apply_new_text = state->TextSrc;
+ apply_new_text_length = state->TextLen;
value_changed = true;
}
}
@@ -5102,8 +5348,6 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
// Otherwise request text input ahead for next frame.
if (g.ActiveId == id && clear_active_id)
ClearActiveID();
- else if (g.ActiveId == id)
- g.WantTextInputNextFrame = 1;
// Render frame
if (!is_multiline)
@@ -5112,9 +5356,11 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
}
- const ImVec4 clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + inner_size.x, frame_bb.Min.y + inner_size.y); // Not using frame_bb.Max because we have adjusted size
ImVec2 draw_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding;
ImVec2 text_size(0.0f, 0.0f);
+ ImRect clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + inner_size.x, frame_bb.Min.y + inner_size.y); // Not using frame_bb.Max because we have adjusted size
+ if (is_multiline)
+ clip_rect.ClipWith(draw_window->ClipRect);
// Set upper limit of single-line InputTextEx() at 2 million characters strings. The current pathological worst case is a long line
// without any carriage return, which would makes ImFont::RenderText() reserve too many vertices and probably crash. Avoid it altogether.
@@ -5122,20 +5368,59 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
const int buf_display_max_length = 2 * 1024 * 1024;
const char* buf_display = buf_display_from_state ? state->TextA.Data : buf; //-V595
const char* buf_display_end = NULL; // We have specialized paths below for setting the length
+
+ // Display hint when contents is empty
+ // At this point we need to handle the possibility that a callback could have modified the underlying buffer (#8368)
+ const bool new_is_displaying_hint = (hint != NULL && (buf_display_from_state ? state->TextA.Data : buf)[0] == 0);
+ if (new_is_displaying_hint != is_displaying_hint)
+ {
+ if (is_password && !is_displaying_hint)
+ PopPasswordFont();
+ is_displaying_hint = new_is_displaying_hint;
+ if (is_password && !is_displaying_hint)
+ PushPasswordFont();
+ }
if (is_displaying_hint)
{
buf_display = hint;
- buf_display_end = hint + strlen(hint);
+ buf_display_end = hint + ImStrlen(hint);
+ }
+ else
+ {
+ if (render_cursor || render_selection || g.ActiveId == id)
+ buf_display_end = buf_display + state->TextLen; //-V595
+ else if (is_multiline && !is_wordwrap)
+ buf_display_end = NULL; // Inactive multi-line: end of buffer will be output by InputTextLineIndexBuild() special strchr() path.
+ else
+ buf_display_end = buf_display + ImStrlen(buf_display);
}
+ // Calculate visibility
+ int line_visible_n0 = 0, line_visible_n1 = 1;
+ if (is_multiline)
+ CalcClipRectVisibleItemsY(clip_rect, draw_pos, g.FontSize, &line_visible_n0, &line_visible_n1);
+
+ // Build line index for easy data access (makes code below simpler and faster)
+ ImGuiTextIndex* line_index = &g.InputTextLineIndex;
+ line_index->Offsets.resize(0);
+ int line_count = 1;
+ if (is_multiline)
+ line_count = InputTextLineIndexBuild(flags, line_index, buf_display, buf_display_end, wrap_width, (render_cursor && state && state->CursorFollow) ? INT_MAX : line_visible_n1 + 1, buf_display_end ? NULL : &buf_display_end);
+ line_index->EndOffset = (int)(buf_display_end - buf_display);
+ line_visible_n1 = ImMin(line_visible_n1, line_count);
+
+ // Store text height (we don't need width)
+ text_size = ImVec2(inner_size.x, line_count * g.FontSize);
+ //GetForegroundDrawList()->AddRect(draw_pos + ImVec2(0, line_visible_n0 * g.FontSize), draw_pos + ImVec2(frame_size.x, line_visible_n1 * g.FontSize), IM_COL32(255, 0, 0, 255));
+
+ // Calculate blinking cursor position
+ const ImVec2 cursor_offset = render_cursor && state ? InputTextLineIndexGetPosOffset(g, state, line_index, buf_display, buf_display_end, state->Stb->cursor) : ImVec2(0.0f, 0.0f);
+ ImVec2 draw_scroll;
+
// Render text. We currently only render selection when the widget is active or while scrolling.
- // FIXME: We could remove the '&& render_cursor' to keep rendering selection when inactive.
+ const ImU32 text_col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text);
if (render_cursor || render_selection)
{
- IM_ASSERT(state != NULL);
- if (!is_displaying_hint)
- buf_display_end = buf_display + state->CurLenA;
-
// Render text (with cursor and selection)
// This is going to be messy. We need to:
// - Display the text (this alone can be more easily clipped)
@@ -5143,48 +5428,11 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
// - Measure text height (for scrollbar)
// We are attempting to do most of that in **one main pass** to minimize the computation cost (non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an extra refactoring effort)
// FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8.
- const char* text_begin = state->TextA.Data;
- const char* text_end = text_begin + state->CurLenA;
- ImVec2 cursor_offset, select_start_offset;
-
- {
- // Find lines numbers straddling cursor and selection min position
- int cursor_line_no = render_cursor ? -1 : -1000;
- int selmin_line_no = render_selection ? -1 : -1000;
- const char* cursor_ptr = render_cursor ? text_begin + state->Stb->cursor : NULL;
- const char* selmin_ptr = render_selection ? text_begin + ImMin(state->Stb->select_start, state->Stb->select_end) : NULL;
-
- // Count lines and find line number for cursor and selection ends
- int line_count = 1;
- if (is_multiline)
- {
- for (const char* s = text_begin; (s = (const char*)memchr(s, '\n', (size_t)(text_end - s))) != NULL; s++)
- {
- if (cursor_line_no == -1 && s >= cursor_ptr) { cursor_line_no = line_count; }
- if (selmin_line_no == -1 && s >= selmin_ptr) { selmin_line_no = line_count; }
- line_count++;
- }
- }
- if (cursor_line_no == -1)
- cursor_line_no = line_count;
- if (selmin_line_no == -1)
- selmin_line_no = line_count;
-
- // Calculate 2d position by finding the beginning of the line and measuring distance
- cursor_offset.x = InputTextCalcTextSize(&g, ImStrbol(cursor_ptr, text_begin), cursor_ptr).x;
- cursor_offset.y = cursor_line_no * g.FontSize;
- if (selmin_line_no >= 0)
- {
- select_start_offset.x = InputTextCalcTextSize(&g, ImStrbol(selmin_ptr, text_begin), selmin_ptr).x;
- select_start_offset.y = selmin_line_no * g.FontSize;
- }
-
- // Store text height (note that we haven't calculated text width at all, see GitHub issues #383, #1224)
- if (is_multiline)
- text_size = ImVec2(inner_size.x, line_count * g.FontSize);
- }
+ IM_ASSERT(state != NULL);
+ state->LineCount = line_count;
// Scroll
+ float new_scroll_y = scroll_y;
if (render_cursor && state->CursorFollow)
{
// Horizontal scroll in chunks of quarter width
@@ -5199,7 +5447,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
}
else
{
- state->Scroll.y = 0.0f;
+ state->Scroll.x = 0.0f;
}
// Vertical scroll
@@ -5207,99 +5455,110 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
{
// Test if cursor is vertically visible
if (cursor_offset.y - g.FontSize < scroll_y)
- scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize);
+ new_scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize);
else if (cursor_offset.y - (inner_size.y - style.FramePadding.y * 2.0f) >= scroll_y)
- scroll_y = cursor_offset.y - inner_size.y + style.FramePadding.y * 2.0f;
- const float scroll_max_y = ImMax((text_size.y + style.FramePadding.y * 2.0f) - inner_size.y, 0.0f);
- scroll_y = ImClamp(scroll_y, 0.0f, scroll_max_y);
- draw_pos.y += (draw_window->Scroll.y - scroll_y); // Manipulate cursor pos immediately avoid a frame of lag
- draw_window->Scroll.y = scroll_y;
+ new_scroll_y = cursor_offset.y - inner_size.y + style.FramePadding.y * 2.0f;
}
-
state->CursorFollow = false;
}
-
- // Draw selection
- const ImVec2 draw_scroll = ImVec2(state->Scroll.x, 0.0f);
- if (render_selection)
+ if (state->CursorCenterY)
{
- const char* text_selected_begin = text_begin + ImMin(state->Stb->select_start, state->Stb->select_end);
- const char* text_selected_end = text_begin + ImMax(state->Stb->select_start, state->Stb->select_end);
-
- ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg, render_cursor ? 1.0f : 0.6f); // FIXME: current code flow mandate that render_cursor is always true here, we are leaving the transparent one for tests.
- float bg_offy_up = is_multiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection.
- float bg_offy_dn = is_multiline ? 0.0f : 2.0f;
- ImVec2 rect_pos = draw_pos + select_start_offset - draw_scroll;
- for (const char* p = text_selected_begin; p < text_selected_end; )
- {
- if (rect_pos.y > clip_rect.w + g.FontSize)
- break;
- if (rect_pos.y < clip_rect.y)
- {
- p = (const char*)memchr((void*)p, '\n', text_selected_end - p);
- p = p ? p + 1 : text_selected_end;
- }
- else
- {
- ImVec2 rect_size = InputTextCalcTextSize(&g, p, text_selected_end, &p, NULL, true);
- if (rect_size.x <= 0.0f) rect_size.x = IM_TRUNC(g.Font->GetCharAdvance((ImWchar)' ') * 0.50f); // So we can see selected empty lines
- ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos + ImVec2(rect_size.x, bg_offy_dn));
- rect.ClipWith(clip_rect);
- if (rect.Overlaps(clip_rect))
- draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color);
- rect_pos.x = draw_pos.x - draw_scroll.x;
- }
- rect_pos.y += g.FontSize;
- }
+ if (is_multiline)
+ new_scroll_y = cursor_offset.y - g.FontSize - (inner_size.y * 0.5f - style.FramePadding.y);
+ state->CursorCenterY = false;
+ render_cursor = false;
}
-
- // We test for 'buf_display_max_length' as a way to avoid some pathological cases (e.g. single-line 1 MB string) which would make ImDrawList crash.
- // FIXME-OPT: Multiline could submit a smaller amount of contents to AddText() since we already iterated through it.
- if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length)
+ if (new_scroll_y != scroll_y)
{
- ImU32 col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text);
- draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, col, buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect);
+ const float scroll_max_y = ImMax((text_size.y + style.FramePadding.y * 2.0f) - inner_size.y, 0.0f);
+ scroll_y = ImClamp(new_scroll_y, 0.0f, scroll_max_y);
+ draw_pos.y += (draw_window->Scroll.y - scroll_y); // Manipulate cursor pos immediately avoid a frame of lag
+ draw_window->Scroll.y = scroll_y;
+ CalcClipRectVisibleItemsY(clip_rect, draw_pos, g.FontSize, &line_visible_n0, &line_visible_n1);
+ line_visible_n1 = ImMin(line_visible_n1, line_count);
}
- // Draw blinking cursor
- if (render_cursor)
+ // Draw selection
+ draw_scroll.x = state->Scroll.x;
+ if (render_selection)
{
- state->CursorAnim += io.DeltaTime;
- bool cursor_is_visible = (!g.IO.ConfigInputTextCursorBlink) || (state->CursorAnim <= 0.0f) || ImFmod(state->CursorAnim, 1.20f) <= 0.80f;
- ImVec2 cursor_screen_pos = ImTrunc(draw_pos + cursor_offset - draw_scroll);
- ImRect cursor_screen_rect(cursor_screen_pos.x, cursor_screen_pos.y - g.FontSize + 0.5f, cursor_screen_pos.x + 1.0f, cursor_screen_pos.y - 1.5f);
- if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect))
- draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_Text));
+ const ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg, render_cursor ? 1.0f : 0.6f); // FIXME: current code flow mandate that render_cursor is always true here, we are leaving the transparent one for tests.
+ const float bg_offy_up = is_multiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection.
+ const float bg_offy_dn = is_multiline ? 0.0f : 2.0f;
+ const float bg_eol_width = IM_TRUNC(g.FontBaked->GetCharAdvance((ImWchar)' ') * 0.50f); // So we can see selected empty lines
- // Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.)
- if (!is_readonly)
+ const char* text_selected_begin = buf_display + ImMin(state->Stb->select_start, state->Stb->select_end);
+ const char* text_selected_end = buf_display + ImMax(state->Stb->select_start, state->Stb->select_end);
+ for (int line_n = line_visible_n0; line_n < line_visible_n1; line_n++)
{
- g.PlatformImeData.WantVisible = true;
- g.PlatformImeData.InputPos = ImVec2(cursor_screen_pos.x - 1.0f, cursor_screen_pos.y - g.FontSize);
- g.PlatformImeData.InputLineHeight = g.FontSize;
- g.PlatformImeViewport = window->Viewport->ID;
+ const char* p = line_index->get_line_begin(buf_display, line_n);
+ const char* p_eol = line_index->get_line_end(buf_display, line_n);
+ const bool p_eol_is_wrap = (p_eol < buf_display_end && *p_eol != '\n');
+ if (p_eol_is_wrap)
+ p_eol++;
+ const char* line_selected_begin = (text_selected_begin > p) ? text_selected_begin : p;
+ const char* line_selected_end = (text_selected_end < p_eol) ? text_selected_end : p_eol;
+
+ float rect_width = 0.0f;
+ if (line_selected_begin < line_selected_end)
+ rect_width += CalcTextSize(line_selected_begin, line_selected_end).x;
+ if (text_selected_begin <= p_eol && text_selected_end > p_eol && !p_eol_is_wrap)
+ rect_width += bg_eol_width; // So we can see selected empty lines
+ if (rect_width == 0.0f)
+ continue;
+
+ ImRect rect;
+ rect.Min.x = draw_pos.x - draw_scroll.x + CalcTextSize(p, line_selected_begin).x;
+ rect.Min.y = draw_pos.y - draw_scroll.y + line_n * g.FontSize;
+ rect.Max.x = rect.Min.x + rect_width;
+ rect.Max.y = rect.Min.y + bg_offy_dn + g.FontSize;
+ rect.Min.y -= bg_offy_up;
+ rect.ClipWith(clip_rect);
+ draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color);
}
}
}
- else
+
+ // Find render position for right alignment (single-line only)
+ if (g.ActiveId != id && flags & ImGuiInputTextFlags_ElideLeft)
+ draw_pos.x = ImMin(draw_pos.x, frame_bb.Max.x - CalcTextSize(buf_display, NULL).x - style.FramePadding.x);
+ //draw_scroll.x = state->Scroll.x; // Preserve scroll when inactive?
+
+ // Render text
+ if ((is_multiline || (buf_display_end - buf_display) < buf_display_max_length) && (text_col & IM_COL32_A_MASK) && (line_visible_n0 < line_visible_n1))
+ g.Font->RenderText(draw_window->DrawList, g.FontSize,
+ draw_pos - draw_scroll + ImVec2(0.0f, line_visible_n0 * g.FontSize),
+ text_col, clip_rect.AsVec4(),
+ line_index->get_line_begin(buf_display, line_visible_n0),
+ line_index->get_line_end(buf_display, line_visible_n1 - 1),
+ wrap_width, ImDrawTextFlags_WrapKeepBlanks);
+
+ // Render blinking cursor
+ if (render_cursor)
{
- // Render text only (no selection, no cursor)
- if (is_multiline)
- text_size = ImVec2(inner_size.x, InputTextCalcTextLenAndLineCount(buf_display, &buf_display_end) * g.FontSize); // We don't need width
- else if (!is_displaying_hint && g.ActiveId == id)
- buf_display_end = buf_display + state->CurLenA;
- else if (!is_displaying_hint)
- buf_display_end = buf_display + strlen(buf_display);
+ state->CursorAnim += io.DeltaTime;
+ bool cursor_is_visible = (!g.IO.ConfigInputTextCursorBlink) || (state->CursorAnim <= 0.0f) || ImFmod(state->CursorAnim, 1.20f) <= 0.80f;
+ ImVec2 cursor_screen_pos = ImTrunc(draw_pos + cursor_offset - draw_scroll);
+ ImRect cursor_screen_rect(cursor_screen_pos.x, cursor_screen_pos.y - g.FontSize + 0.5f, cursor_screen_pos.x + 1.0f, cursor_screen_pos.y - 1.5f);
+ if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect))
+ draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_InputTextCursor), 1.0f); // FIXME-DPI: Cursor thickness (#7031)
- if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length)
+ // Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.)
+ // This is required for some backends (SDL3) to start emitting character/text inputs.
+ // As per #6341, make sure we don't set that on the deactivating frame.
+ if (!is_readonly && g.ActiveId == id)
{
- ImU32 col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text);
- draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos, col, buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect);
+ ImGuiPlatformImeData* ime_data = &g.PlatformImeData; // (this is a public struct, passed to io.Platform_SetImeDataFn() handler)
+ ime_data->WantVisible = true;
+ ime_data->WantTextInput = true;
+ ime_data->InputPos = ImVec2(cursor_screen_pos.x - 1.0f, cursor_screen_pos.y - g.FontSize);
+ ime_data->InputLineHeight = g.FontSize;
+ ime_data->ViewportId = window->Viewport->ID;
}
}
if (is_password && !is_displaying_hint)
- PopFont();
+ PopPasswordFont();
if (is_multiline)
{
@@ -5319,6 +5578,8 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
g.LastItemData.StatusFlags = item_data_backup.StatusFlags;
}
}
+ if (state)
+ state->TextSrc = NULL;
// Log as text
if (g.LogEnabled && (!is_password || is_displaying_hint))
@@ -5348,7 +5609,11 @@ void ImGui::DebugNodeInputTextState(ImGuiInputTextState* state)
ImStb::StbUndoState* undo_state = &stb_state->undostate;
Text("ID: 0x%08X, ActiveID: 0x%08X", state->ID, g.ActiveId);
DebugLocateItemOnHover(state->ID);
- Text("CurLenA: %d, Cursor: %d, Selection: %d..%d", state->CurLenA, stb_state->cursor, stb_state->select_start, stb_state->select_end);
+ Text("TextLen: %d, Cursor: %d%s, Selection: %d..%d", state->TextLen, stb_state->cursor,
+ (state->Flags & ImGuiInputTextFlags_WordWrap) ? (state->LastMoveDirectionLR == ImGuiDir_Left ? " (L)" : " (R)") : "",
+ stb_state->select_start, stb_state->select_end);
+ Text("BufCapacity: %d, LineCount: %d", state->BufCapacity, state->LineCount);
+ Text("(Internal Buffer: TextA Size: %d, Capacity: %d)", state->TextA.Size, state->TextA.Capacity);
Text("has_preferred_x: %d (%.2f)", stb_state->has_preferred_x, stb_state->preferred_x);
Text("undo_point: %d, redo_point: %d, undo_char_point: %d, redo_char_point: %d", undo_state->undo_point, undo_state->redo_point, undo_state->undo_char_point, undo_state->redo_char_point);
if (BeginChild("undopoints", ImVec2(0.0f, GetTextLineHeight() * 10), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeY)) // Visualize undo state
@@ -5425,7 +5690,7 @@ static void ColorEditRestoreHS(const float* col, float* H, float* S, float* V)
// Edit colors components (each component in 0.0f..1.0f range).
// See enum ImGuiColorEditFlags_ for available options. e.g. Only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
-// With typical options: Left-click on color square to open color picker. Right-click to open option menu. CTRL-Click over input fields to edit them and TAB to go to next item.
+// With typical options: Left-click on color square to open color picker. Right-click to open option menu. CTRL+Click over input fields to edit them and TAB to go to next item.
bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
@@ -5872,7 +6137,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl
if ((flags & ImGuiColorEditFlags_NoLabel))
Text("Current");
- ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf | ImGuiColorEditFlags_NoTooltip;
+ ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_AlphaMask_ | ImGuiColorEditFlags_NoTooltip;
ColorButton("##current", col_v4, (flags & sub_flags_to_forward), ImVec2(square_sz * 3, square_sz * 2));
if (ref_col != NULL)
{
@@ -5912,7 +6177,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl
if ((flags & ImGuiColorEditFlags_NoInputs) == 0)
{
PushItemWidth((alpha_bar ? bar1_pos_x : bar0_pos_x) + bars_width - picker_pos.x);
- ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags_DataTypeMask_ | ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoSmallPreview | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf;
+ ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags_DataTypeMask_ | ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_AlphaMask_ | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoSmallPreview;
ImGuiColorEditFlags sub_flags = (flags & sub_flags_to_forward) | ImGuiColorEditFlags_NoPicker;
if (flags & ImGuiColorEditFlags_DisplayRGB || (flags & ImGuiColorEditFlags_DisplayMask_) == 0)
if (ColorEdit4("##rgb", col, sub_flags | ImGuiColorEditFlags_DisplayRGB))
@@ -6088,8 +6353,8 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held);
- if (flags & ImGuiColorEditFlags_NoAlpha)
- flags &= ~(ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf);
+ if (flags & (ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaOpaque))
+ flags &= ~(ImGuiColorEditFlags_AlphaNoBg | ImGuiColorEditFlags_AlphaPreviewHalf);
ImVec4 col_rgb = col;
if (flags & ImGuiColorEditFlags_InputHSV)
@@ -6108,14 +6373,17 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl
if ((flags & ImGuiColorEditFlags_AlphaPreviewHalf) && col_rgb.w < 1.0f)
{
float mid_x = IM_ROUND((bb_inner.Min.x + bb_inner.Max.x) * 0.5f);
- RenderColorRectWithAlphaCheckerboard(window->DrawList, ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, GetColorU32(col_rgb), grid_step, ImVec2(-grid_step + off, off), rounding, ImDrawFlags_RoundCornersRight);
+ if ((flags & ImGuiColorEditFlags_AlphaNoBg) == 0)
+ RenderColorRectWithAlphaCheckerboard(window->DrawList, ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, GetColorU32(col_rgb), grid_step, ImVec2(-grid_step + off, off), rounding, ImDrawFlags_RoundCornersRight);
+ else
+ window->DrawList->AddRectFilled(ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, GetColorU32(col_rgb), rounding, ImDrawFlags_RoundCornersRight);
window->DrawList->AddRectFilled(bb_inner.Min, ImVec2(mid_x, bb_inner.Max.y), GetColorU32(col_rgb_without_alpha), rounding, ImDrawFlags_RoundCornersLeft);
}
else
{
// Because GetColorU32() multiplies by the global style Alpha and we don't want to display a checkerboard if the source code had no alpha
- ImVec4 col_source = (flags & ImGuiColorEditFlags_AlphaPreview) ? col_rgb : col_rgb_without_alpha;
- if (col_source.w < 1.0f)
+ ImVec4 col_source = (flags & ImGuiColorEditFlags_AlphaOpaque) ? col_rgb_without_alpha : col_rgb;
+ if (col_source.w < 1.0f && (flags & ImGuiColorEditFlags_AlphaNoBg) == 0)
RenderColorRectWithAlphaCheckerboard(window->DrawList, bb_inner.Min, bb_inner.Max, GetColorU32(col_source), grid_step, ImVec2(off, off), rounding);
else
window->DrawList->AddRectFilled(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), rounding);
@@ -6126,7 +6394,7 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl
if (g.Style.FrameBorderSize > 0.0f)
RenderFrameBorder(bb.Min, bb.Max, rounding);
else
- window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), rounding); // Color button are often in need of some sort of border
+ window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), rounding); // Color buttons are often in need of some sort of border // FIXME-DPI
}
// Drag and Drop Source
@@ -6145,7 +6413,7 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl
// Tooltip
if (!(flags & ImGuiColorEditFlags_NoTooltip) && hovered && IsItemHovered(ImGuiHoveredFlags_ForTooltip))
- ColorTooltip(desc_id, &col.x, flags & (ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf));
+ ColorTooltip(desc_id, &col.x, flags & (ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_AlphaMask_));
return pressed;
}
@@ -6186,7 +6454,8 @@ void ImGui::ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags
ImVec2 sz(g.FontSize * 3 + g.Style.FramePadding.y * 2, g.FontSize * 3 + g.Style.FramePadding.y * 2);
ImVec4 cf(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);
int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]);
- ColorButton("##preview", cf, (flags & (ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf)) | ImGuiColorEditFlags_NoTooltip, sz);
+ ImGuiColorEditFlags flags_to_forward = ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_AlphaMask_;
+ ColorButton("##preview", cf, (flags & flags_to_forward) | ImGuiColorEditFlags_NoTooltip, sz);
SameLine();
if ((flags & ImGuiColorEditFlags_InputRGB) || !(flags & ImGuiColorEditFlags_InputMask_))
{
@@ -6307,6 +6576,7 @@ void ImGui::ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags fl
// - TreeNodeV()
// - TreeNodeEx()
// - TreeNodeExV()
+// - TreeNodeStoreStackData() [Internal]
// - TreeNodeBehavior() [Internal]
// - TreePush()
// - TreePop()
@@ -6465,18 +6735,26 @@ bool ImGui::TreeNodeUpdateNextOpen(ImGuiID storage_id, ImGuiTreeNodeFlags flags)
// Store ImGuiTreeNodeStackData for just submitted node.
// Currently only supports 32 level deep and we are fine with (1 << Depth) overflowing into a zero, easy to increase.
-static void TreeNodeStoreStackData(ImGuiTreeNodeFlags flags)
+static void TreeNodeStoreStackData(ImGuiTreeNodeFlags flags, float x1)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
g.TreeNodeStack.resize(g.TreeNodeStack.Size + 1);
- ImGuiTreeNodeStackData* tree_node_data = &g.TreeNodeStack.back();
+ ImGuiTreeNodeStackData* tree_node_data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1];
tree_node_data->ID = g.LastItemData.ID;
tree_node_data->TreeFlags = flags;
tree_node_data->ItemFlags = g.LastItemData.ItemFlags;
tree_node_data->NavRect = g.LastItemData.NavRect;
+
+ // Initially I tried to latch value for GetColorU32(ImGuiCol_TreeLines) but it's not a good trade-off for very large trees.
+ const bool draw_lines = (flags & (ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes)) != 0;
+ tree_node_data->DrawLinesX1 = draw_lines ? (x1 + g.FontSize * 0.5f + g.Style.FramePadding.x) : +FLT_MAX;
+ tree_node_data->DrawLinesTableColumn = (draw_lines && g.CurrentTable) ? (ImGuiTableColumnIdx)g.CurrentTable->CurrentColumn : -1;
+ tree_node_data->DrawLinesToNodesY2 = -FLT_MAX;
window->DC.TreeHasStackDataDepthMask |= (1 << window->DC.TreeDepth);
+ if (flags & ImGuiTreeNodeFlags_DrawLinesToNodes)
+ window->DC.TreeRecordsClippedNodesY2Mask |= (1 << window->DC.TreeDepth);
}
// When using public API, currently 'id == storage_id' is always true, but we separate the values to facilitate advanced user code doing storage queries outside of UI loop.
@@ -6502,10 +6780,11 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l
// We vertically grow up to current line height up the typical widget height.
const float frame_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + style.FramePadding.y * 2), label_size.y + padding.y * 2);
const bool span_all_columns = (flags & ImGuiTreeNodeFlags_SpanAllColumns) != 0 && (g.CurrentTable != NULL);
+ const bool span_all_columns_label = (flags & ImGuiTreeNodeFlags_LabelSpanAllColumns) != 0 && (g.CurrentTable != NULL);
ImRect frame_bb;
frame_bb.Min.x = span_all_columns ? window->ParentWorkRect.Min.x : (flags & ImGuiTreeNodeFlags_SpanFullWidth) ? window->WorkRect.Min.x : window->DC.CursorPos.x;
frame_bb.Min.y = window->DC.CursorPos.y;
- frame_bb.Max.x = span_all_columns ? window->ParentWorkRect.Max.x : (flags & ImGuiTreeNodeFlags_SpanTextWidth) ? window->DC.CursorPos.x + text_width + padding.x : window->WorkRect.Max.x;
+ frame_bb.Max.x = span_all_columns ? window->ParentWorkRect.Max.x : (flags & ImGuiTreeNodeFlags_SpanLabelWidth) ? window->DC.CursorPos.x + text_width + padding.x : window->WorkRect.Max.x;
frame_bb.Max.y = window->DC.CursorPos.y + frame_height;
if (display_frame)
{
@@ -6519,7 +6798,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l
// For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing
ImRect interact_bb = frame_bb;
- if ((flags & (ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_SpanFullWidth | ImGuiTreeNodeFlags_SpanTextWidth | ImGuiTreeNodeFlags_SpanAllColumns)) == 0)
+ if ((flags & (ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_SpanFullWidth | ImGuiTreeNodeFlags_SpanLabelWidth | ImGuiTreeNodeFlags_SpanAllColumns)) == 0)
interact_bb.Max.x = frame_bb.Min.x + text_width + (label_size.x > 0.0f ? style.ItemSpacing.x * 2.0f : 0.0f);
// Compute open and multi-select states before ItemAdd() as it clear NextItem data.
@@ -6527,7 +6806,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l
bool is_open = TreeNodeUpdateNextOpen(storage_id, flags);
bool is_visible;
- if (span_all_columns)
+ if (span_all_columns || span_all_columns_label)
{
// Modify ClipRect for the ItemAdd(), faster than doing a PushColumnsBackground/PushTableBackgroundChannel for every Selectable..
const float backup_clip_rect_min_x = window->ClipRect.Min.x;
@@ -6545,14 +6824,18 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l
g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDisplayRect;
g.LastItemData.DisplayRect = frame_bb;
- // If a NavLeft request is happening and ImGuiTreeNodeFlags_NavLeftJumpsBackHere enabled:
+ // If a NavLeft request is happening and ImGuiTreeNodeFlags_NavLeftJumpsToParent enabled:
// Store data for the current depth to allow returning to this node from any child item.
// For this purpose we essentially compare if g.NavIdIsAlive went from 0 to 1 between TreeNode() and TreePop().
- // It will become tempting to enable ImGuiTreeNodeFlags_NavLeftJumpsBackHere by default or move it to ImGuiStyle.
+ // It will become tempting to enable ImGuiTreeNodeFlags_NavLeftJumpsToParent by default or move it to ImGuiStyle.
bool store_tree_node_stack_data = false;
+ if ((flags & ImGuiTreeNodeFlags_DrawLinesMask_) == 0)
+ flags |= g.Style.TreeLinesFlags;
+ const bool draw_tree_lines = (flags & (ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes)) && (frame_bb.Min.y < window->ClipRect.Max.y) && (g.Style.TreeLinesSize > 0.0f);
if (!(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
{
- if ((flags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere) && is_open && !g.NavIdIsAlive)
+ store_tree_node_stack_data = draw_tree_lines;
+ if ((flags & ImGuiTreeNodeFlags_NavLeftJumpsToParent) && !g.NavIdIsAlive)
if (g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet())
store_tree_node_stack_data = true;
}
@@ -6560,15 +6843,22 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l
const bool is_leaf = (flags & ImGuiTreeNodeFlags_Leaf) != 0;
if (!is_visible)
{
- if (store_tree_node_stack_data && is_open)
- TreeNodeStoreStackData(flags); // Call before TreePushOverrideID()
+ if ((flags & ImGuiTreeNodeFlags_DrawLinesToNodes) && (window->DC.TreeRecordsClippedNodesY2Mask & (1 << (window->DC.TreeDepth - 1))))
+ {
+ ImGuiTreeNodeStackData* parent_data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1];
+ parent_data->DrawLinesToNodesY2 = ImMax(parent_data->DrawLinesToNodesY2, window->DC.CursorPos.y); // Don't need to aim to mid Y position as we are clipped anyway.
+ if (frame_bb.Min.y >= window->ClipRect.Max.y)
+ window->DC.TreeRecordsClippedNodesY2Mask &= ~(1 << (window->DC.TreeDepth - 1)); // Done
+ }
+ if (is_open && store_tree_node_stack_data)
+ TreeNodeStoreStackData(flags, text_pos.x - text_offset_x); // Call before TreePushOverrideID()
if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
TreePushOverrideID(id);
IMGUI_TEST_ENGINE_ITEM_INFO(g.LastItemData.ID, label, g.LastItemData.StatusFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0));
return is_open;
}
- if (span_all_columns)
+ if (span_all_columns || span_all_columns_label)
{
TablePushBackgroundChannel();
g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasClipRect;
@@ -6607,6 +6897,8 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l
button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick;
else
button_flags |= ImGuiButtonFlags_PressedOnClickRelease;
+ if (flags & ImGuiTreeNodeFlags_NoNavFocus)
+ button_flags |= ImGuiButtonFlags_NoNavFocus;
bool selected = (flags & ImGuiTreeNodeFlags_Selected) != 0;
const bool was_selected = selected;
@@ -6693,6 +6985,8 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l
const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, true, style.FrameRounding);
RenderNavCursor(frame_bb, id, nav_render_cursor_flags);
+ if (span_all_columns && !span_all_columns_label)
+ TablePopBackgroundChannel();
if (flags & ImGuiTreeNodeFlags_Bullet)
RenderBullet(window->DrawList, ImVec2(text_pos.x - text_offset_x * 0.60f, text_pos.y + g.FontSize * 0.5f), text_col);
else if (!is_leaf)
@@ -6713,6 +7007,8 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l
RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, false);
}
RenderNavCursor(frame_bb, id, nav_render_cursor_flags);
+ if (span_all_columns && !span_all_columns_label)
+ TablePopBackgroundChannel();
if (flags & ImGuiTreeNodeFlags_Bullet)
RenderBullet(window->DrawList, ImVec2(text_pos.x - text_offset_x * 0.5f, text_pos.y + g.FontSize * 0.5f), text_col);
else if (!is_leaf)
@@ -6721,18 +7017,21 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l
LogSetNextTextDecoration(">", NULL);
}
- if (span_all_columns)
- TablePopBackgroundChannel();
+ if (draw_tree_lines)
+ TreeNodeDrawLineToChildNode(ImVec2(text_pos.x - text_offset_x + padding.x, text_pos.y + g.FontSize * 0.5f));
// Label
if (display_frame)
RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size);
else
RenderText(text_pos, label, label_end, false);
+
+ if (span_all_columns_label)
+ TablePopBackgroundChannel();
}
- if (store_tree_node_stack_data && is_open)
- TreeNodeStoreStackData(flags); // Call before TreePushOverrideID()
+ if (is_open && store_tree_node_stack_data)
+ TreeNodeStoreStackData(flags, text_pos.x - text_offset_x); // Call before TreePushOverrideID()
if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
TreePushOverrideID(id); // Could use TreePush(label) but this avoid computing twice
@@ -6740,6 +7039,64 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l
return is_open;
}
+// Draw horizontal line from our parent node
+// This is only called for visible child nodes so we are not too fussy anymore about performances
+void ImGui::TreeNodeDrawLineToChildNode(const ImVec2& target_pos)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ if (window->DC.TreeDepth == 0 || (window->DC.TreeHasStackDataDepthMask & (1 << (window->DC.TreeDepth - 1))) == 0)
+ return;
+
+ ImGuiTreeNodeStackData* parent_data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1];
+ float x1 = ImTrunc(parent_data->DrawLinesX1);
+ float x2 = ImTrunc(target_pos.x - g.Style.ItemInnerSpacing.x);
+ float y = ImTrunc(target_pos.y);
+ float rounding = (g.Style.TreeLinesRounding > 0.0f) ? ImMin(x2 - x1, g.Style.TreeLinesRounding) : 0.0f;
+ parent_data->DrawLinesToNodesY2 = ImMax(parent_data->DrawLinesToNodesY2, y - rounding);
+ if (x1 >= x2)
+ return;
+ if (rounding > 0.0f)
+ {
+ x1 += 0.5f + rounding;
+ window->DrawList->PathArcToFast(ImVec2(x1, y - rounding), rounding, 6, 3);
+ if (x1 < x2)
+ window->DrawList->PathLineTo(ImVec2(x2, y));
+ window->DrawList->PathStroke(GetColorU32(ImGuiCol_TreeLines), ImDrawFlags_None, g.Style.TreeLinesSize);
+ }
+ else
+ {
+ window->DrawList->AddLine(ImVec2(x1, y), ImVec2(x2, y), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize);
+ }
+}
+
+// Draw vertical line of the hierarchy
+void ImGui::TreeNodeDrawLineToTreePop(const ImGuiTreeNodeStackData* data)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ float y1 = ImMax(data->NavRect.Max.y, window->ClipRect.Min.y);
+ float y2 = data->DrawLinesToNodesY2;
+ if (data->TreeFlags & ImGuiTreeNodeFlags_DrawLinesFull)
+ {
+ float y2_full = window->DC.CursorPos.y;
+ if (g.CurrentTable)
+ y2_full = ImMax(g.CurrentTable->RowPosY2, y2_full);
+ y2_full = ImTrunc(y2_full - g.Style.ItemSpacing.y - g.FontSize * 0.5f);
+ if (y2 + (g.Style.ItemSpacing.y + g.Style.TreeLinesRounding) < y2_full) // FIXME: threshold to use ToNodes Y2 instead of Full Y2 when close by ItemSpacing.y
+ y2 = y2_full;
+ }
+ y2 = ImMin(y2, window->ClipRect.Max.y);
+ if (y2 <= y1)
+ return;
+ float x = ImTrunc(data->DrawLinesX1);
+ if (data->DrawLinesTableColumn != -1)
+ TablePushColumnChannel(data->DrawLinesTableColumn);
+ window->DrawList->AddLine(ImVec2(x, y1), ImVec2(x, y2), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize);
+ if (data->DrawLinesTableColumn != -1)
+ TablePopColumnChannel();
+}
+
void ImGui::TreePush(const char* str_id)
{
ImGuiWindow* window = GetCurrentWindow();
@@ -6774,18 +7131,23 @@ void ImGui::TreePop()
window->DC.TreeDepth--;
ImU32 tree_depth_mask = (1 << window->DC.TreeDepth);
- if (window->DC.TreeHasStackDataDepthMask & tree_depth_mask) // Only set during request
+ if (window->DC.TreeHasStackDataDepthMask & tree_depth_mask)
{
- ImGuiTreeNodeStackData* data = &g.TreeNodeStack.back();
+ const ImGuiTreeNodeStackData* data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1];
IM_ASSERT(data->ID == window->IDStack.back());
- if (data->TreeFlags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere)
- {
- // Handle Left arrow to move to parent tree node (when ImGuiTreeNodeFlags_NavLeftJumpsBackHere is enabled)
+
+ // Handle Left arrow to move to parent tree node (when ImGuiTreeNodeFlags_NavLeftJumpsToParent is enabled)
+ if (data->TreeFlags & ImGuiTreeNodeFlags_NavLeftJumpsToParent)
if (g.NavIdIsAlive && g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet())
NavMoveRequestResolveWithPastTreeNode(&g.NavMoveResultLocal, data);
- }
+
+ // Draw hierarchy lines
+ if (data->DrawLinesX1 != +FLT_MAX && window->DC.CursorPos.y >= window->ClipRect.Min.y)
+ TreeNodeDrawLineToTreePop(data);
+
g.TreeNodeStack.pop_back();
window->DC.TreeHasStackDataDepthMask &= ~tree_depth_mask;
+ window->DC.TreeRecordsClippedNodesY2Mask &= ~tree_depth_mask;
}
IM_ASSERT(window->IDStack.Size > 1); // There should always be 1 element in the IDStack (pushed during window creation). If this triggers you called TreePop/PopID too much.
@@ -6903,13 +7265,9 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl
if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_SpanAvailWidth))
size.x = ImMax(label_size.x, max_x - min_x);
- // Text stays at the submission position, but bounding box may be extended on both sides
- const ImVec2 text_min = pos;
- const ImVec2 text_max(min_x + size.x, pos.y + size.y);
-
// Selectables are meant to be tightly packed together with no click-gap, so we extend their box to cover spacing between selectable.
// FIXME: Not part of layout so not included in clipper calculation, but ItemSize currently doesn't allow offsetting CursorPos.
- ImRect bb(min_x, pos.y, text_max.x, text_max.y);
+ ImRect bb(min_x, pos.y, min_x + size.x, pos.y + size.y);
if ((flags & ImGuiSelectableFlags_NoPadWithHalfSpacing) == 0)
{
const float spacing_x = span_all_columns ? 0.0f : style.ItemSpacing.x;
@@ -6982,6 +7340,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags);
+ bool auto_selected = false;
// Multi-selection support (footer)
if (is_multi_select)
@@ -6998,8 +7357,8 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl
// - (2) usage will fail with clipped items
// The multi-select API aim to fix those issues, e.g. may be replaced with a BeginSelection() API.
if ((flags & ImGuiSelectableFlags_SelectOnNav) && g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == g.CurrentFocusScopeId)
- if (g.NavJustMovedToId == id)
- selected = pressed = true;
+ if (g.NavJustMovedToId == id && (g.NavJustMovedToKeyMods & ImGuiMod_Ctrl) == 0)
+ selected = pressed = auto_selected = true;
}
// Update NavId when clicking or when Hovering (this doesn't happen on most widgets), so navigation can be resumed with keyboard/gamepad
@@ -7024,12 +7383,8 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl
const bool highlighted = hovered || (flags & ImGuiSelectableFlags_Highlight);
if (highlighted || selected)
{
- // FIXME-MULTISELECT: Styling: Color for 'selected' elements? ImGuiCol_HeaderSelected
- ImU32 col;
- if (selected && !highlighted)
- col = GetColorU32(ImLerp(GetStyleColorVec4(ImGuiCol_Header), GetStyleColorVec4(ImGuiCol_HeaderHovered), 0.5f));
- else
- col = GetColorU32((held && highlighted) ? ImGuiCol_HeaderActive : highlighted ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
+ // Between 1.91.0 and 1.91.4 we made selected Selectable use an arbitrary lerp between _Header and _HeaderHovered. Removed that now. (#8106)
+ ImU32 col = GetColorU32((held && highlighted) ? ImGuiCol_HeaderActive : highlighted ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
RenderFrame(bb.Min, bb.Max, col, false, 0.0f);
}
if (g.NavId == id)
@@ -7049,11 +7404,12 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl
PopColumnsBackground();
}
+ // Text stays at the submission position. Alignment/clipping extents ignore SpanAllColumns.
if (is_visible)
- RenderTextClipped(text_min, text_max, label, NULL, &label_size, style.SelectableTextAlign, &bb);
+ RenderTextClipped(pos, ImVec2(ImMin(pos.x + size.x, window->WorkRect.Max.x), pos.y + size.y), label, NULL, &label_size, style.SelectableTextAlign, &bb);
// Automatically close popups
- if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_NoAutoClosePopups) && (g.LastItemData.ItemFlags & ImGuiItemFlags_AutoClosePopups))
+ if (pressed && !auto_selected && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_NoAutoClosePopups) && (g.LastItemData.ItemFlags & ImGuiItemFlags_AutoClosePopups))
CloseCurrentPopup();
if (disabled_item && !disabled_global)
@@ -7113,7 +7469,7 @@ ImGuiTypingSelectRequest* ImGui::GetTypingSelectRequest(ImGuiTypingSelectFlags f
// Append to buffer
const int buffer_max_len = IM_ARRAYSIZE(data->SearchBuffer) - 1;
- int buffer_len = (int)strlen(data->SearchBuffer);
+ int buffer_len = (int)ImStrlen(data->SearchBuffer);
bool select_request = false;
for (ImWchar w : g.IO.InputQueueCharacters)
{
@@ -7407,7 +7763,7 @@ void ImGui::EndBoxSelect(const ImRect& scope_rect, ImGuiMultiSelectFlags ms_flag
ImRect box_select_r = bs->BoxSelectRectCurr;
box_select_r.ClipWith(scope_rect);
window->DrawList->AddRectFilled(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_SeparatorHovered, 0.30f)); // FIXME-MULTISELECT: Styling
- window->DrawList->AddRect(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_NavCursor)); // FIXME-MULTISELECT: Styling
+ window->DrawList->AddRect(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_NavCursor)); // FIXME-MULTISELECT FIXME-DPI: Styling
// Scroll
const bool enable_scroll = (ms_flags & ImGuiMultiSelectFlags_ScopeWindow) && (ms_flags & ImGuiMultiSelectFlags_BoxSelectNoScroll) == 0;
@@ -7491,6 +7847,12 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int sel
if (flags & ImGuiMultiSelectFlags_BoxSelect2d)
flags &= ~ImGuiMultiSelectFlags_BoxSelect1d;
+ // FIXME: Workaround to the fact we override CursorMaxPos, meaning size measurement are lost. (#8250)
+ // They should perhaps be stacked properly?
+ if (ImGuiTable* table = g.CurrentTable)
+ if (table->CurrentColumn != -1)
+ TableEndCell(table); // This is currently safe to call multiple time. If that properly is lost we can extract the "save measurement" part of it.
+
// FIXME: BeginFocusScope()
const ImGuiID id = window->IDStack.back();
ms->Clear();
@@ -7605,7 +7967,7 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect()
if (ms->IsFocused)
{
// We currently don't allow user code to modify RangeSrcItem by writing to BeginIO's version, but that would be an easy change here.
- if (ms->IO.RangeSrcReset || (ms->RangeSrcPassedBy == false && ms->IO.RangeSrcItem != ImGuiSelectionUserData_Invalid)) // Can't read storage->RangeSrcItem here -> we want the state at begining of the scope (see tests for easy failure)
+ if (ms->IO.RangeSrcReset || (ms->RangeSrcPassedBy == false && ms->IO.RangeSrcItem != ImGuiSelectionUserData_Invalid)) // Can't read storage->RangeSrcItem here -> we want the state at beginning of the scope (see tests for easy failure)
{
IMGUI_DEBUG_LOG_SELECTION("[selection] EndMultiSelect: Reset RangeSrcItem.\n"); // Will set be to NavId.
storage->RangeSrcItem = ImGuiSelectionUserData_Invalid;
@@ -8125,7 +8487,7 @@ void ImGuiSelectionBasicStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io)
// - Optimized select can append unsorted, then sort in a second pass. Optimized unselect can clear in-place then compact in a second pass.
// - A more optimal version wouldn't even use ImGuiStorage but directly a ImVector<ImGuiID> to reduce bandwidth, but this is a reasonable trade off to reuse code.
// - There are many ways this could be better optimized. The worse case scenario being: using BoxSelect2d in a grid, box-select scrolling down while wiggling
- // left and right: it affects coarse clipping + can emit multiple SetRange with 1 item each.)
+ // left and right: it affects coarse clipping + can emit multiple SetRange with 1 item each.
// FIXME-OPT: For each block of consecutive SetRange request:
// - add all requests to a sorted list, store ID, selected, offset in ImGuiStorage.
// - rewrite sorted storage a single time.
@@ -8204,15 +8566,10 @@ void ImGuiSelectionExternalStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io)
//-------------------------------------------------------------------------
// This is essentially a thin wrapper to using BeginChild/EndChild with the ImGuiChildFlags_FrameStyle flag for stylistic changes + displaying a label.
-// This handle some subtleties with capturing info from the label, but for 99% uses it could essentially be rewritten as:
-// if (ImGui::BeginChild("...", ImVec2(ImGui::CalcItemWidth(), ImGui::GetTextLineHeight() * 7.5f), ImGuiChildFlags_FrameStyle))
-// { .... }
-// ImGui::EndChild();
-// ImGui::SameLine();
-// ImGui::AlignTextToFramePadding();
-// ImGui::Text("Label");
+// This handle some subtleties with capturing info from the label.
+// If you don't need a label you can pretty much directly use ImGui::BeginChild() with ImGuiChildFlags_FrameStyle.
// Tip: To have a list filling the entire window width, use size.x = -FLT_MIN and pass an non-visible label e.g. "##empty"
-// Tip: If your vertical size is calculated from an item count (e.g. 10 * item_height) consider adding a fractional part to facilitate seeing scrolling boundaries (e.g. 10.25 * item_height).
+// Tip: If your vertical size is calculated from an item count (e.g. 10 * item_height) consider adding a fractional part to facilitate seeing scrolling boundaries (e.g. 10.5f * item_height).
bool ImGui::BeginListBox(const char* label, const ImVec2& size_arg)
{
ImGuiContext& g = *GImGui;
@@ -8591,12 +8948,14 @@ bool ImGui::BeginMenuBar()
IM_ASSERT(!window->DC.MenuBarAppending);
BeginGroup(); // Backup position on layer 0 // FIXME: Misleading to use a group for that backup/restore
- PushID("##menubar");
+ PushID("##MenuBar");
// We don't clip with current window clipping rectangle as it is already set to the area below. However we clip with window full rect.
// We remove 1 worth of rounding to Max.x to that text in long menus and small windows don't tend to display over the lower-right rounded area, which looks particularly glitchy.
+ const float border_top = ImMax(IM_ROUND(window->WindowBorderSize * 0.5f - window->TitleBarHeight), 0.0f);
+ const float border_half = IM_ROUND(window->WindowBorderSize * 0.5f);
ImRect bar_rect = window->MenuBarRect();
- ImRect clip_rect(ImFloor(bar_rect.Min.x + window->WindowBorderSize), ImFloor(bar_rect.Min.y + window->WindowBorderSize), ImFloor(ImMax(bar_rect.Min.x, bar_rect.Max.x - ImMax(window->WindowRounding, window->WindowBorderSize))), ImFloor(bar_rect.Max.y));
+ ImRect clip_rect(ImFloor(bar_rect.Min.x + border_half), ImFloor(bar_rect.Min.y + border_top), ImFloor(ImMax(bar_rect.Min.x, bar_rect.Max.x - ImMax(window->WindowRounding, border_half))), ImFloor(bar_rect.Max.y));
clip_rect.ClipWith(window->OuterRectClipped);
PushClipRect(clip_rect.Min, clip_rect.Max, false);
@@ -8617,6 +8976,10 @@ void ImGui::EndMenuBar()
return;
ImGuiContext& g = *GImGui;
+ IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
+ IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar);
+ IM_ASSERT(window->DC.MenuBarAppending);
+
// Nav: When a move request within one of our child menu failed, capture the request to navigate among our siblings.
if (NavMoveRequestButNoResultYet() && (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right) && (g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
{
@@ -8643,11 +9006,9 @@ void ImGui::EndMenuBar()
}
}
- IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
- IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar);
- IM_ASSERT(window->DC.MenuBarAppending);
PopClipRect();
PopID();
+ IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
window->DC.MenuBarOffset.x = window->DC.CursorPos.x - window->Pos.x; // Save horizontal position so next append can reuse it. This is kinda equivalent to a per-layer CursorPos.
// FIXME: Extremely confusing, cleanup by (a) working on WorkRect stack system (b) not using a Group confusingly here.
@@ -8718,22 +9079,33 @@ bool ImGui::BeginMainMenuBar()
float height = GetFrameHeight();
bool is_open = BeginViewportSideBar("##MainMenuBar", viewport, ImGuiDir_Up, height, window_flags);
g.NextWindowData.MenuBarOffsetMinVal = ImVec2(0.0f, 0.0f);
-
- if (is_open)
- BeginMenuBar();
- else
+ if (!is_open)
+ {
End();
+ return false;
+ }
+
+ // Temporarily disable _NoSavedSettings, in the off-chance that tables or child windows submitted within the menu-bar may want to use settings. (#8356)
+ g.CurrentWindow->Flags &= ~ImGuiWindowFlags_NoSavedSettings;
+ BeginMenuBar();
return is_open;
}
void ImGui::EndMainMenuBar()
{
+ ImGuiContext& g = *GImGui;
+ if (!g.CurrentWindow->DC.MenuBarAppending)
+ {
+ IM_ASSERT_USER_ERROR(0, "Calling EndMainMenuBar() not from a menu-bar!"); // Not technically testing that it is the main menu bar
+ return;
+ }
+
EndMenuBar();
+ g.CurrentWindow->Flags |= ImGuiWindowFlags_NoSavedSettings; // Restore _NoSavedSettings (#8356)
// When the user has left the menu layer (typically: closed menus through activation of an item), we restore focus to the previous window
// FIXME: With this strategy we won't be able to restore a NULL focus.
- ImGuiContext& g = *GImGui;
- if (g.CurrentWindow == g.NavWindow && g.NavLayer == ImGuiNavLayer_Main && !g.NavAnyRequest)
+ if (g.CurrentWindow == g.NavWindow && g.NavLayer == ImGuiNavLayer_Main && !g.NavAnyRequest && g.ActiveId == 0)
FocusTopMostWindowUnderOne(g.NavWindow, NULL, NULL, ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild);
End();
@@ -8786,7 +9158,7 @@ bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled)
if (g.MenusIdSubmittedThisFrame.contains(id))
{
if (menu_is_open)
- menu_is_open = BeginPopupEx(id, window_flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
+ menu_is_open = BeginPopupMenuEx(id, label, window_flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
else
g.NextWindowData.ClearFlags(); // we behave like Begin() and need to consume those values
return menu_is_open;
@@ -8817,7 +9189,7 @@ bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled)
const ImGuiSelectableFlags selectable_flags = ImGuiSelectableFlags_NoHoldingActiveID | ImGuiSelectableFlags_NoSetKeyOwner | ImGuiSelectableFlags_SelectOnClick | ImGuiSelectableFlags_NoAutoClosePopups;
if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
{
- // Menu inside an horizontal menu bar
+ // Menu inside a horizontal menu bar
// Selectable extend their highlight by half ItemSpacing in each direction.
// For ChildMenu, the popup position will be overwritten by the call to FindBestWindowPosForPopup() in Begin()
popup_pos = ImVec2(pos.x - 1.0f - IM_TRUNC(style.ItemSpacing.x * 0.5f), pos.y - style.FramePadding.y + window->MenuBarHeight);
@@ -8826,6 +9198,7 @@ bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled)
float w = label_size.x;
ImVec2 text_pos(window->DC.CursorPos.x + offsets->OffsetLabel, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);
pressed = Selectable("", menu_is_open, selectable_flags, ImVec2(w, label_size.y));
+ LogSetNextTextDecoration("[", "]");
RenderText(text_pos, label);
PopStyleVar();
window->DC.CursorPos.x += IM_TRUNC(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar().
@@ -8834,7 +9207,7 @@ bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled)
{
// Menu inside a regular/vertical menu
// (In a typical menu window where all items are BeginMenu() or MenuItem() calls, extra_w will always be 0.0f.
- // Only when they are other items sticking out we're going to add spacing, yet only register minimum width into the layout system.
+ // Only when they are other items sticking out we're going to add spacing, yet only register minimum width into the layout system.)
popup_pos = ImVec2(pos.x, pos.y - style.WindowPadding.y);
float icon_w = (icon && icon[0]) ? CalcTextSize(icon, NULL).x : 0.0f;
float checkmark_w = IM_TRUNC(g.FontSize * 1.20f);
@@ -8842,6 +9215,7 @@ bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled)
float extra_w = ImMax(0.0f, GetContentRegionAvail().x - min_w);
ImVec2 text_pos(window->DC.CursorPos.x + offsets->OffsetLabel, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);
pressed = Selectable("", menu_is_open, selectable_flags | ImGuiSelectableFlags_SpanAvailWidth, ImVec2(min_w, label_size.y));
+ LogSetNextTextDecoration("", ">");
RenderText(text_pos, label);
if (icon_w > 0.0f)
RenderText(pos + ImVec2(offsets->OffsetIcon, 0.0f), icon);
@@ -8946,7 +9320,7 @@ bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled)
ImGuiLastItemData last_item_in_parent = g.LastItemData;
SetNextWindowPos(popup_pos, ImGuiCond_Always); // Note: misleading: the value will serve as reference for FindBestWindowPosForPopup(), not actual pos.
PushStyleVar(ImGuiStyleVar_ChildRounding, style.PopupRounding); // First level will use _PopupRounding, subsequent will use _ChildRounding
- menu_is_open = BeginPopupEx(id, window_flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
+ menu_is_open = BeginPopupMenuEx(id, label, window_flags); // menu_is_open may be 'false' when the popup is completely clipped (e.g. zero size display)
PopStyleVar();
if (menu_is_open)
{
@@ -9040,7 +9414,7 @@ bool ImGui::MenuItemEx(const char* label, const char* icon, const char* shortcut
{
// Menu item inside a vertical menu
// (In a typical menu window where all items are BeginMenu() or MenuItem() calls, extra_w will always be 0.0f.
- // Only when they are other items sticking out we're going to add spacing, yet only register minimum width into the layout system.
+ // Only when they are other items sticking out we're going to add spacing, yet only register minimum width into the layout system.)
float icon_w = (icon && icon[0]) ? CalcTextSize(icon, NULL).x : 0.0f;
float shortcut_w = (shortcut && shortcut[0]) ? CalcTextSize(shortcut, NULL).x : 0.0f;
float checkmark_w = IM_TRUNC(g.FontSize * 1.20f);
@@ -9055,6 +9429,7 @@ bool ImGui::MenuItemEx(const char* label, const char* icon, const char* shortcut
if (shortcut_w > 0.0f)
{
PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]);
+ LogSetNextTextDecoration("(", ")");
RenderText(pos + ImVec2(offsets->OffsetShortcut + stretch_w, 0.0f), shortcut, NULL, false);
PopStyleColor();
}
@@ -9119,6 +9494,7 @@ struct ImGuiTabBarSection
{
int TabCount; // Number of tabs in this section.
float Width; // Sum of width of tabs in this section (after shrinking down)
+ float WidthAfterShrinkMinWidth;
float Spacing; // Horizontal spacing at the end of the section.
ImGuiTabBarSection() { memset(this, 0, sizeof(*this)); }
@@ -9179,6 +9555,19 @@ static ImGuiPtrOrIndex GetTabBarRefFromTabBar(ImGuiTabBar* tab_bar)
return ImGuiPtrOrIndex(tab_bar);
}
+ImGuiTabBar* ImGui::TabBarFindByID(ImGuiID id)
+{
+ ImGuiContext& g = *GImGui;
+ return g.TabBars.GetByKey(id);
+}
+
+// Remove TabBar data (currently only used by TestEngine)
+void ImGui::TabBarRemove(ImGuiTabBar* tab_bar)
+{
+ ImGuiContext& g = *GImGui;
+ g.TabBars.Remove(tab_bar->ID, tab_bar);
+}
+
bool ImGui::BeginTabBar(const char* str_id, ImGuiTabBarFlags flags)
{
ImGuiContext& g = *GImGui;
@@ -9190,8 +9579,8 @@ bool ImGui::BeginTabBar(const char* str_id, ImGuiTabBarFlags flags)
ImGuiTabBar* tab_bar = g.TabBars.GetOrAddByKey(id);
ImRect tab_bar_bb = ImRect(window->DC.CursorPos.x, window->DC.CursorPos.y, window->WorkRect.Max.x, window->DC.CursorPos.y + g.FontSize + g.Style.FramePadding.y * 2);
tab_bar->ID = id;
- tab_bar->SeparatorMinX = tab_bar->BarRect.Min.x - IM_TRUNC(window->WindowPadding.x * 0.5f);
- tab_bar->SeparatorMaxX = tab_bar->BarRect.Max.x + IM_TRUNC(window->WindowPadding.x * 0.5f);
+ tab_bar->SeparatorMinX = tab_bar_bb.Min.x - IM_TRUNC(window->WindowPadding.x * 0.5f);
+ tab_bar->SeparatorMaxX = tab_bar_bb.Max.x + IM_TRUNC(window->WindowPadding.x * 0.5f);
//if (g.NavWindow && IsWindowChildOf(g.NavWindow, window, false, false))
flags |= ImGuiTabBarFlags_IsFocused;
return BeginTabBarEx(tab_bar, tab_bar_bb, flags);
@@ -9312,6 +9701,10 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar)
ImGuiContext& g = *GImGui;
tab_bar->WantLayout = false;
+ // Track selected tab when resizing our parent down
+ const bool scroll_to_selected_tab = (tab_bar->BarRectPrevWidth > tab_bar->BarRect.GetWidth());
+ tab_bar->BarRectPrevWidth = tab_bar->BarRect.GetWidth();
+
// Garbage collect by compacting list
// Detect if we need to sort out tab list (e.g. in rare case where a tab changed section)
int tab_dst_n = 0;
@@ -9388,6 +9781,9 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar)
int shrink_buffer_indexes[3] = { 0, sections[0].TabCount + sections[2].TabCount, sections[0].TabCount };
g.ShrinkWidthBuffer.resize(tab_bar->Tabs.Size);
+ // Minimum shrink width
+ const float shrink_min_width = (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyMixed) ? g.Style.TabMinWidthShrink : 1.0f;
+
// Compute ideal tabs widths + store them into shrink buffer
ImGuiTabItem* most_recently_selected_tab = NULL;
int curr_section_n = -1;
@@ -9410,10 +9806,13 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar)
const char* tab_name = TabBarGetTabName(tab_bar, tab);
const bool has_close_button_or_unsaved_marker = (tab->Flags & ImGuiTabItemFlags_NoCloseButton) == 0 || (tab->Flags & ImGuiTabItemFlags_UnsavedDocument);
tab->ContentWidth = (tab->RequestedWidth >= 0.0f) ? tab->RequestedWidth : TabItemCalcSize(tab_name, has_close_button_or_unsaved_marker).x;
+ if ((tab->Flags & ImGuiTabItemFlags_Button) == 0)
+ tab->ContentWidth = ImMax(tab->ContentWidth, g.Style.TabMinWidthBase);
int section_n = TabItemGetSectionIdx(tab);
ImGuiTabBarSection* section = &sections[section_n];
section->Width += tab->ContentWidth + (section_n == curr_section_n ? g.Style.ItemInnerSpacing.x : 0.0f);
+ section->WidthAfterShrinkMinWidth += ImMin(tab->ContentWidth, shrink_min_width) + (section_n == curr_section_n ? g.Style.ItemInnerSpacing.x : 0.0f);
curr_section_n = section_n;
// Store data so we can build an array sorted by width if we need to shrink tabs down
@@ -9425,19 +9824,28 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar)
}
// Compute total ideal width (used for e.g. auto-resizing a window)
+ float width_all_tabs_after_min_width_shrink = 0.0f;
tab_bar->WidthAllTabsIdeal = 0.0f;
for (int section_n = 0; section_n < 3; section_n++)
+ {
tab_bar->WidthAllTabsIdeal += sections[section_n].Width + sections[section_n].Spacing;
+ width_all_tabs_after_min_width_shrink += sections[section_n].WidthAfterShrinkMinWidth + sections[section_n].Spacing;
+ }
// Horizontal scrolling buttons
- // (note that TabBarScrollButtons() will alter BarRect.Max.x)
- if ((tab_bar->WidthAllTabsIdeal > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll))
+ // Important: note that TabBarScrollButtons() will alter BarRect.Max.x.
+ const bool can_scroll = (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll) || (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyMixed);
+ const float width_all_tabs_to_use_for_scroll = (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll) ? tab_bar->WidthAllTabs : width_all_tabs_after_min_width_shrink;
+ tab_bar->ScrollButtonEnabled = ((width_all_tabs_to_use_for_scroll > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && can_scroll);
+ if (tab_bar->ScrollButtonEnabled)
if (ImGuiTabItem* scroll_and_select_tab = TabBarScrollingButtons(tab_bar))
{
scroll_to_tab_id = scroll_and_select_tab->ID;
if ((scroll_and_select_tab->Flags & ImGuiTabItemFlags_Button) == 0)
tab_bar->SelectedTabId = scroll_to_tab_id;
}
+ if (scroll_to_tab_id == 0 && scroll_to_selected_tab)
+ scroll_to_tab_id = tab_bar->SelectedTabId;
// Shrink widths if full tabs don't fit in their allocated space
float section_0_w = sections[0].Width + sections[0].Spacing;
@@ -9451,11 +9859,12 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar)
width_excess = (section_0_w + section_2_w) - tab_bar->BarRect.GetWidth(); // Excess used to shrink leading/trailing section
// With ImGuiTabBarFlags_FittingPolicyScroll policy, we will only shrink leading/trailing if the central section is not visible anymore
- if (width_excess >= 1.0f && ((tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyResizeDown) || !central_section_is_visible))
+ const bool can_shrink = (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyShrink) || (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyMixed);
+ if (width_excess >= 1.0f && (can_shrink || !central_section_is_visible))
{
int shrink_data_count = (central_section_is_visible ? sections[1].TabCount : sections[0].TabCount + sections[2].TabCount);
int shrink_data_offset = (central_section_is_visible ? sections[0].TabCount + sections[2].TabCount : 0);
- ShrinkWidths(g.ShrinkWidthBuffer.Data + shrink_data_offset, shrink_data_count, width_excess);
+ ShrinkWidths(g.ShrinkWidthBuffer.Data + shrink_data_offset, shrink_data_count, width_excess, shrink_min_width);
// Apply shrunk values into tabs and sections
for (int tab_n = shrink_data_offset; tab_n < shrink_data_offset + shrink_data_count; tab_n++)
@@ -9498,7 +9907,8 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar)
tab_bar->TabsNames.Buf.resize(0);
// If we have lost the selected tab, select the next most recently active one
- if (found_selected_tab_id == false)
+ const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount);
+ if (found_selected_tab_id == false && !tab_bar_appearing)
tab_bar->SelectedTabId = 0;
if (tab_bar->SelectedTabId == 0 && tab_bar->NextSelectedTabId == 0 && most_recently_selected_tab != NULL)
scroll_to_tab_id = tab_bar->SelectedTabId = most_recently_selected_tab->ID;
@@ -9514,7 +9924,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar)
// Apply request requests
if (scroll_to_tab_id != 0)
TabBarScrollToTab(tab_bar, scroll_to_tab_id, sections);
- else if ((tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll) && IsMouseHoveringRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, true) && IsWindowContentHoverable(g.CurrentWindow))
+ else if (tab_bar->ScrollButtonEnabled && IsMouseHoveringRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, true) && IsWindowContentHoverable(g.CurrentWindow))
{
const float wheel = g.IO.MouseWheelRequestAxisSwap ? g.IO.MouseWheel : g.IO.MouseWheelH;
const ImGuiKey wheel_key = g.IO.MouseWheelRequestAxisSwap ? ImGuiKey_MouseWheelY : ImGuiKey_MouseWheelX;
@@ -9825,7 +10235,7 @@ static ImGuiTabItem* ImGui::TabBarScrollingButtons(ImGuiTabBar* tab_bar)
PushStyleColor(ImGuiCol_Text, arrow_col);
PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));
- PushItemFlag(ImGuiItemFlags_ButtonRepeat, true);
+ PushItemFlag(ImGuiItemFlags_ButtonRepeat | ImGuiItemFlags_NoNav, true);
const float backup_repeat_delay = g.IO.KeyRepeatDelay;
const float backup_repeat_rate = g.IO.KeyRepeatRate;
g.IO.KeyRepeatDelay = 0.250f;
@@ -9935,7 +10345,7 @@ bool ImGui::BeginTabItem(const char* label, bool* p_open, ImGuiTabItemFlags f
IM_ASSERT_USER_ERROR(tab_bar, "Needs to be called between BeginTabBar() and EndTabBar()!");
return false;
}
- IM_ASSERT((flags & ImGuiTabItemFlags_Button) == 0); // BeginTabItem() Can't be used with button flags, use TabItemButton() instead!
+ IM_ASSERT((flags & ImGuiTabItemFlags_Button) == 0); // BeginTabItem() Can't be used with button flags, use TabItemButton() instead!
bool ret = TabItemEx(tab_bar, label, p_open, flags, NULL);
if (ret && !(flags & ImGuiTabItemFlags_NoPushId))
@@ -9981,6 +10391,23 @@ bool ImGui::TabItemButton(const char* label, ImGuiTabItemFlags flags)
return TabItemEx(tab_bar, label, NULL, flags | ImGuiTabItemFlags_Button | ImGuiTabItemFlags_NoReorder, NULL);
}
+void ImGui::TabItemSpacing(const char* str_id, ImGuiTabItemFlags flags, float width)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ if (window->SkipItems)
+ return;
+
+ ImGuiTabBar* tab_bar = g.CurrentTabBar;
+ if (tab_bar == NULL)
+ {
+ IM_ASSERT_USER_ERROR(tab_bar != NULL, "Needs to be called between BeginTabBar() and EndTabBar()!");
+ return;
+ }
+ SetNextItemWidth(width);
+ TabItemEx(tab_bar, str_id, NULL, flags | ImGuiTabItemFlags_Button | ImGuiTabItemFlags_NoReorder | ImGuiTabItemFlags_Invisible, NULL);
+}
+
bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags, ImGuiWindow* docked_window)
{
// Layout whole tab bar if not already done
@@ -10057,7 +10484,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open,
else
{
tab->NameOffset = (ImS32)tab_bar->TabsNames.size();
- tab_bar->TabsNames.append(label, label + strlen(label) + 1);
+ tab_bar->TabsNames.append(label, label + ImStrlen(label) + 1);
}
// Update selected tab
@@ -10128,8 +10555,11 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open,
ImGuiButtonFlags button_flags = ((is_tab_button ? ImGuiButtonFlags_PressedOnClickRelease : ImGuiButtonFlags_PressedOnClick) | ImGuiButtonFlags_AllowOverlap);
if (g.DragDropActive && !g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW)) // FIXME: May be an opt-in property of the payload to disable this
button_flags |= ImGuiButtonFlags_PressedOnDragDropHold;
- bool hovered, held;
- bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags);
+ bool hovered, held, pressed;
+ if (flags & ImGuiTabItemFlags_Invisible)
+ hovered = held = pressed = false;
+ else
+ pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags);
if (pressed && !is_tab_button)
TabBarQueueFocus(tab_bar, tab);
@@ -10214,57 +10644,71 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open,
#endif
// Render tab shape
- ImDrawList* display_draw_list = window->DrawList;
- const ImU32 tab_col = GetColorU32((held || hovered) ? ImGuiCol_TabHovered : tab_contents_visible ? (tab_bar_focused ? ImGuiCol_TabSelected : ImGuiCol_TabDimmedSelected) : (tab_bar_focused ? ImGuiCol_Tab : ImGuiCol_TabDimmed));
- TabItemBackground(display_draw_list, bb, flags, tab_col);
- if (tab_contents_visible && (tab_bar->Flags & ImGuiTabBarFlags_DrawSelectedOverline) && style.TabBarOverlineSize > 0.0f)
+ const bool is_visible = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) && !(flags & ImGuiTabItemFlags_Invisible);
+ if (is_visible)
{
- float x_offset = IM_TRUNC(0.4f * style.TabRounding);
- if (x_offset < 2.0f * g.CurrentDpiScale)
- x_offset = 0.0f;
- float y_offset = 1.0f * g.CurrentDpiScale;
- display_draw_list->AddLine(bb.GetTL() + ImVec2(x_offset, y_offset), bb.GetTR() + ImVec2(-x_offset, y_offset), GetColorU32(tab_bar_focused ? ImGuiCol_TabSelectedOverline : ImGuiCol_TabDimmedSelectedOverline), style.TabBarOverlineSize);
- }
- RenderNavCursor(bb, id);
+ ImDrawList* display_draw_list = window->DrawList;
+ const ImU32 tab_col = GetColorU32((held || hovered) ? ImGuiCol_TabHovered : tab_contents_visible ? (tab_bar_focused ? ImGuiCol_TabSelected : ImGuiCol_TabDimmedSelected) : (tab_bar_focused ? ImGuiCol_Tab : ImGuiCol_TabDimmed));
+ TabItemBackground(display_draw_list, bb, flags, tab_col);
+ if (tab_contents_visible && (tab_bar->Flags & ImGuiTabBarFlags_DrawSelectedOverline) && style.TabBarOverlineSize > 0.0f)
+ {
+ // Might be moved to TabItemBackground() ?
+ ImVec2 tl = bb.GetTL() + ImVec2(0, 1.0f * g.CurrentDpiScale);
+ ImVec2 tr = bb.GetTR() + ImVec2(0, 1.0f * g.CurrentDpiScale);
+ ImU32 overline_col = GetColorU32(tab_bar_focused ? ImGuiCol_TabSelectedOverline : ImGuiCol_TabDimmedSelectedOverline);
+ if (style.TabRounding > 0.0f)
+ {
+ float rounding = style.TabRounding;
+ display_draw_list->PathArcToFast(tl + ImVec2(+rounding, +rounding), rounding, 7, 9);
+ display_draw_list->PathArcToFast(tr + ImVec2(-rounding, +rounding), rounding, 9, 11);
+ display_draw_list->PathStroke(overline_col, 0, style.TabBarOverlineSize);
+ }
+ else
+ {
+ display_draw_list->AddLine(tl - ImVec2(0.5f, 0.5f), tr - ImVec2(0.5f, 0.5f), overline_col, style.TabBarOverlineSize);
+ }
+ }
+ RenderNavCursor(bb, id);
- // Select with right mouse button. This is so the common idiom for context menu automatically highlight the current widget.
- const bool hovered_unblocked = IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup);
- if (tab_bar->SelectedTabId != tab->ID && hovered_unblocked && (IsMouseClicked(1) || IsMouseReleased(1)) && !is_tab_button)
- TabBarQueueFocus(tab_bar, tab);
+ // Select with right mouse button. This is so the common idiom for context menu automatically highlight the current widget.
+ const bool hovered_unblocked = IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup);
+ if (tab_bar->SelectedTabId != tab->ID && hovered_unblocked && (IsMouseClicked(1) || IsMouseReleased(1)) && !is_tab_button)
+ TabBarQueueFocus(tab_bar, tab);
- if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
- flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
+ if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
+ flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
- // Render tab label, process close button
- const ImGuiID close_button_id = p_open ? GetIDWithSeed("#CLOSE", NULL, docked_window ? docked_window->ID : id) : 0;
- bool just_closed;
- bool text_clipped;
- TabItemLabelAndCloseButton(display_draw_list, bb, tab_just_unsaved ? (flags & ~ImGuiTabItemFlags_UnsavedDocument) : flags, tab_bar->FramePadding, label, id, close_button_id, tab_contents_visible, &just_closed, &text_clipped);
- if (just_closed && p_open != NULL)
- {
- *p_open = false;
- TabBarCloseTab(tab_bar, tab);
- }
+ // Render tab label, process close button
+ const ImGuiID close_button_id = p_open ? GetIDWithSeed("#CLOSE", NULL, docked_window ? docked_window->ID : id) : 0;
+ bool just_closed;
+ bool text_clipped;
+ TabItemLabelAndCloseButton(display_draw_list, bb, tab_just_unsaved ? (flags & ~ImGuiTabItemFlags_UnsavedDocument) : flags, tab_bar->FramePadding, label, id, close_button_id, tab_contents_visible, &just_closed, &text_clipped);
+ if (just_closed && p_open != NULL)
+ {
+ *p_open = false;
+ TabBarCloseTab(tab_bar, tab);
+ }
+
+ // Forward Hovered state so IsItemHovered() after Begin() can work (even though we are technically hovering our parent)
+ // That state is copied to window->DockTabItemStatusFlags by our caller.
+ if (docked_window && (hovered || g.HoveredId == close_button_id))
+ g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
- // Forward Hovered state so IsItemHovered() after Begin() can work (even though we are technically hovering our parent)
- // That state is copied to window->DockTabItemStatusFlags by our caller.
- if (docked_window && (hovered || g.HoveredId == close_button_id))
- g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
+ // Tooltip
+ // (Won't work over the close button because ItemOverlap systems messes up with HoveredIdTimer-> seems ok)
+ // (We test IsItemHovered() to discard e.g. when another item is active or drag and drop over the tab bar, which g.HoveredId ignores)
+ // FIXME: This is a mess.
+ // FIXME: We may want disabled tab to still display the tooltip?
+ if (text_clipped && g.HoveredId == id && !held)
+ if (!(tab_bar->Flags & ImGuiTabBarFlags_NoTooltip) && !(tab->Flags & ImGuiTabItemFlags_NoTooltip))
+ SetItemTooltip("%.*s", (int)(FindRenderedTextEnd(label) - label), label);
+ }
// Restore main window position so user can draw there
if (want_clip_rect)
PopClipRect();
window->DC.CursorPos = backup_main_cursor_pos;
- // Tooltip
- // (Won't work over the close button because ItemOverlap systems messes up with HoveredIdTimer-> seems ok)
- // (We test IsItemHovered() to discard e.g. when another item is active or drag and drop over the tab bar, which g.HoveredId ignores)
- // FIXME: This is a mess.
- // FIXME: We may want disabled tab to still display the tooltip?
- if (text_clipped && g.HoveredId == id && !held)
- if (!(tab_bar->Flags & ImGuiTabBarFlags_NoTooltip) && !(tab->Flags & ImGuiTabItemFlags_NoTooltip))
- SetItemTooltip("%.*s", (int)(FindRenderedTextEnd(label) - label), label);
-
IM_ASSERT(!is_tab_button || !(tab_bar->SelectedTabId == tab->ID && is_tab_button)); // TabItemButton should not be selected
if (is_tab_button)
return pressed;
@@ -10363,13 +10807,12 @@ void ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb,
#endif
// Render text label (with clipping + alpha gradient) + unsaved marker
- ImRect text_pixel_clip_bb(bb.Min.x + frame_padding.x, bb.Min.y + frame_padding.y, bb.Max.x - frame_padding.x, bb.Max.y);
- ImRect text_ellipsis_clip_bb = text_pixel_clip_bb;
+ ImRect text_ellipsis_clip_bb(bb.Min.x + frame_padding.x, bb.Min.y + frame_padding.y, bb.Max.x - frame_padding.x, bb.Max.y);
// Return clipped state ignoring the close button
if (out_text_clipped)
{
- *out_text_clipped = (text_ellipsis_clip_bb.Min.x + label_size.x) > text_pixel_clip_bb.Max.x;
+ *out_text_clipped = (text_ellipsis_clip_bb.Min.x + label_size.x) > text_ellipsis_clip_bb.Max.x;
//draw_list->AddCircle(text_ellipsis_clip_bb.Min, 3.0f, *out_text_clipped ? IM_COL32(255, 0, 0, 255) : IM_COL32(0, 255, 0, 255));
}
@@ -10383,13 +10826,24 @@ void ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb,
// 'g.ActiveId==close_button_id' will be true when we are holding on the close button, in which case both hovered booleans are false
bool close_button_pressed = false;
bool close_button_visible = false;
+ bool is_hovered = g.HoveredId == tab_id || g.HoveredId == close_button_id || g.ActiveId == tab_id || g.ActiveId == close_button_id; // Any interaction account for this too.
+
if (close_button_id != 0)
- if (is_contents_visible || bb.GetWidth() >= ImMax(button_sz, g.Style.TabMinWidthForCloseButton))
- if (g.HoveredId == tab_id || g.HoveredId == close_button_id || g.ActiveId == tab_id || g.ActiveId == close_button_id)
- close_button_visible = true;
- bool unsaved_marker_visible = (flags & ImGuiTabItemFlags_UnsavedDocument) != 0 && (button_pos.x + button_sz <= bb.Max.x);
+ {
+ if (is_contents_visible)
+ close_button_visible = (g.Style.TabCloseButtonMinWidthSelected < 0.0f) ? true : (is_hovered && bb.GetWidth() >= ImMax(button_sz, g.Style.TabCloseButtonMinWidthSelected));
+ else
+ close_button_visible = (g.Style.TabCloseButtonMinWidthUnselected < 0.0f) ? true : (is_hovered && bb.GetWidth() >= ImMax(button_sz, g.Style.TabCloseButtonMinWidthUnselected));
+ }
- if (close_button_visible)
+ // When tabs/document is unsaved, the unsaved marker takes priority over the close button.
+ const bool unsaved_marker_visible = (flags & ImGuiTabItemFlags_UnsavedDocument) != 0 && (button_pos.x + button_sz <= bb.Max.x) && (!close_button_visible || !is_hovered);
+ if (unsaved_marker_visible)
+ {
+ const ImRect bullet_bb(button_pos, button_pos + ImVec2(button_sz, button_sz));
+ RenderBullet(draw_list, bullet_bb.GetCenter(), GetColorU32(ImGuiCol_Text));
+ }
+ else if (close_button_visible)
{
ImGuiLastItemData last_item_backup = g.LastItemData;
if (CloseButton(close_button_id, button_pos))
@@ -10397,26 +10851,29 @@ void ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb,
g.LastItemData = last_item_backup;
// Close with middle mouse button
- if (!(flags & ImGuiTabItemFlags_NoCloseWithMiddleMouseButton) && IsMouseClicked(2))
+ if (is_hovered && !(flags & ImGuiTabItemFlags_NoCloseWithMiddleMouseButton) && IsMouseClicked(2))
close_button_pressed = true;
}
- else if (unsaved_marker_visible)
- {
- const ImRect bullet_bb(button_pos, button_pos + ImVec2(button_sz, button_sz));
- RenderBullet(draw_list, bullet_bb.GetCenter(), GetColorU32(ImGuiCol_Text));
- }
// This is all rather complicated
// (the main idea is that because the close button only appears on hover, we don't want it to alter the ellipsis position)
// FIXME: if FramePadding is noticeably large, ellipsis_max_x will be wrong here (e.g. #3497), maybe for consistency that parameter of RenderTextEllipsis() shouldn't exist..
- float ellipsis_max_x = close_button_visible ? text_pixel_clip_bb.Max.x : bb.Max.x - 1.0f;
+ float ellipsis_max_x = text_ellipsis_clip_bb.Max.x;
if (close_button_visible || unsaved_marker_visible)
{
- text_pixel_clip_bb.Max.x -= close_button_visible ? (button_sz) : (button_sz * 0.80f);
- text_ellipsis_clip_bb.Max.x -= unsaved_marker_visible ? (button_sz * 0.80f) : 0.0f;
- ellipsis_max_x = text_pixel_clip_bb.Max.x;
+ const bool visible_without_hover = unsaved_marker_visible || (is_contents_visible ? g.Style.TabCloseButtonMinWidthSelected : g.Style.TabCloseButtonMinWidthUnselected) < 0.0f;
+ if (visible_without_hover)
+ {
+ text_ellipsis_clip_bb.Max.x -= button_sz * 0.90f;
+ ellipsis_max_x -= button_sz * 0.90f;
+ }
+ else
+ {
+ text_ellipsis_clip_bb.Max.x -= button_sz * 1.00f;
+ }
}
- RenderTextEllipsis(draw_list, text_ellipsis_clip_bb.Min, text_ellipsis_clip_bb.Max, text_pixel_clip_bb.Max.x, ellipsis_max_x, label, NULL, &label_size);
+ LogSetNextTextDecoration("/", "\\");
+ RenderTextEllipsis(draw_list, text_ellipsis_clip_bb.Min, text_ellipsis_clip_bb.Max, ellipsis_max_x, label, NULL, &label_size);
#if 0
if (!is_contents_visible)
diff --git a/source/code/Libs/imgui/imstb_textedit.h b/source/code/Libs/imgui/imstb_textedit.h index b7a761c..c41078c 100644 --- a/source/code/Libs/imgui/imstb_textedit.h +++ b/source/code/Libs/imgui/imstb_textedit.h
@@ -141,6 +141,7 @@
// with previous char)
// STB_TEXTEDIT_KEYTOTEXT(k) maps a keyboard input to an insertable character
// (return type is int, -1 means not valid to insert)
+// (not supported if you want to use UTF-8, see below)
// STB_TEXTEDIT_GETCHAR(obj,i) returns the i'th character of obj, 0-based
// STB_TEXTEDIT_NEWLINE the character returned by _GETCHAR() we recognize
// as manually wordwrapping for end-of-line positioning
@@ -178,6 +179,13 @@
// 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
//
+// To support UTF-8:
+//
+// STB_TEXTEDIT_GETPREVCHARINDEX returns index of previous character
+// STB_TEXTEDIT_GETNEXTCHARINDEX returns index of next character
+// Do NOT define STB_TEXTEDIT_KEYTOTEXT.
+// Instead, call stb_textedit_text() directly for text contents.
+//
// 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,
@@ -250,8 +258,10 @@
// if the STB_TEXTEDIT_KEYTOTEXT function is defined, selected keys are
// transformed into text and stb_textedit_text() is automatically called.
//
-// text: [DEAR IMGUI] added 2024-09
-// call this to text inputs sent to the textfield.
+// text: (added 2025)
+// call this to directly send text input the textfield, which is required
+// for UTF-8 support, because stb_textedit_key() + STB_TEXTEDIT_KEYTOTEXT()
+// cannot infer text length.
//
//
// When rendering, you can read the cursor position and selection state from
@@ -400,6 +410,16 @@ typedef struct
#define IMSTB_TEXTEDIT_memmove memmove
#endif
+// [DEAR IMGUI]
+// Functions must be implemented for UTF8 support
+// Code in this file that uses those functions is modified for [DEAR IMGUI] and deviates from the original stb_textedit.
+// There is not necessarily a '[DEAR IMGUI]' at the usage sites.
+#ifndef IMSTB_TEXTEDIT_GETPREVCHARINDEX
+#define IMSTB_TEXTEDIT_GETPREVCHARINDEX(OBJ, IDX) ((IDX) - 1)
+#endif
+#ifndef IMSTB_TEXTEDIT_GETNEXTCHARINDEX
+#define IMSTB_TEXTEDIT_GETNEXTCHARINDEX(OBJ, IDX) ((IDX) + 1)
+#endif
/////////////////////////////////////////////////////////////////////////////
//
@@ -407,7 +427,7 @@ typedef struct
//
// traverse the layout to locate the nearest character to a display position
-static int stb_text_locate_coord(IMSTB_TEXTEDIT_STRING *str, float x, float y)
+static int stb_text_locate_coord(IMSTB_TEXTEDIT_STRING *str, float x, float y, int* out_side_on_line)
{
StbTexteditRow r;
int n = STB_TEXTEDIT_STRINGLEN(str);
@@ -417,6 +437,7 @@ static int stb_text_locate_coord(IMSTB_TEXTEDIT_STRING *str, float x, float y)
r.x0 = r.x1 = 0;
r.ymin = r.ymax = 0;
r.num_chars = 0;
+ *out_side_on_line = 0;
// search rows to find one that straddles 'y'
while (i < n) {
@@ -436,7 +457,10 @@ static int stb_text_locate_coord(IMSTB_TEXTEDIT_STRING *str, float x, float y)
// below all text, return 'after' last character
if (i >= n)
+ {
+ *out_side_on_line = 1;
return n;
+ }
// check if it's before the beginning of the line
if (x < r.x0)
@@ -449,6 +473,7 @@ static int stb_text_locate_coord(IMSTB_TEXTEDIT_STRING *str, float x, float y)
for (k=0; k < r.num_chars; k = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, i + k) - i) {
float w = STB_TEXTEDIT_GETWIDTH(str, i, k);
if (x < prev_x+w) {
+ *out_side_on_line = (k == 0) ? 0 : 1;
if (x < prev_x+w/2)
return k+i;
else
@@ -460,6 +485,7 @@ static int stb_text_locate_coord(IMSTB_TEXTEDIT_STRING *str, float x, float y)
}
// if the last character is a newline, return that. otherwise return 'after' the last character
+ *out_side_on_line = 1;
if (STB_TEXTEDIT_GETCHAR(str, i+r.num_chars-1) == STB_TEXTEDIT_NEWLINE)
return i+r.num_chars-1;
else
@@ -471,6 +497,7 @@ static void stb_textedit_click(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *st
{
// In single-line mode, just always make y = 0. This lets the drag keep working if the mouse
// goes off the top or bottom of the text
+ int side_on_line;
if( state->single_line )
{
StbTexteditRow r;
@@ -478,16 +505,18 @@ static void stb_textedit_click(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *st
y = r.ymin;
}
- state->cursor = stb_text_locate_coord(str, x, y);
+ state->cursor = stb_text_locate_coord(str, x, y, &side_on_line);
state->select_start = state->cursor;
state->select_end = state->cursor;
state->has_preferred_x = 0;
+ str->LastMoveDirectionLR = (ImS8)(side_on_line ? ImGuiDir_Right : ImGuiDir_Left);
}
// API drag: on mouse drag, move the cursor and selection endpoint to the clicked location
static void stb_textedit_drag(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)
{
int p = 0;
+ int side_on_line;
// In single-line mode, just always make y = 0. This lets the drag keep working if the mouse
// goes off the top or bottom of the text
@@ -501,8 +530,9 @@ static void stb_textedit_drag(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *sta
if (state->select_start == state->select_end)
state->select_start = state->cursor;
- p = stb_text_locate_coord(str, x, y);
+ p = stb_text_locate_coord(str, x, y, &side_on_line);
state->cursor = state->select_end = p;
+ str->LastMoveDirectionLR = (ImS8)(side_on_line ? ImGuiDir_Right : ImGuiDir_Left);
}
/////////////////////////////////////////////////////////////////////////////
@@ -552,6 +582,8 @@ static void stb_textedit_find_charpos(StbFindState *find, IMSTB_TEXTEDIT_STRING
STB_TEXTEDIT_LAYOUTROW(&r, str, i);
if (n < i + r.num_chars)
break;
+ if (str->LastMoveDirectionLR == ImGuiDir_Right && str->Stb->cursor > 0 && str->Stb->cursor == i + r.num_chars && STB_TEXTEDIT_GETCHAR(str, i + r.num_chars - 1) != STB_TEXTEDIT_NEWLINE) // [DEAR IMGUI] Wrapping point handling
+ break;
if (i + r.num_chars == z && z > 0 && STB_TEXTEDIT_GETCHAR(str, z - 1) != STB_TEXTEDIT_NEWLINE) // [DEAR IMGUI] special handling for last line
break; // [DEAR IMGUI]
prev_start = i;
@@ -648,15 +680,33 @@ static void stb_textedit_move_to_last(IMSTB_TEXTEDIT_STRING *str, STB_TexteditSt
}
}
-// [DEAR IMGUI]
-// Functions must be implemented for UTF8 support
-// Code in this file that uses those functions is modified for [DEAR IMGUI] and deviates from the original stb_textedit.
-// There is not necessarily a '[DEAR IMGUI]' at the usage sites.
-#ifndef IMSTB_TEXTEDIT_GETPREVCHARINDEX
-#define IMSTB_TEXTEDIT_GETPREVCHARINDEX(obj, idx) (idx - 1)
+// [DEAR IMGUI] Extracted this function so we can more easily add support for word-wrapping.
+#ifndef STB_TEXTEDIT_MOVELINESTART
+static int stb_textedit_move_line_start(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, int cursor)
+{
+ if (state->single_line)
+ return 0;
+ while (cursor > 0) {
+ int prev = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, cursor);
+ if (STB_TEXTEDIT_GETCHAR(str, prev) == STB_TEXTEDIT_NEWLINE)
+ break;
+ cursor = prev;
+ }
+ return cursor;
+}
+#define STB_TEXTEDIT_MOVELINESTART stb_textedit_move_line_start
#endif
-#ifndef IMSTB_TEXTEDIT_GETNEXTCHARINDEX
-#define IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx) (idx + 1)
+#ifndef STB_TEXTEDIT_MOVELINEEND
+static int stb_textedit_move_line_end(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, int cursor)
+{
+ int n = STB_TEXTEDIT_STRINGLEN(str);
+ if (state->single_line)
+ return n;
+ while (cursor < n && STB_TEXTEDIT_GETCHAR(str, cursor) != STB_TEXTEDIT_NEWLINE)
+ cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, cursor);
+ return cursor;
+}
+#define STB_TEXTEDIT_MOVELINEEND stb_textedit_move_line_end
#endif
#ifdef STB_TEXTEDIT_IS_SPACE
@@ -668,9 +718,9 @@ static int is_word_boundary( IMSTB_TEXTEDIT_STRING *str, int idx )
#ifndef STB_TEXTEDIT_MOVEWORDLEFT
static int stb_textedit_move_to_word_previous( IMSTB_TEXTEDIT_STRING *str, int c )
{
- --c; // always move at least one character
- while( c >= 0 && !is_word_boundary( str, c ) )
- --c;
+ c = IMSTB_TEXTEDIT_GETPREVCHARINDEX( str, c ); // always move at least one character
+ while (c >= 0 && !is_word_boundary(str, c))
+ c = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, c);
if( c < 0 )
c = 0;
@@ -684,9 +734,9 @@ static int stb_textedit_move_to_word_previous( IMSTB_TEXTEDIT_STRING *str, int c
static int stb_textedit_move_to_word_next( IMSTB_TEXTEDIT_STRING *str, int c )
{
const int len = STB_TEXTEDIT_STRINGLEN(str);
- ++c; // always move at least one character
+ c = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, c); // always move at least one character
while( c < len && !is_word_boundary( str, c ) )
- ++c;
+ c = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, c);
if( c > len )
c = len;
@@ -739,6 +789,7 @@ static int stb_textedit_paste_internal(IMSTB_TEXTEDIT_STRING *str, STB_TexteditS
#define STB_TEXTEDIT_KEYTYPE int
#endif
+// API key: process text input
// [DEAR IMGUI] Added stb_textedit_text(), extracted out and called by stb_textedit_key() for backward compatibility.
static void stb_textedit_text(IMSTB_TEXTEDIT_STRING* str, STB_TexteditState* state, const IMSTB_TEXTEDIT_CHARTYPE* text, int text_len)
{
@@ -753,8 +804,7 @@ static void stb_textedit_text(IMSTB_TEXTEDIT_STRING* str, STB_TexteditState* sta
state->cursor += text_len;
state->has_preferred_x = 0;
}
- }
- else {
+ } else {
stb_textedit_delete_selection(str, state); // implicitly clamps
if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, text_len)) {
stb_text_makeundo_insert(state, state->cursor, text_len);
@@ -771,6 +821,7 @@ retry:
switch (key) {
default: {
#ifdef STB_TEXTEDIT_KEYTOTEXT
+ // This is not suitable for UTF-8 support.
int c = STB_TEXTEDIT_KEYTOTEXT(key);
if (c > 0) {
IMSTB_TEXTEDIT_CHARTYPE ch = (IMSTB_TEXTEDIT_CHARTYPE)c;
@@ -911,15 +962,16 @@ retry:
// [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;
+ //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;
- for (i=0; i < row.num_chars; ++i) {
+ for (i=0; i < row.num_chars; ) {
float dx = STB_TEXTEDIT_GETWIDTH(str, start, i);
+ int next = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor);
#ifdef IMSTB_TEXTEDIT_GETWIDTH_NEWLINE
if (dx == IMSTB_TEXTEDIT_GETWIDTH_NEWLINE)
break;
@@ -927,10 +979,13 @@ retry:
x += dx;
if (x > goal_x)
break;
- state->cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor);
+ i += next - state->cursor;
+ state->cursor = next;
}
stb_textedit_clamp(str, state);
+ if (state->cursor == find.first_char + find.length)
+ str->LastMoveDirectionLR = ImGuiDir_Left;
state->has_preferred_x = 1;
state->preferred_x = goal_x;
@@ -980,8 +1035,9 @@ retry:
state->cursor = find.prev_first;
STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor);
x = row.x0;
- for (i=0; i < row.num_chars; ++i) {
+ for (i=0; i < row.num_chars; ) {
float dx = STB_TEXTEDIT_GETWIDTH(str, find.prev_first, i);
+ int next = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor);
#ifdef IMSTB_TEXTEDIT_GETWIDTH_NEWLINE
if (dx == IMSTB_TEXTEDIT_GETWIDTH_NEWLINE)
break;
@@ -989,10 +1045,15 @@ retry:
x += dx;
if (x > goal_x)
break;
- state->cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor);
+ i += next - state->cursor;
+ state->cursor = next;
}
stb_textedit_clamp(str, state);
+ if (state->cursor == find.first_char)
+ str->LastMoveDirectionLR = ImGuiDir_Right;
+ else if (state->cursor == find.prev_first)
+ str->LastMoveDirectionLR = ImGuiDir_Left;
state->has_preferred_x = 1;
state->preferred_x = goal_x;
@@ -1002,10 +1063,15 @@ retry:
// 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;
+ while (prev_scan > 0)
+ {
+ int prev = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, prev_scan);
+ if (STB_TEXTEDIT_GETCHAR(str, prev) == STB_TEXTEDIT_NEWLINE)
+ break;
+ prev_scan = prev;
+ }
find.first_char = find.prev_first;
- find.prev_first = prev_scan;
+ find.prev_first = STB_TEXTEDIT_MOVELINESTART(str, state, prev_scan);
}
break;
}
@@ -1079,10 +1145,7 @@ retry:
case STB_TEXTEDIT_K_LINESTART:
stb_textedit_clamp(str, state);
stb_textedit_move_to_first(state);
- if (state->single_line)
- state->cursor = 0;
- else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE)
- --state->cursor;
+ state->cursor = STB_TEXTEDIT_MOVELINESTART(str, state, state->cursor);
state->has_preferred_x = 0;
break;
@@ -1090,13 +1153,9 @@ retry:
case STB_TEXTEDIT_K_LINEEND2:
#endif
case STB_TEXTEDIT_K_LINEEND: {
- int n = STB_TEXTEDIT_STRINGLEN(str);
stb_textedit_clamp(str, state);
- stb_textedit_move_to_first(state);
- if (state->single_line)
- state->cursor = n;
- else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE)
- ++state->cursor;
+ stb_textedit_move_to_last(str, state);
+ state->cursor = STB_TEXTEDIT_MOVELINEEND(str, state, state->cursor);
state->has_preferred_x = 0;
break;
}
@@ -1107,10 +1166,7 @@ retry:
case STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT:
stb_textedit_clamp(str, state);
stb_textedit_prep_selection_at_cursor(state);
- if (state->single_line)
- state->cursor = 0;
- else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE)
- --state->cursor;
+ state->cursor = STB_TEXTEDIT_MOVELINESTART(str, state, state->cursor);
state->select_end = state->cursor;
state->has_preferred_x = 0;
break;
@@ -1119,13 +1175,9 @@ retry:
case STB_TEXTEDIT_K_LINEEND2 | STB_TEXTEDIT_K_SHIFT:
#endif
case STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_SHIFT: {
- int n = STB_TEXTEDIT_STRINGLEN(str);
stb_textedit_clamp(str, state);
stb_textedit_prep_selection_at_cursor(state);
- if (state->single_line)
- state->cursor = n;
- else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE)
- ++state->cursor;
+ state->cursor = STB_TEXTEDIT_MOVELINEEND(str, state, state->cursor);
state->select_end = state->cursor;
state->has_preferred_x = 0;
break;
diff --git a/source/code/Libs/imgui/imstb_truetype.h b/source/code/Libs/imgui/imstb_truetype.h index 976f09c..cf33289 100644 --- a/source/code/Libs/imgui/imstb_truetype.h +++ b/source/code/Libs/imgui/imstb_truetype.h
@@ -4516,8 +4516,8 @@ static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex
q2[0] = (float)x2;
q2[1] = (float)y2;
if (equal(q0,q1) || equal(q1,q2)) {
- x0 = (int)verts[i-1].x;
- y0 = (int)verts[i-1].y;
+ x0 = (int)verts[i-1].x; //-V1048
+ y0 = (int)verts[i-1].y; //-V1048
x1 = (int)verts[i ].x;
y1 = (int)verts[i ].y;
if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) {